text:
package alluxio.underfs.glusterfs;

import alluxio.Configuration;
import alluxio.PropertyKey;
import alluxio.underfs.UnderFileSystem;
import alluxio.underfs.UnderFileSystemFactory;
import alluxio.underfs.UnderFileSystemRegistry;

import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit tests for {@link GlusterFSUnderFileSystem}.
 */
public class GlusterFSUnderFileSystemFactoryTest {
  private String mMount = null;
  private String mVolume = null;

  /**
   * Sets the volume and the mount directory before a test runs.
   */
  @Before
  public final void before() {
    if (Configuration.containsKey(PropertyKey.UNDERFS_GLUSTERFS_MR_DIR)) {
      mMount = Configuration.get(PropertyKey.UNDERFS_GLUSTERFS_MR_DIR);
    }
    if (Configuration.containsKey(PropertyKey.UNDERFS_GLUSTERFS_VOLUMES)) {
      mVolume = Configuration.get(PropertyKey.UNDERFS_GLUSTERFS_VOLUMES);
    }
  }

  /**
   * Tests the {@link UnderFileSystem#create(String)} method.
   */
  @Test
  public void createGlusterFS() throws Exception {
    // Using Assume will mark the tests as skipped rather than passed which provides a truer
    // indication of their status
    Assume.assumeTrue(!StringUtils.isEmpty(mMount));
    Assume.assumeTrue(!StringUtils.isEmpty(mVolume));

    UnderFileSystem gfs = UnderFileSystem.Factory.get("glusterfs:///");
    Assert.assertNotNull(gfs.create("alluxio_test"));
  }

  /**
   * Tests the {@link UnderFileSystemRegistry#find(String)} method.
   */
  @Test
  public void factory() {
    UnderFileSystemFactory factory =
        UnderFileSystemRegistry.find("glusterfs://localhost/test/path");
    Assert.assertNotNull(
        "A UnderFileSystemFactory should exist for Gluster FS paths when using this module",
        factory);

    factory = UnderFileSystemRegistry.find("alluxio://localhost/test/path");
    Assert.assertNull("A UnderFileSystemFactory should not exist for unsupported paths when using"
        + " this module.", factory);
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;

namespace CSharpFunctionalExtensions.Tests.ResultTests.Extensions
{
    public class CheckIfTests_Task : CheckIfTestsBase
    {
        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_T_executes_func_result_T_conditionally_and_returns_self(bool isSuccess, bool condition)
        {
            Result<bool> result = Result.SuccessIf(isSuccess, condition, ErrorMessage);

            var returned = await result.AsTask().CheckIf(condition, Task_Func_Result);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }

        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_T_executes_func_result_K_conditionally_and_returns_self(bool isSuccess, bool condition)
        {
            Result<bool> result = Result.SuccessIf(isSuccess, condition, ErrorMessage);

            var returned = await result.AsTask().CheckIf(condition, Task_Func_Result_K);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }

        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_T_executes_func_result_K_E_conditionally_and_returns_self(bool isSuccess, bool condition)
        {
            Result<bool, E> result = Result.SuccessIf(isSuccess, condition, E.Value);

            var returned = await result.AsTask().CheckIf(condition, Task_Func_Result_K_E);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }

        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_T_executes_func_result_T_E_conditionally_and_returns_self(bool isSuccess, bool condition)
        {
            Result<bool, E> result = Result.SuccessIf(isSuccess, condition, E.Value);

            var returned = await result.AsTask().CheckIf(condition, Task_Func_UnitResult_E);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }

        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_E_executes_func_UnitResult_E_conditionally_and_returns_self(bool isSuccess, bool condition)
        {
            UnitResult<E> result = UnitResult.SuccessIf(isSuccess, E.Value);

            var returned = await result.AsTask().CheckIf(condition, Task_Func_UnitResult_E);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }

        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_T_executes_func_result_T_per_predicate_and_returns_self(bool isSuccess, bool condition)
        {
            Result<bool> result = Result.SuccessIf(isSuccess, condition, ErrorMessage);

            var returned = await result.AsTask().CheckIf(Predicate, Task_Func_Result);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }

        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_T_executes_func_result_K_per_predicate_and_returns_self(bool isSuccess, bool condition)
        {
            Result<bool> result = Result.SuccessIf(isSuccess, condition, ErrorMessage);

            var returned = await result.AsTask().CheckIf(Predicate, Task_Func_Result_K);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }

        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_T_executes_func_result_K_E_per_predicate_and_returns_self(bool isSuccess, bool condition)
        {
            Result<bool, E> result = Result.SuccessIf(isSuccess, condition, E.Value);

            var returned = await result.AsTask().CheckIf(Predicate, Task_Func_Result_K_E);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }

        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_T_executes_func_result_T_E_per_predicate_and_returns_self(bool isSuccess, bool condition)
        {
            Result<bool, E> result = Result.SuccessIf(isSuccess, condition, E.Value);

            var returned = await result.AsTask().CheckIf(Predicate, Task_Func_UnitResult_E);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }

        [Theory]
        [InlineData(true, true)]
        [InlineData(true, false)]
        [InlineData(false, true)]
        [InlineData(false, false)]
        public async Task CheckIf_Task_E_executes_func_UnitResult_E_per_predicate_and_returns_self(bool isSuccess, bool condition)
        {
            UnitResult<E> result = UnitResult.SuccessIf(isSuccess, E.Value);

            var returned = await result.AsTask().CheckIf(Predicate(condition), Task_Func_UnitResult_E);

            actionExecuted.Should().Be(isSuccess && condition);
            result.Should().Be(returned);
        }
    }
}


text:
from ...base.helper import key_for_cypher
from ....exceptions import AnnotationAttributeError, SubsetError

from ..elements import (EqualClauseElement, GtClauseElement, GteClauseElement,
                        LtClauseElement, LteClauseElement, NotEqualClauseElement,
                        InClauseElement, NotInClauseElement, ContainsClauseElement, RegexClauseElement,
                        RightAlignedClauseElement, LeftAlignedClauseElement,
                        NotRightAlignedClauseElement, NotLeftAlignedClauseElement,
                        SubsetClauseElement, NotSubsetClauseElement,
                        NullClauseElement, NotNullClauseElement,
                        FollowsClauseElement, PrecedesClauseElement)

from ...base import NodeAttribute, Node, CollectionNode, CollectionAttribute

special_attributes = ['duration', 'count', 'rate', 'position', 'subset']

class AnnotationAttribute(NodeAttribute):
    """
    Class for information about the attributes of annotations in a graph
    query

    Parameters
    ----------
    annotation : AnnotationAttribute
        Annotation that this attribute refers to
    label : str
        Label of the attribute

    Attributes
    ----------
    annotation : AnnotationAttribute
        Annotation that this attribute refers to
    label : str
        Label of the attribute
    output_label : str or None
        User-specified label to use in query results
    """
    collapsing = False

    def __init__(self, annotation, label):
        super(AnnotationAttribute, self).__init__(annotation, label)
        self.acoustic = False

    def __hash__(self):
        return hash((self.node, self.label))

    def __repr__(self):
        return '<AnnotationAttribute \'{}\'>'.format(str(self))

    def requires_type(self):
        if self.node.hierarchy is None or self.label in special_attributes:
            return False
        return not self.node.hierarchy.has_token_property(self.node.node_type, self.label)

    def for_cypher(self, type=False):
        """Returns annotation duration or annotation type if applicable, otherwise annotation name and label """
        if self.label == 'duration':
            return '{a}.end - {a}.begin'.format(a=self.node.alias)
        if type or self.requires_type():
            return '{}.{}'.format(self.node.type_alias, key_for_cypher(self.label))
        return '{}.{}'.format(self.node.alias, key_for_cypher(self.label))

    @property
    def with_alias(self):
        """
        returns type_alias if there is one
        alias otherwise
        """
        if self.requires_type():
            return self.node.type_alias
        else:
            return self.node.alias

    def __eq__(self, other):
        try:
            if self.label == 'begin' and other.label == 'begin':
                return LeftAlignedClauseElement(self.node, other.node)
            elif self.label == 'end' and other.label == 'end':
                return RightAlignedClauseElement(self.node, other.node)
        except AttributeError:
            pass
        if self.label == 'subset':
            return SubsetClauseElement(self, other)
        if other is None:
            return NullClauseElement(self, other)
        return EqualClauseElement(self, other)

    def __ne__(self, other):
        try:
            if self.label == 'begin' and other.label == 'begin':
                return NotLeftAlignedClauseElement(self.node, other.node)
            elif self.label == 'end' and other.label == 'end':
                return NotRightAlignedClauseElement(self.node, other.node)
        except AttributeError:
            pass
        if self.label == 'subset':
            return NotSubsetClauseElement(self, other)
        if other is None:
            return NotNullClauseElement(self, other)
        return NotEqualClauseElement(self, other)

    def __gt__(self, other):
        return GtClauseElement(self, other)

    def __ge__(self, other):
        return GteClauseElement(self, other)

    def __lt__(self, other):
        return LtClauseElement(self, other)

    def __le__(self, other):
        return LteClauseElement(self, other)

    def in_(self, other):
        """
        Checks if the parameter other has a 'cypher' element
        executes the query if it does and appends the relevant results
        or appends parameter other

        Parameters
        ----------
        other : list
            attribute will be checked against elements in this list
        Returns
        -------
        string
            clause for asserting membership in a filter

        """
        if hasattr(other, 'cypher'):
            results = other.all()
            t = []
            for x in results:
                t.append(getattr(x, self.label))
        else:
            t = other
        return InClauseElement(self, t)

    def not_in_(self, other):
        """
        Checks if the parameter other has a 'cypher' element
        executes the query if it does and appends the relevant results
        or appends parameter other

        Parameters
        ----------
        other : list
            attribute will be checked against elements in this list
        Returns
        -------
        string
            clause for asserting non-membership in a filter
        """
        if hasattr(other, 'cypher'):
            results = other.all()
            t = []
            for x in results:
                t.append(getattr(x, self.label))
        else:
            t = other
        return NotInClauseElement(self, t)

    def regex(self, pattern):
        """ Returns a clause for filtering based on regular expressions."""
        return RegexClauseElement(self, pattern)

    def aliased_for_output(self, type=False):
        """
        creates cypher string for output

        Returns
        -------
        string
            string for output
        """
        return '{} AS {}'.format(self.for_cypher(type), self.output_alias_for_cypher)

    def for_type_filter(self):
        return self.for_cypher(type=True)

class AnnotationNode(Node):
    """
    Class for annotations referenced in graph queries

    Parameters
    ----------
    type : str
        Annotation type
    pos : int
        Position in the query, defaults to 0

    Attributes
    ----------
    type : str
        Annotation type
    pos : int
        Position in the query
    previous : :class:`~polyglotdb.graph.attributes.AnnotationAttribute`
        Returns the Annotation of the same type with the previous position
    following : :class:`~polyglotdb.graph.attributes.AnnotationAttribute`
        Returns the Annotation of the same type with the following position
    """
    match_template = '''({token_alias})-[:is_a]->({type_alias})'''
    # template = '''({token_alias})'''
    begin_template = '{}_{}_begin'
    end_template = '{}_{}_end'
    alias_template = 'node_{t}'

    def __init__(self, node_type, corpus=None, hierarchy=None):
        super(AnnotationNode, self).__init__(node_type, corpus=corpus, hierarchy=hierarchy)

    def __hash__(self):
        return hash(self.key)

    def __eq__(self, other):
        if not isinstance(other, AnnotationNode):
            return False
        if self.key != other.key:
            return False
        return True

    def __str__(self):
        return '{}_0'.format(self.key)

    def __repr__(self):
        return '<AnnotationNode object with \'{}\' type>'.format(self.node_type)

    def for_match(self):
        """ sets 'token_alias' and 'type_alias'  keyword arguments for an annotation """
        kwargs = {'token_alias': self.define_alias,
                  'type_alias': self.define_type_alias}
        return self.match_template.format(**kwargs)

    def filter_by_subset(self, *args):
        """ adds each item in args to the hierarchy type_labels"""
        if self.hierarchy is not None:
            for a in args:
                if not self.hierarchy.has_type_subset(self.node_type, a) and not self.hierarchy.has_token_subset(
                        self.node_type, a):
                    raise (SubsetError('{} is not a subset of {} types or tokens.'.format(a, self.node_type)))
        self.subset_labels = sorted(set(self.subset_labels + list(args)))
        return self

    @property
    def define_type_alias(self):
        """ Returns a cypher string for getting all type_labels"""
        label_string = ':{}_type'.format(self.node_type)
        if self.corpus is not None:
            label_string += ':{}'.format(key_for_cypher(self.corpus))
        if self.subset_labels:
            subset_type_labels = [x for x in self.subset_labels if self.hierarchy.has_type_subset(self.node_type, x)]
            if subset_type_labels:
                label_string += ':' + ':'.join(map(key_for_cypher, subset_type_labels))
        return '{}{}'.format(self.type_alias, label_string)

    @property
    def define_alias(self):
        """ Returns a cypher string for getting all token_labels"""
        label_string = ':{}:speech'.format(self.node_type)
        if self.corpus is not None:
            label_string += ':{}'.format(key_for_cypher(self.corpus))
        if self.subset_labels:
            subset_token_labels = [x for x in self.subset_labels if self.hierarchy.has_token_subset(self.node_type, x)]
            if subset_token_labels:
                label_string += ':' + ':'.join(map(key_for_cypher, subset_token_labels))
        return '{}{}'.format(self.alias, label_string)

    @property
    def type_alias(self):
        """ Returns a cypher formatted string of type alias"""
        return key_for_cypher('type_' + self.alias.replace('`', ''))

    @property
    def alias(self):
        """Returns a cypher formatted string of keys and prefixes"""
        return key_for_cypher(self.alias_template.format(t=self.key))

    @property
    def with_alias(self):
        """ Returns alias """
        return self.alias

    @property
    def withs(self):
        """ Returns a list of alias and type_alias """
        return [self.alias, self.type_alias]

    def precedes(self, other_annotation):
        return PrecedesClauseElement(self, other_annotation)

    def follows(self, other_annotation):
        return FollowsClauseElement(self, other_annotation)

    def __getattr__(self, key):
        if key in ['previous', 'following']:
            from .precedence import PreviousAnnotation, FollowingAnnotation
            if key == 'previous':
                return PreviousAnnotation(self, -1)
            else:
                return FollowingAnnotation(self, 1)
        elif key in ['previous_pause', 'following_pause']:
            from .pause import FollowingPauseAnnotation, PreviousPauseAnnotation
            node = self
            if self.node_type != self.hierarchy.word_name:
                node = getattr(self, self.hierarchy.word_name)
            if key == 'previous_pause':
                return PreviousPauseAnnotation(node)
            else:
                return FollowingPauseAnnotation(node)
        elif key == 'follows_pause':
            from .pause import FollowsPauseAttribute
            return FollowsPauseAttribute(self)
        elif key == 'precedes_pause':
            from .pause import PrecedesPauseAttribute
            return PrecedesPauseAttribute(self)
        elif key == 'speaker':
            from .speaker import SpeakerAnnotation
            return SpeakerAnnotation(self)
        elif key == 'discourse':
            from .discourse import DiscourseAnnotation
            return DiscourseAnnotation(self)
        elif key.startswith('pitch'):
            from .acoustic import PitchAttribute
            return PitchAttribute(self, relative=('relative' in key))
        elif key.startswith('intensity'):
            from .acoustic import IntensityAttribute
            return IntensityAttribute(self, relative=('relative' in key))
        elif key.startswith('formants'):
            from .acoustic import FormantAttribute
            return FormantAttribute(self, relative=('relative' in key))
        elif self.hierarchy is not None and key in self.hierarchy.contained_by(self.node_type):
            from .hierarchical import HierarchicalAnnotation
            types = self.hierarchy.get_higher_types(self.node_type)
            prev_node = self
            cur_node = None
            for t in types:
                higher_node = AnnotationNode(t, corpus=self.corpus, hierarchy=self.hierarchy)
                cur_node = HierarchicalAnnotation(prev_node, higher_node)
                prev_node = cur_node
                if t == key:
                    break
            return cur_node
        elif self.hierarchy is not None and key in self.hierarchy.contains(self.node_type):
            from .path import SubPathAnnotation
            return SubPathAnnotation(self, AnnotationNode(key, corpus=self.corpus))
        elif self.hierarchy is not None \
                and self.node_type in self.hierarchy.subannotations \
                and key in self.hierarchy.subannotations[self.node_type]:
            from .subannotation import SubAnnotation
            return SubAnnotation(self, AnnotationNode(key, corpus=self.corpus))
        else:
            if key not in special_attributes and self.hierarchy is not None and not self.hierarchy.has_token_property(
                    self.node_type, key) and not self.hierarchy.has_type_property(self.node_type, key):
                properties = [x[0] for x in
                              self.hierarchy.type_properties[self.node_type] | self.hierarchy.token_properties[
                                  self.node_type]]
                raise AnnotationAttributeError(
                    'The \'{}\' annotation types do not have a \'{}\' property (available: {}).'.format(self.node_type,
                                                                                key, ', '.join(
                            properties)))
            return AnnotationAttribute(self, key)

class AnnotationCollectionNode(CollectionNode):
    def with_statement(self):
        """ """
        return ', '.join(['collect(n) as {a}'.format(a=self.collection_alias),
                          'collect(t) as {a}'.format(a=self.collection_type_alias)])

    @property
    def withs(self):
        withs = [self.collection_alias, self.collection_type_alias]
        return withs

class AnnotationCollectionAttribute(CollectionAttribute):
    pass


text:
[![Gem Version](https://badge.fury.io/rb/cnb.png)](http://badge.fury.io/rb/cnb)
[![Build Status](https://travis-ci.org/ucetnictvi-on-line/cnb.png?branch=master)](https://travis-ci.org/ucetnictvi-on-line/cnb)
[![Dependency Status](https://gemnasium.com/ucetnictvi-on-line/cnb.svg)](https://gemnasium.com/ucetnictvi-on-line/cnb)
[![Code Climate](https://codeclimate.com/github/ucetnictvi-on-line/cnb/badges/gpa.svg)](https://codeclimate.com/github/ucetnictvi-on-line/cnb)
[![Test Coverage](https://codeclimate.com/github/ucetnictvi-on-line/cnb/badges/coverage.svg)](https://codeclimate.com/github/ucetnictvi-on-line/cnb)

CNB is a gem that will help you get daily and monthly currency rates for czech crown (CZK) from Czech National Bank.

## Install

Add following into your Gemfile

```ruby
gem 'cnb'
```

Or install the gem by on your own

```ruby
gem install cnb
```

## Usage

### Daily

```ruby
CNB.daily_rate('AUD', Date.today)
```

Returns today's exchange rate between CZK and AUD.
Input date defaults to Date.today so the above line can written like this:

```ruby
CNB.daily_rate('AUD')
```

### Monthly

```ruby
CNB.monthly_rate('ALL', Date.today)
```

Returns today's exchange rate between CZK and ALL (Albanian lek).

#### Exceptions
* DateTooOld - triggers when date entered is older than 24 years, or 10 years if monthly.
* DateInFuture - triggers when date enetered is in future.
* CurrencyMissing - triggers when currency is not present.
* CurrencyNotSupported - triggers when currency is not in downloaded list of currencies.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## License
MIT License. Copyright (c) 2014


text:
package flags_test

import (
	"io/ioutil"
	"strconv"
	"testing"

	"github.com/google/gapid/core/app/flags"
	"github.com/google/gapid/core/assert"
)

const (
	Pagefaultman Hero = iota
	Supergirl
	Batman
	Aquaman
)
const (
	PoisonIvy Villain = iota
	Joker
	HarleyQuinn
	Sinestro
)

type (
	Hero    uint8
	Villain int32

	MyVerbFlags struct {
		Str     string
		Hero    Hero
		Villain Villain
	}
)

var heroNames = map[Hero]string{
	Pagefaultman: "pagefaultman",
	Supergirl:    "supergirl",
	Batman:       "batman",
	Aquaman:      "aquaman",
}

func (h Hero) String() string        { return heroNames[h] }
func (h *Hero) Choose(c interface{}) { *h = c.(Hero) }
func (h *Hero) Chooser() flags.Chooser {
	c := flags.Chooser{Value: h}
	for h := range heroNames {
		c.Choices = append(c.Choices, h)
	}
	return c
}

func (v *Villain) Choose(c interface{}) { *v = c.(Villain) }
func (v Villain) String() string {
	switch v {
	case PoisonIvy:
		return "Poison Ivy"
	case Joker:
		return "Joker"
	case HarleyQuinn:
		return "Harley Quinn"
	case Sinestro:
		return "Sinestro"
	default:
		return strconv.Itoa(int(v))
	}
}

func TestChoiceParsing(t *testing.T) {
	assert := assert.To(t)

	for _, cs := range []struct {
		args []string
		ok   bool
		h    Hero
		v    Villain
		s    string
	}{
		{[]string{"-hero", "Joker"}, false, 0, 0, "-"},
		{[]string{"-hero", "AQUAMAN"}, true, Aquaman, 0, ""},
		{[]string{"-str", "foo", "-hero", "supergirl"}, true, Supergirl, 0, "foo"},
		{[]string{"-str", "bar", "-hero", "Batman"}, true, Batman, 0, "bar"},
		{[]string{}, true, Pagefaultman, 0, ""},
		{[]string{"-villain", "Joker"}, true, 0, Joker, ""},
		{[]string{"-villain", "Harley Quinn"}, true, 0, HarleyQuinn, ""},
	} {
		verb := &struct{ MyVerbFlags }{}
		flags := flags.Set{}
		flags.Raw.Usage = func() {}
		flags.Raw.SetOutput(ioutil.Discard)
		flags.Bind("", verb, "")
		err := flags.Raw.Parse(cs.args)
		if cs.ok {
			assert.For("err").ThatError(err).Succeeded()
			assert.For("str").ThatString(verb.Str).Equals(cs.s)
			assert.For("hero").That(verb.Hero).Equals(cs.h)
		} else {
			assert.For("err").ThatError(err).Failed()
		}
	}
}


text:
package application.objects;

public class MatchResult {
    public enum Stage {
        ROUND_OF_SIXTEEN,
        QUATER_FINALS,
        SEMI_FINALS,
        FINAL
    }

    public Boolean reversed = false;
    public Boolean changed = false;
    public String matchResultSecondaryID;
    public String matchResultPrimaryID;
    public String teamOne;
    public String teamTwo;
    public Integer teamOneScore;
    public Integer teamTwoScore;
    public Integer type = 0;
    public Stage matchStage;

    public MatchResult() {
        ;
    }

    public String getWinnersName() {
        if(teamOneScore < teamTwoScore) {
            return teamOne;
        } else {
            return teamTwo;
        }
    }
}


text:
```C# Snippet:Azure_Search_Tests_Samples_Namespaces
using Azure.Search.Documents;
using Azure.Search.Documents.Indexes.Models;
```

## Create a client
Create a `SearchServiceClient` and send a request.
```C# Snippet:Azure_Search_Tests_Samples_CreateClientAsync
// Get the service endpoint and API key from the environment
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));
AzureKeyCredential credential = new AzureKeyCredential(
    Environment.GetEnvironmentVariable("SEARCH_API_KEY"));

// Create a new SearchServiceClient
SearchIndexClient search = new SearchIndexClient(endpoint, credential);

// Perform an operation
Response<SearchServiceStatistics> stats = await search.GetServiceStatisticsAsync();
Console.WriteLine($"You are using {stats.Value.Counters.IndexCounter.Usage} indexes.");
```

## Handle Errors
All Search operations will throw a RequestFailedException on failure.
```C# Snippet:Azure_Search_Tests_Samples_HandleErrorsAsync
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));
AzureKeyCredential credential = new AzureKeyCredential(
    Environment.GetEnvironmentVariable("SEARCH_API_KEY"));

// Create an invalid SearchClient
string fakeIndexName = "doesnotexist";
SearchClient client = new SearchClient(endpoint, fakeIndexName, credential);
try
{
    await client.GetDocumentCountAsync();
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
    Console.WriteLine("Index wasn't found.");
}
```


text:
import os
import sys
import urllib
import time
import copy
from parsers import ExpirationParser, OptionParser

def normalize_option_data(data, expiration):
    options = {}
    for line in data:
        options[line[0]] = {
            'type': 'C',
            'strike': float(line[8]),
            'last': float(line[1]),
            'change': float(line[3]),
            'bid': float(line[4]),
            'ask': float(line[5]),
            'volume': int(line[6]),
            'open_int': int(line[7]),
            'expiration': expiration,
        }

        options[line[9]] = {
            'type': 'P',
            'strike': float(line[8]),
            'last': float(line[10]),
            'change': float(line[12]),
            'bid': float(line[13]),
            'ask': float(line[14]),
            'volume': int(line[15]),
            'open_int': int(line[16]),
            'expiration': expiration,
        }

    return options

class OptionQuote(object):
    def __init__(self):
        self._expr_url = 'http://finance.yahoo.com/q/os?s=%s'
        self._option_url = "http://finance.yahoo.com/q/os?s=%s&m=%s"
        self._exp_parser = ExpirationParser()
        self._option_parser = OptionParser()

    def _convert_exp2str(self, expr):
        """
        Convert date object to YYYY-MM string format
        @param expr expiration date as python DateTime object
        """
        return expr.strftime('%Y-%m')

    def _get_option_expirations(self, underlying):
        """
        Parser the main option page for list of expirations dates
        @param symbol symbol of the underlying stock
        @return list of expiration dates as Datetime obj
        """
        url = self._expr_url % underlying
        data = urllib.urlopen(url).read()
        self._exp_parser.reset()
        self._exp_parser.feed(data)
        self._exp_parser.close()
        return self._exp_parser.expirations

    def _get_option_by_expr(self, underlying, expr):
        """
        Parser yahoo option page for data
        @param underlying stock
        @param expr expiration date in YYYY-MM string format
        @return dict of option data for the given stock/expiration date
        """
        url = self._option_url % (underlying, expr)
        data = urllib.urlopen(url).read()
        self._option_parser.reset()
        self._option_parser.feed(data)
        self._option_parser.close()
        return normalize_option_data(self._option_parser.data[1:-1], expr)

class CachedOptionQuote(OptionQuote):
    def __init__(self, cache_timeout=60*60):
        """
        Caching layer on top of OptionQuote.
        @param cache_timeout: Max time in second to keep data in cache. default
        to 1hour.
        """
        OptionQuote.__init__(self)
        self._cache = {}
        self._expirations = {}
        self._refresh_time = {}
        self._cache_timeout = cache_timeout

    def _get_option_expirations(self, underlying, force_reload=False):
        """
        Get expiration dates for the given stock, try to use cache if possible
        @param force_reload if false try to get data from cache first
        @return list of expiration dates as Datetime obj
        """
        if not force_reload and underlying in self._expirations:
            exps = self._expirations[underlying]
        else:
            exps = OptionQuote._get_option_expirations(self, underlying)
            self._expirations[underlying] = exps
        return exps

    def _get_option_by_expr(self, underlying, exp, force_reload=False):
        """
        Get data for option, try to use cache if possible
        @param force_reload if false try to get data from cache first
        @return dict of option data for the given stock/expiration date
        """
        if (not force_reload and (underlying,exp) in self._cache and
            time.time()-self._refresh_time[(underlying,exp)] < self._cache_timeout):
            options = self._cache[(underlying,exp)]
        else:
            options = OptionQuote._get_option_by_expr(self, underlying, exp)
            self._cache[(underlying,exp)] = options
            self._refresh_time[(underlying, exp)] = time.time()
        return options

    def get_options(self, underlying, options=[], expirations=[],
            strike=lambda x:True, force_reload=False):
        """
        The main interface for retrieving option data. This function will return
        deepcopy of the data and store original in cache for future use
        @param underlying: stock symbol to retrieve option data for
        @param options: filter the results for only these options. if the list
            is empty, this param is ignored
        @param expirations: filter the results for only these expirations. if
            the iterable is empty, this param is ignored
        @param strike: lambda function for selecting by strike price.
            default is select all. ex: lambda x:x>100 selects options with strike>100
        """
        result_set = {}
        if len(expirations) == 0:
            expirations = self._get_option_expirations(underlying)
        for exp in expirations:
            data = self._get_option_by_expr(underlying,
                    self._convert_exp2str(exp), force_reload)
            result_set.update(data)

        # filter for options
        for p in result_set.keys():
            if not strike(result_set[p]['strike']):
                del result_set[p]
        # filter for strike price and make deepcopy at same time
        if len(options) > 0:
            result_set2 = {}
            for p in options:
                if p in result_set:
                    result_set2[p] = copy.deepcopy(result_set[p])
            return result_set2
        else:
            return copy.deepcopy(result_set)


text:
'use strict';

var React = require('react-native');

var {
  NativeModules,
  requireNativeComponent,
  StyleSheet,
  PropTypes,
} = React;

var CircleProgress = React.createClass({
  propTypes: {
    progress: PropTypes.number,
    lineWidth: PropTypes.number,
    lineCap: PropTypes.string,
    circleRadius: PropTypes.number,
    foregroundColor: PropTypes.string,
    backgroundColor: PropTypes.string,
  },

  render: function() {
    let defaultProps = {
      progress: 0,
      lineWidth: 3,
      lineCap: NativeModules.CircleProgressManager.LineCapRound,
      circleColor: 'blue',
      circleUnderlayColor: 'transparent',
    }
    let props = {...defaultProps, ...this.props};

    return (
      <RCTCircleProgress {...props}
        style={[styles.base, this.props.style]}/>
    );
  },
});

var styles = StyleSheet.create({
  base: {
    width: 50,
    height: 50,
  },
});

var RCTCircleProgress = requireNativeComponent('RCTCircleProgress', null);

CircleProgress.LineCapButt = NativeModules.CircleProgressManager.LineCapButt;
CircleProgress.LineCapRound = NativeModules.CircleProgressManager.LineCapRound;
CircleProgress.LineCapSquare = NativeModules.CircleProgressManager.LineCapSquare;
module.exports = CircleProgress;


text:
const expect      = require('chai').expect;
const url         = require('url');
const DOMParser   = require('xmldom').DOMParser;
const fs          = require('fs');
const path        = require('path');
const zlib        = require('zlib');
const samlpLogout = require('..');

const credentials = {
  cert: fs.readFileSync(path.join(__dirname, 'fixture', 'samlp.test-cert.pem')),
  key:  fs.readFileSync(path.join(__dirname, 'fixture', 'samlp.test-cert.key')),
};

describe('samlpLogout', function () {
  describe('with a malformed key', function () {
    it('should invoke the callback with an error', function (done) {
      const logout = samlpLogout({
        issuer: 'http://example.org',
        identityProviderUrl: 'http://myadfs.com/ls',
        cert: credentials.cert,
        key:  'badly-formatted-key',
        relayState: 'foo=bar',
        deflate: true,
        identityProviderSigningCert: credentials.cert // only for testing purposes
      });

      logout({
        samlNameID: '112233',
        samlSessionIndex: '554433',
        query: {},
        body: {}
      }, {
        redirect: function (location) {
          const parsedUrl = url.parse(location, true);

          expect(parsedUrl.protocol).to.equal('http:');
          expect(parsedUrl.hostname).to.equal('myadfs.com');
          expect(parsedUrl.pathname).to.equal('/ls');

          zlib.inflateRaw(new Buffer(parsedUrl.query.SAMLRequest, 'base64'), function (err, buffer) {
            if (err) return done(err);

            SAMLRequestWithDeflate = parsedUrl.query.SAMLRequest;
            SAMLRequest = new DOMParser().parseFromString(buffer.toString());
            RelayState = parsedUrl.query.RelayState;
            SigAlg = parsedUrl.query.SigAlg;
            Signature = parsedUrl.query.Signature;
          });
        }
      }, (err) => {
        expect(err.message).to.equal('error:0909006C:PEM routines:get_name:no start line')
        done();
      });
    });
  });
});


text:
"""Module providing functions useful for reporting on dependencies."""

import pkg_resources

from typing import Generator

from .anib import get_version as get_blast_version
from .aniblastall import get_version as get_blastall_version
from .anim import get_version as get_nucmer_version
from .fastani import get_version as get_fastani_version

# Dict of dependencies that support pyani
REQUIREMENTS = [
    "biopython",
    "matplotlib",
    "namedlist",
    "networkx",
    "numpy",
    "openpyxl",
    "pandas",
    "Pillow",
    "scipy",
    "seaborn",
    "sqlalchemy",
    "tqdm",
]

DEVELOPMENT = [
    "bandit",
    "black",
    "codecov",
    "coverage",
    "doc8",
    "flake8",
    "jinja2",
    "mypy",
    "pydocstyle",
    "pylint",
    "pytest",
    "pytest-cov",
    "sphinx",
]

PIP = ["pre-commit", "pytest-ordering", "sphinx-rtd-theme"]

def get_versions(deplist: str) -> Generator:
    """Yield package name and version for contents of REQUIREMENTS."""
    depdict = {"REQUIREMENTS": REQUIREMENTS, "DEVELOPMENT": DEVELOPMENT, "PIP": PIP}
    for depname in sorted(depdict[deplist]):
        try:
            version = pkg_resources.get_distribution(depname).version
            loc = pkg_resources.get_distribution(depname).location
        except pkg_resources.DistributionNotFound:
            version = "Not Installed"
            loc = "-"
        yield (depname, version, loc)

def get_requirements() -> Generator:
    """Yield package name and version for Python requirements."""
    return get_versions("REQUIREMENTS")

def get_dev_requirements() -> Generator:
    """Yield package name and version for Python developer requirements."""
    return get_versions("DEVELOPMENT")

def get_pip_requirements() -> Generator:
    """Yield package name and version for Python pip installed requirements."""
    return get_versions("PIP")

def get_tool_versions() -> Generator:
    """Yield tool name and version for third-party installed tools."""
    for name, func in [
        ("blast+", get_blast_version),
        ("nucmer", get_nucmer_version),
        ("blastall", get_blastall_version),
        ("fastani", get_fastani_version),
    ]:
        yield (name, func())


text:
#include <JPetAnalysisTools/JPetAnalysisTools.h>
#include <JPetGeantParser/JPetGeantParser.h>
#include <JPetGeantParser/JPetGeantParserTools.h>
#include <JPetOptionsTools/JPetOptionsTools.h>
#include <JPetWriter/JPetWriter.h>
#include <iostream>

#include <JPetScin/JPetScin.h>
#include <TMath.h>
#include <array>
#include <cmath>
#include <string>

using namespace jpet_options_tools;

JPetGeantParser::JPetGeantParser(const char* name) : JPetUserTask(name) {}

JPetGeantParser::~JPetGeantParser() {}

bool JPetGeantParser::init()
{
  // create detector map
  std::unique_ptr<JPetGeomMapping> fDetectorMap(new JPetGeomMapping(getParamBank()));

  fOutputEvents = new JPetTimeWindowMC("JPetHit", "JPetMCHit", "JPetMCDecayTree");
  auto opts = getOptions();

  if (isOptionSet(fParams.getOptions(), kMaxTimeWindowParamKey))
  {
    fMaxTime = getOptionAsDouble(fParams.getOptions(), kMaxTimeWindowParamKey);
  }
  if (isOptionSet(fParams.getOptions(), kMinTimeWindowParamKey))
  {
    fMinTime = getOptionAsDouble(fParams.getOptions(), kMinTimeWindowParamKey);
  }
  if (isOptionSet(fParams.getOptions(), kSourceActivityParamKey))
  {
    fSimulatedActivity = getOptionAsDouble(fParams.getOptions(), kSourceActivityParamKey);
  }
  if (isOptionSet(fParams.getOptions(), kMakeHistogramsParamKey))
  {
    fMakeHisto = getOptionAsBool(fParams.getOptions(), kMakeHistogramsParamKey);
  }
  if (isOptionSet(fParams.getOptions(), kMakeEfficienciesParamKey))
  {
    fMakeEffiHisto = getOptionAsBool(fParams.getOptions(), kMakeEfficienciesParamKey);
  }
  if (isOptionSet(fParams.getOptions(), kEnergyThresholdParamKey))
  {
    fExperimentalThreshold = getOptionAsDouble(fParams.getOptions(), kEnergyThresholdParamKey);
  }
  if (isOptionSet(fParams.getOptions(), kProcessSingleEventinWindowParamKey))
  {
    fProcessSingleEventinWindow = getOptionAsBool(fParams.getOptions(), kProcessSingleEventinWindowParamKey);
  }

  if (isOptionSet(fParams.getOptions(), kSeedParamKey))
  {
    fSeed = getOptionAsInt(fParams.getOptions(), kSeedParamKey);
  }

  JPetGeantParserTools::setSeedTogRandom(getOriginalSeed());
  INFO("Seed value used for resolution smearing of MC simulation data: " << boost::lexical_cast<std::string>(getOriginalSeed()));

  loadSmearingOptionsAndSetupExperimentalParametrizer();

  if (fMakeHisto)
    bookBasicHistograms();
  if (fMakeEffiHisto)
    bookEfficiencyHistograms();

  // make distribution of decays in time window
  // needed to adjust simulation times into time window scheme
  std::tie(fTimeDistroOfDecays, fTimeDiffDistro) = JPetGeantParserTools::getTimeDistoOfDecays(fSimulatedActivity, fMinTime, fMaxTime);

  INFO("MC Hit wrapper started.");

  return true;
}

void JPetGeantParser::loadSmearingOptionsAndSetupExperimentalParametrizer()
{
  std::vector<double> timeSmearingParameters;
  if (isOptionSet(fParams.getOptions(), kTimeSmearingParametersParamKey))
  {
    timeSmearingParameters = getOptionAsVectorOfDoubles(fParams.getOptions(), kTimeSmearingParametersParamKey);
  }

  std::string timeSmearingFormula;
  if (isOptionSet(fParams.getOptions(), kTimeSmearingFunctionParamKey))
  {
    timeSmearingFormula = getOptionAsString(fParams.getOptions(), kTimeSmearingFunctionParamKey);
  }

  std::vector<double> timeSmearingLimits;
  if (isOptionSet(fParams.getOptions(), kTimeSmearingFunctionLimitsParamKey))
  {
    timeSmearingLimits = getOptionAsVectorOfDoubles(fParams.getOptions(), kTimeSmearingFunctionLimitsParamKey);
  }

  std::vector<double> energySmearingParameters;
  if (isOptionSet(fParams.getOptions(), kEnergySmearingParametersParamKey))
  {
    energySmearingParameters = getOptionAsVectorOfDoubles(fParams.getOptions(), kEnergySmearingParametersParamKey);
  }

  std::string energySmearingFormula;
  if (isOptionSet(fParams.getOptions(), kEnergySmearingFunctionParamKey))
  {
    energySmearingFormula = getOptionAsString(fParams.getOptions(), kEnergySmearingFunctionParamKey);
  }

  std::vector<double> energySmearingLimits;
  if (isOptionSet(fParams.getOptions(), kEnergySmearingFunctionLimitsParamKey))
  {
    energySmearingLimits = getOptionAsVectorOfDoubles(fParams.getOptions(), kEnergySmearingFunctionLimitsParamKey);
  }

  std::vector<double> zPositionSmearingParameters;
  if (isOptionSet(fParams.getOptions(), kZPositionSmearingParametersParamKey))
  {
    zPositionSmearingParameters = getOptionAsVectorOfDoubles(fParams.getOptions(), kZPositionSmearingParametersParamKey);
  }

  std::string zPositionSmearingFormula;
  if (isOptionSet(fParams.getOptions(), kZPositionSmearingFunctionParamKey))
  {
    zPositionSmearingFormula = getOptionAsString(fParams.getOptions(), kZPositionSmearingFunctionParamKey);
  }

  std::vector<double> zPositionSmearingLimits;
  if (isOptionSet(fParams.getOptions(), kZPositionSmearingFunctionLimitsParamKey))
  {
    zPositionSmearingLimits = getOptionAsVectorOfDoubles(fParams.getOptions(), kZPositionSmearingFunctionLimitsParamKey);
  }

  fExperimentalParametrizer.setSmearingFunctions({{timeSmearingFormula, timeSmearingParameters},
                                                  {energySmearingFormula, energySmearingParameters},
                                                  {zPositionSmearingFormula, zPositionSmearingParameters}});

  std::vector<std::pair<double, double>> limits;

  if (timeSmearingLimits.size() == 2)
  {
    limits.push_back({timeSmearingLimits[0], timeSmearingLimits[1]});
  }
  else
  {
    limits.push_back({-1, -1});
  }

  if (energySmearingLimits.size() == 2)
  {
    limits.push_back({energySmearingLimits[0], energySmearingLimits[1]});
  }
  else
  {
    limits.push_back({-1, -1});
  }

  if (zPositionSmearingLimits.size() == 2)
  {
    limits.push_back({zPositionSmearingLimits[0], zPositionSmearingLimits[1]});
  }
  else
  {
    limits.push_back({-1, -1});
  }

  fExperimentalParametrizer.setSmearingFunctionLimits(limits);
}

bool JPetGeantParser::exec()
{

  if (auto& mcEventPack = dynamic_cast<JPetGeantEventPack* const>(fEvent))
  {

    processMCEvent(mcEventPack);

    if (fProcessSingleEventinWindow)
    {
      saveHits();
    }
    else
    {
      if (isTimeWindowFull())
      {
        saveHits();
        clearTimeDistoOfDecays();
        std::tie(fTimeDistroOfDecays, fTimeDiffDistro) = JPetGeantParserTools::getTimeDistoOfDecays(fSimulatedActivity, fMinTime, fMaxTime);
      }
    }
  }
  else
  {
    return false;
  }

  return true;
}

bool JPetGeantParser::terminate()
{
  INFO("MC events processing ended");
  float effi;
  float err_effi;
  std::tie(effi, err_effi) = JPetGeantParserTools::calculateEfficiency(nPromptGen, nPromptRec);
  INFO(" Efficiency for prompt gamma registration: " << boost::lexical_cast<std::string>(effi) << " pm "
                                                     << boost::lexical_cast<std::string>(err_effi));

  std::tie(effi, err_effi) = JPetGeantParserTools::calculateEfficiency(n2gGen, n2gRec);
  INFO(" Efficiency for prompt 2gamma registration: " << boost::lexical_cast<std::string>(effi) << " pm "
                                                      << boost::lexical_cast<std::string>(err_effi));

  std::tie(effi, err_effi) = JPetGeantParserTools::calculateEfficiency(n3gGen, n3gRec);
  INFO(" Efficiency for prompt 3gamma registration: " << boost::lexical_cast<std::string>(effi) << " pm "
                                                      << boost::lexical_cast<std::string>(err_effi));

  return true;
}

void JPetGeantParser::processMCEvent(JPetGeantEventPack* evPack)
{

  bool isRecPrompt = false;
  std::array<bool, 2> isSaved2g{false, false};
  std::array<bool, 3> isSaved3g{false, false, false};

  bool isRec2g = false;
  bool isRec3g = false;

  float enePrompt = 0;
  std::array<float, 2> ene2g{0., 0.};
  std::array<float, 3> ene3g{0., 0., 0.};

  bool isGenPrompt = evPack->GetEventInformation()->GetPromptGammaGen();
  bool isGen2g = evPack->GetEventInformation()->GetTwoGammaGen();
  bool isGen3g = evPack->GetEventInformation()->GetThreeGammaGen();

  float timeShift = getNextTimeShift();
  for (unsigned int i = 0; i < evPack->GetNumberOfHits(); i++)
  {

    // translate geantHit -> JPetMCHit
    JPetMCHit mcHit = JPetGeantParserTools::createJPetMCHit(evPack->GetHit(i), getParamBank());

    if (fMakeHisto)
      fillHistoMCGen(mcHit);
    // create reconstructed hit and add all smearings
    JPetHit recHit = JPetGeantParserTools::reconstructHit(mcHit, getParamBank(), timeShift, fExperimentalParametrizer);

    // add criteria for possible rejection of reconstructed events (e.g. E>50 keV)
    if (JPetGeantParserTools::isHitReconstructed(recHit, fExperimentalThreshold))
    {
      saveReconstructedHit(recHit);
      JPetGeantParserTools::identifyRecoHits(evPack->GetHit(i), recHit, isRecPrompt, isSaved2g, isSaved3g, enePrompt, ene2g, ene3g);

      if (fMakeHisto)
        fillHistoMCRec(recHit);
    }
    fStoredMCHits.push_back(mcHit);
  }

  isRec2g = isSaved2g[0] && isSaved2g[1];
  isRec3g = isSaved3g[0] && isSaved3g[1] && isSaved3g[2];

  if (fMakeHisto)
    fillHistoGenInfo(evPack->GetEventInformation());

  // fill efficiency histograms

  if (isGenPrompt && fMakeEffiHisto)
  {
    double x = evPack->GetEventInformation()->GetVtxPromptPositionX();
    double y = evPack->GetEventInformation()->GetVtxPromptPositionY();
    double z = evPack->GetEventInformation()->GetVtxPromptPositionZ();
    getStatistics().getEffiHisto("effi_prompt_in_rho_z")->Fill(isRecPrompt, sqrt(pow(x, 2) + pow(y, 2)), z);
  }

  if (isGen2g && fMakeEffiHisto)
  {
    double x = evPack->GetEventInformation()->GetVtxPositionX();
    double y = evPack->GetEventInformation()->GetVtxPositionY();
    double z = evPack->GetEventInformation()->GetVtxPositionZ();
    getStatistics().getEffiHisto("effi_2g_in_rho_z")->Fill(isRec2g, sqrt(pow(x, 2) + pow(y, 2)), z);
  }

  if (isGen3g && fMakeEffiHisto)
  {
    double x = evPack->GetEventInformation()->GetVtxPositionX();
    double y = evPack->GetEventInformation()->GetVtxPositionY();
    double z = evPack->GetEventInformation()->GetVtxPositionZ();
    getStatistics().getEffiHisto("effi_3g_in_rho_z")->Fill(isRec3g, sqrt(pow(x, 2) + pow(y, 2)), z);
  }

  if (isGenPrompt)
  {
    nPromptGen++;
    if (isRecPrompt)
      nPromptRec++;
  }

  if (isGen2g)
  {
    n2gGen++;
    if (isRec2g)
      n2gRec++;
  }

  if (isGen3g)
  {
    n3gGen++;
    if (isRec3g)
      n3gRec++;
  }

  //    // add loop processing DecayTree
}

void JPetGeantParser::saveReconstructedHit(JPetHit recHit)
{
  recHit.setMCindex(fStoredMCHits.size());
  fStoredHits.push_back(recHit);
}

void JPetGeantParser::fillHistoGenInfo(JPetGeantEventInformation* evInfo)
{
  bool isGenPrompt = evInfo->GetPromptGammaGen();
  bool isGen2g = evInfo->GetTwoGammaGen();
  bool isGen3g = evInfo->GetThreeGammaGen();

  // general histograms
  getStatistics().getHisto1D("gen_lifetime")->Fill(evInfo->GetLifetime());

  // histograms for prompt gamma
  if (isGenPrompt)
  {
    getStatistics().getHisto1D("gen_hit_multiplicity")->Fill(1);
    getStatistics().getHisto2D("gen_prompt_XY")->Fill(evInfo->GetVtxPromptPositionX(), evInfo->GetVtxPromptPositionY());
    getStatistics().getHisto2D("gen_prompt_XZ")->Fill(evInfo->GetVtxPromptPositionX(), evInfo->GetVtxPromptPositionZ());
    getStatistics().getHisto2D("gen_prompt_YZ")->Fill(evInfo->GetVtxPromptPositionY(), evInfo->GetVtxPromptPositionZ());
  }

  // histograms for annihilation 2g 3g
  if (isGen2g)
  {
    getStatistics().getHisto1D("gen_hit_multiplicity")->Fill(2);
  }

  if (isGen3g)
  {
    getStatistics().getHisto1D("gen_hit_multiplicity")->Fill(3);
  }

  if (isGen2g || isGen3g)
  {
    getStatistics().getHisto2D("gen_XY")->Fill(evInfo->GetVtxPositionX(), evInfo->GetVtxPositionY());
    getStatistics().getHisto2D("gen_XZ")->Fill(evInfo->GetVtxPositionX(), evInfo->GetVtxPositionZ());
    getStatistics().getHisto2D("gen_YZ")->Fill(evInfo->GetVtxPositionY(), evInfo->GetVtxPositionZ());
  }
}

void JPetGeantParser::saveHits()
{

  for (const auto& hit : fStoredHits)
  {
    fOutputEvents->add<JPetHit>(hit);
  }

  for (const auto& mcHit : fStoredMCHits)
  {
    dynamic_cast<JPetTimeWindowMC*>(fOutputEvents)->addMCHit<JPetMCHit>(mcHit);
  }

  if (fMakeHisto)
  {
    getStatistics().getHisto1D("hits_per_time_window")->Fill(fStoredHits.size());
    for (const auto i : fTimeDiffDistro)
    {
      getStatistics().getHisto1D("time_diff_bw_decays")->Fill(i);
    }
  }

  fStoredMCHits.clear();
  fStoredHits.clear();
}

void JPetGeantParser::fillHistoMCGen(JPetMCHit& mcHit)
{
  getStatistics().getHisto1D("gen_hits_z_pos")->Fill(mcHit.getPosZ());
  getStatistics().getHisto2D("gen_hits_xy_pos")->Fill(mcHit.getPosX(), mcHit.getPosY());
  getStatistics().getHisto1D("gen_hit_time")->Fill(mcHit.getTime());
  getStatistics().getHisto1D("gen_hit_eneDepos")->Fill(mcHit.getEnergy());
}

void JPetGeantParser::fillHistoMCRec(JPetHit& recHit)
{
  getStatistics().getHisto1D("hits_z_pos")->Fill(recHit.getPosZ());
  getStatistics().getHisto2D("hits_xy_pos")->Fill(recHit.getPosX(), recHit.getPosY());
  getStatistics().getHisto1D("rec_hit_time")->Fill(recHit.getTime());
  getStatistics().getHisto1D("rec_hit_eneDepos")->Fill(recHit.getEnergy());
}

void JPetGeantParser::bookBasicHistograms()
{
  // HISTOGRAMS FROM STANDARD HITFINDER

  getStatistics().createHistogram(new TH1F("hits_per_time_window", "Number of Hits in Time Window", 101, -0.5, 500.5));

  getStatistics().createHistogram(new TH1F("time_diff_bw_decays", "Time difference between decays", 101, -0.5, (fMaxTime - fMinTime) / 50.));

  // GENERATED HISTOGRAMS

  getStatistics().createHistogram(new TH1F("gen_hits_z_pos", "Gen hits Z position", 100, -60.0, 60.0));

  getStatistics().createHistogram(new TH2F("gen_hits_xy_pos", "GEN hits XY pos", 121, -60.5, 60.5, 121, -60.5, 60.5));

  getStatistics().createHistogram(new TH1F("gen_hit_time", "Gen hit time", 100, 0.0, 15000.0));

  getStatistics().createHistogram(new TH1F("gen_hit_eneDepos", "Gen hit ene deposition", 750, 0.0, 1500.0));

  getStatistics().createHistogram(new TH2F("gen_XY", "GEN XY coordinates of annihilation point", 121, -60.5, 60.5, 121, -60.5, 60.5));

  getStatistics().createHistogram(new TH2F("gen_XZ", "GEN XZ coordinates of annihilation point", 121, -60.5, 60.5, 121, -60.5, 60.5));

  getStatistics().createHistogram(new TH2F("gen_YZ", "GEN YZ coordinates of annihilation point", 121, -60.5, 60.5, 121, -60.5, 60.5));

  getStatistics().createHistogram(new TH2F("gen_prompt_XY", "GEN XY coordinates of prompt emission point", 121, -60.5, 60.5, 121, -60.5, 60.5));

  getStatistics().createHistogram(new TH2F("gen_prompt_XZ", "GEN XZ coordinates of prompt emission point", 121, -60.5, 60.5, 121, -60.5, 60.5));

  getStatistics().createHistogram(new TH2F("gen_prompt_YZ", "GEN YZ coordinates of prompt emission point", 121, -60.5, 60.5, 121, -60.5, 60.5));

  getStatistics().createHistogram(new TH1F("gen_hit_multiplicity", "Gen hit multiplicity", 6, 0.0, 5.0));

  getStatistics().createHistogram(new TH1F("gen_lifetime", "Gen lifetime", 100, 0.0, 1500.0));

  // RECONSTRUCTED HISTOGRAMS

  getStatistics().createHistogram(new TH1F("hits_z_pos", "hits Z position", 100, -60.0, 60.0));

  getStatistics().createHistogram(new TH2F("hits_xy_pos", "hits XY pos", 121, -60.5, 60.5, 121, -60.5, 60.5));

  getStatistics().createHistogram(new TH1F("rec_hit_time", "hit time", 100, 0.0, 15000.0));

  getStatistics().createHistogram(new TH1F("rec_hit_eneDepos", "hit ene deposition", 750, 0.0, 1500.0));
}

void JPetGeantParser::bookEfficiencyHistograms()
{

  getStatistics().createHistogram(new TEfficiency("effi_3g_in_rho_z", "effi for 1g as function of rho and z of vtx", 100, 0., 50., 100, -25., 25.));

  getStatistics().createHistogram(new TEfficiency("effi_2g_in_rho_z", "effi for 2g as function of rho and z of vtx", 100, 0., 50., 100, -25., 25.));

  getStatistics().createHistogram(
      new TEfficiency("effi_prompt_in_rho_z", "effi for 3g as function of rho and z of vtx", 100, 0., 50., 100, -25., 25.));
}

unsigned int JPetGeantParser::getNumberOfDecaysInWindow() const { return fTimeDistroOfDecays.size(); }

float JPetGeantParser::getNextTimeShift()
{
  float t = fTimeDistroOfDecays[fCurrentIndexTimeShift];
  fCurrentIndexTimeShift++;
  return t;
}

void JPetGeantParser::clearTimeDistoOfDecays()
{
  fCurrentIndexTimeShift = 0;
  fTimeDiffDistro.clear();
  fTimeDistroOfDecays.clear();
}

bool JPetGeantParser::isTimeWindowFull() const
{
  if (fCurrentIndexTimeShift >= getNumberOfDecaysInWindow())
  {
    return true;
  }
  else
  {
    return false;
  }
}

unsigned long JPetGeantParser::getOriginalSeed() const { return fSeed; }


text:
/**
 * The file contains styles for GWT widgets in the standard theme, in RTL mode.
 *
 * In order to maintain cross-browser compatibility, the following syntax is
 * used to create IE6 specific style rules:
 *    .gwt-Widget {
 *      property: rule applies to all browsers
 *      -property: rule applies only to IE6 (overrides previous rule)
 *    }
 *    * html .gwt-Widget {
 *      property: rule applies to all versions of IE
 *    }
 */

body, table td, select {
  font-family: Arial Unicode MS, Arial, sans-serif;
  font-size: small;
}
pre {
  font-family: "courier new", courier;
  font-size: small;
}
body {
  color: black;
  margin: 0px;
  border: 0px;
  padding: 0px;
  background: #fff;
  direction: rtl;
}
a, a:visited, a:hover {
  color: #0000AA;
}

/**
 * The reference theme can be used to determine when this style sheet has
 * loaded.  Create a hidden div element with absolute position, assign the style
 * name below, and attach it to the DOM.  Use a timer to detect when the
 * element's height and width are set to 5px.
 */
.gwt-Reference-standard-rtl {
  height: 5px;
  width: 5px;
  zoom: 1;
}

.gwt-Button {
  margin: 0;
  padding: 3px 5px;
  text-decoration: none;
  font-size: small;
  cursor: pointer;
  cursor: hand;
  background: url("images/hborder.png") repeat-x 0px -27px;
  border: 1px outset #ccc;
}
.gwt-Button:active {
  border: 1px inset #ccc;
}
.gwt-Button:hover {
  border-color: #9cf #69e #69e #7af;
}
.gwt-Button[disabled] {
  cursor: default;
  color: #888;
}
.gwt-Button[disabled]:hover {
  border: 1px outset #ccc;
}

.gwt-CheckBox {
}
.gwt-CheckBox-disabled {
  color: #888;
}

.gwt-DecoratorPanel {
}
.gwt-DecoratorPanel .topCenter,
.gwt-DecoratorPanel .bottomCenter {
  background: url(images/hborder.png) repeat-x;
}
.gwt-DecoratorPanel .middleLeft,
.gwt-DecoratorPanel .middleRight {
  background: url(images/vborder.png) repeat-y;
}
.gwt-DecoratorPanel .topLeftInner,
.gwt-DecoratorPanel .topRightInner,
.gwt-DecoratorPanel .bottomLeftInner,
.gwt-DecoratorPanel .bottomRightInner {
  width: 5px;
  height: 5px;
  zoom: 1;
}
.gwt-DecoratorPanel .topLeft {
  background: url(images/corner.png) no-repeat 0px 0px;
  -background: url(images/corner_ie6.png) no-repeat 0px 0px;
}
.gwt-DecoratorPanel .topRight {
  background: url(images/corner.png) no-repeat -5px 0px;
  -background: url(images/corner_ie6.png) no-repeat -5px 0px;
}
.gwt-DecoratorPanel .bottomLeft {
  background: url(images/corner.png) no-repeat 0px -5px;
  -background: url(images/corner_ie6.png) no-repeat 0px -5px;
}
.gwt-DecoratorPanel .bottomRight {
  background: url(images/corner.png) no-repeat -5px -5px;
  -background: url(images/corner_ie6.png) no-repeat -5px -5px;
}
* html .gwt-DecoratorPanel .topLeftInner,
* html .gwt-DecoratorPanel .topRightInner,
* html .gwt-DecoratorPanel .bottomLeftInner,
* html .gwt-DecoratorPanel .bottomRightInner {
  width: 5px;
  height: 5px;
  overflow: hidden;
}

.gwt-DialogBox .Caption {
  background: #e3e8f3 url(images/hborder.png) repeat-x 0px -2003px;
  padding: 4px 8px 4px 4px;
  cursor: default;
  border-bottom: 1px solid #bbbbbb;
  border-top: 5px solid #d0e4f6;
}
.gwt-DialogBox .dialogContent {
}
.gwt-DialogBox .dialogMiddleCenter {
  padding: 3px;
  background: white;
}
.gwt-DialogBox .dialogBottomCenter {
  background: url(images/hborder.png) repeat-x 0px -4px;
  -background: url(images/hborder_ie6.png) repeat-x 0px -4px;
}
.gwt-DialogBox .dialogMiddleLeft {
  background: url(images/vborder.png) repeat-y;
}
.gwt-DialogBox .dialogMiddleRight {
  background: url(images/vborder.png) repeat-y -4px 0px;
  -background: url(images/vborder_ie6.png) repeat-y -4px 0px;
}
.gwt-DialogBox .dialogTopLeftInner {
  width: 5px;
  zoom: 1;
}
.gwt-DialogBox .dialogTopRightInner {
  width: 8px;
  zoom: 1;
}
.gwt-DialogBox .dialogBottomLeftInner {
  width: 5px;
  height: 8px;
  zoom: 1;
}
.gwt-DialogBox .dialogBottomRightInner {
  width: 5px;
  height: 8px;
  zoom: 1;
}
.gwt-DialogBox .dialogTopLeft {
  background: url(images/corner.png) no-repeat -13px 0px;
  -background: url(images/corner_ie6.png) no-repeat -13px 0px;
}
.gwt-DialogBox .dialogTopRight {
  background: url(images/corner.png) no-repeat -18px 0px;
  -background: url(images/corner_ie6.png) no-repeat -18px 0px;
}
.gwt-DialogBox .dialogBottomLeft {
  background: url(images/corner.png) no-repeat 0px -15px;
  -background: url(images/corner_ie6.png) no-repeat 0px -15px;
}
.gwt-DialogBox .dialogBottomRight {
  background: url(images/corner.png) no-repeat -5px -15px;
  -background: url(images/corner_ie6.png) no-repeat -5px -15px;
}
* html .gwt-DialogBox .dialogTopLeftInner {
  width: 5px;
  overflow: hidden;
}
* html .gwt-DialogBox .dialogTopRightInner {
  width: 8px;
  overflow: hidden;
}
* html .gwt-DialogBox .dialogBottomLeftInner {
  width: 5px;
  height: 8px;
  overflow: hidden;
}
* html .gwt-DialogBox .dialogBottomRightInner {
  width: 8px;
  height: 8px;
  overflow: hidden;
}

.gwt-DisclosurePanel {
}
.gwt-DisclosurePanel-open {
}
.gwt-DisclosurePanel-closed {
}
.gwt-DisclosurePanel .header,
.gwt-DisclosurePanel .header a,
.gwt-DisclosurePanel .header td {
  text-decoration: none;  /* Remove underline from header */
  color: black;
  cursor: pointer;
  cursor: hand;
}
.gwt-DisclosurePanel .content {
  border-right: 3px solid #e8eef7;
  padding: 4px 8px 4px 0px;
  margin-right: 6px;
}

.gwt-FileUpload {
}

.gwt-Frame {
  border-top: 2px solid #666;
  border-left: 2px solid #666;
  border-right: 2px solid #bbb;
  border-bottom: 2px solid #bbb;
}

.gwt-HorizontalSplitPanel {
}
.gwt-HorizontalSplitPanel .hsplitter {
  cursor: move;
  border: 0px;
  background: #91c0ef url(images/vborder.png) repeat-y;
  line-height: 0px;
}
.gwt-VerticalSplitPanel {
}
.gwt-VerticalSplitPanel .vsplitter {
  cursor: move;
  border: 0px;
  background: #91c0ef url(images/hborder.png) repeat-x;
  line-height: 0px;
}

.gwt-HTML {
}

.gwt-Hyperlink {
}

.gwt-Image {
}

.gwt-Label {
}

.gwt-ListBox {
}

.gwt-MenuBar {
  cursor: default;
}
.gwt-MenuBar .gwt-MenuItem {
  cursor: default;
}
.gwt-MenuBar .gwt-MenuItem-selected {
  background: #E0EDFE;
}
.gwt-MenuBar .gwt-MenuItem-disabled {
  color: #c0c0c0;
}
.gwt-MenuBar-horizontal {
  background: #e3e8f3 url(images/hborder.png) repeat-x 0px -2003px;
  border: 1px solid #BBBBBB;
}
.gwt-MenuBar-horizontal .gwt-MenuItem {
  padding: 0px 10px;
  vertical-align: bottom;
  color: #666666;
  font-weight: bold;
}
.gwt-MenuBar-horizontal .gwt-MenuItemSeparator {
  width: 1px;
  padding: 0px;
  margin: 0px;
  border: 0px;
  border-right: 1px solid #888888;
  background: white;
}
.gwt-MenuBar-horizontal .gwt-MenuItemSeparator .menuSeparatorInner {
  width: 1px;
  height: 1px;
  background: white;
}
.gwt-MenuBar-vertical {
  margin-top: 0px;
  margin-right: 0px;
  background: white;
}
.gwt-MenuBar-vertical table {
  border-collapse: collapse;
}
.gwt-MenuBar-vertical .gwt-MenuItem {
  padding: 4px 1px 4px 14px;
}
.gwt-MenuBar-vertical .gwt-MenuItemSeparator {
  padding: 2px 0px;
}
.gwt-MenuBar-vertical .gwt-MenuItemSeparator .menuSeparatorInner {
  height: 1px;
  padding: 0px;
  border: 0px;
  border-top: 1px solid #777777;
  background: #ddddee;
  overflow: hidden;
}
.gwt-MenuBar-vertical .subMenuIcon {
  padding-left: 4px;
}
.gwt-MenuBar-vertical .subMenuIcon-selected {
  background: #E0EDFE;
}
.gwt-MenuBarPopup {
  margin: 0px 3px 0px 0px;
}
.gwt-MenuBarPopup .menuPopupTopCenter {
  background: url(images/hborder.png) 0px -12px repeat-x;
}
.gwt-MenuBarPopup .menuPopupBottomCenter {
  background: url(images/hborder.png) 0px -13px repeat-x;
  -background: url(images/hborder_ie6.png) 0px -13px repeat-x;
}
.gwt-MenuBarPopup .menuPopupMiddleLeft {
  background: url(images/vborder.png) -12px 0px repeat-y;
  -background: url(images/vborder_ie6.png) -12px 0px repeat-y;
}
.gwt-MenuBarPopup .menuPopupMiddleRight {
  background: url(images/vborder.png) -13px 0px repeat-y;
  -background: url(images/vborder_ie6.png) -13px 0px repeat-y;
}
.gwt-MenuBarPopup .menuPopupTopLeftInner {
  width: 5px;
  height: 5px;
  zoom: 1;
}
.gwt-MenuBarPopup .menuPopupTopRightInner {
  width: 8px;
  height: 5px;
  zoom: 1;
}
.gwt-MenuBarPopup .menuPopupBottomLeftInner {
  width: 5px;
  height: 8px;
  zoom: 1;
}
.gwt-MenuBarPopup .menuPopupBottomRightInner {
  width: 8px;
  height: 8px;
  zoom: 1;
}
.gwt-MenuBarPopup .menuPopupTopLeft {
  background: url(images/corner.png) no-repeat 0px -36px;
  -background: url(images/corner_ie6.png) no-repeat 0px -36px;
}
.gwt-MenuBarPopup .menuPopupTopRight {
  background: url(images/corner.png) no-repeat -5px -36px;
  -background: url(images/corner_ie6.png) no-repeat -5px -36px;
}
.gwt-MenuBarPopup .menuPopupBottomLeft {
  background: url(images/corner.png) no-repeat 0px -41px;
  -background: url(images/corner_ie6.png) no-repeat 0px -41px;
}
.gwt-MenuBarPopup .menuPopupBottomRight {
  background: url(images/corner.png) no-repeat -5px -41px;
  -background: url(images/corner_ie6.png) no-repeat -5px -41px;
}
* html .gwt-MenuBarPopup .menuPopupTopLeftInner {
  width: 5px;
  height: 5px;
  overflow: hidden;
}
* html .gwt-MenuBarPopup .menuPopupTopRightInner {
  width: 8px;
  height: 5px;
  overflow: hidden;
}
* html .gwt-MenuBarPopup .menuPopupBottomLeftInner {
  width: 5px;
  height: 8px;
  overflow: hidden;
}
* html .gwt-MenuBarPopup .menuPopupBottomRightInner {
  width: 8px;
  height: 8px;
  overflow: hidden;
}

.gwt-PasswordTextBox {
  padding: 2px;
}
.gwt-PasswordTextBox-readonly {
  color: #888;
}

.gwt-PopupPanel {
  border: 3px solid #C3D9FF;
  padding: 3px;
  background: white;
}

.gwt-DecoratedPopupPanel .popupContent {
}
.gwt-DecoratedPopupPanel .popupMiddleCenter {
  padding: 3px;
  background: #d0e4f6;
}
.gwt-DecoratedPopupPanel .popupTopCenter {
  background: url(images/hborder.png) repeat-x;
}
.gwt-DecoratedPopupPanel .popupBottomCenter {
  background: url(images/hborder.png) repeat-x 0px -4px;
  -background: url(images/hborder_ie6.png) repeat-x 0px -4px;
}
.gwt-DecoratedPopupPanel .popupMiddleLeft {
  background: url(images/vborder.png) repeat-y;
}
.gwt-DecoratedPopupPanel .popupMiddleRight {
  background: url(images/vborder.png) repeat-y -4px 0px;
  -background: url(images/vborder_ie6.png) repeat-y -4px 0px;
}
.gwt-DecoratedPopupPanel .popupTopLeftInner {
  width: 5px;
  height: 5px;
  zoom: 1;
}
.gwt-DecoratedPopupPanel .popupTopRightInner {
  width: 8px;
  height: 5px;
  zoom: 1;
}
.gwt-DecoratedPopupPanel .popupBottomLeftInner {
  width: 5px;
  height: 8px;
  zoom: 1;
}
.gwt-DecoratedPopupPanel .popupBottomRightInner {
  width: 8px;
  height: 8px;
  zoom: 1;
}
.gwt-DecoratedPopupPanel .popupTopLeft {
  background: url(images/corner.png) no-repeat 0px -10px;
  -background: url(images/corner_ie6.png) no-repeat 0px -10px;
}
.gwt-DecoratedPopupPanel .popupTopRight {
  background: url(images/corner.png) no-repeat -5px -10px;
  -background: url(images/corner_ie6.png) no-repeat -5px -10px;
}
.gwt-DecoratedPopupPanel .popupBottomLeft {
  background: url(images/corner.png) no-repeat 0px -15px;
  -background: url(images/corner_ie6.png) no-repeat 0px -15px;
}
.gwt-DecoratedPopupPanel .popupBottomRight {
  background: url(images/corner.png) no-repeat -5px -15px;
  -background: url(images/corner_ie6.png) no-repeat -5px -15px;
}
* html .gwt-DecoratedPopupPanel .popupTopLeftInner {
  width: 5px;
  height: 5px;
  overflow: hidden;
}
* html .gwt-DecoratedPopupPanel .popupTopRightInner {
  width: 8px;
  height: 5px;
  overflow: hidden;
}
* html .gwt-DecoratedPopupPanel .popupBottomLeftInner {
  width: 5px;
  height: 8px;
  overflow: hidden;
}
* html .gwt-DecoratedPopupPanel .popupBottomRightInner {
  width: 8px;
  height: 8px;
  overflow: hidden;
}

.gwt-PopupPanelGlass {
  background-color: #000;
  opacity: 0.3;
  filter: alpha(opacity=30);
}

.gwt-PushButton-up,
.gwt-PushButton-up-hovering,
.gwt-PushButton-up-disabled,
.gwt-PushButton-down,
.gwt-PushButton-down-hovering,
.gwt-PushButton-down-disabled {
  margin: 0;
  text-decoration: none;
  background: url("images/hborder.png") repeat-x 0px -27px;
}
.gwt-PushButton-up,
.gwt-PushButton-up-hovering,
.gwt-PushButton-up-disabled {
  padding: 3px 5px 3px 5px;
}
.gwt-PushButton-up {
  border: 1px outset #ccc;
  cursor: pointer;
  cursor: hand;
}
.gwt-PushButton-up-hovering {
  border: 1px outset;
  border-color: #9cf #69e #69e #7af;
  cursor: pointer;
  cursor: hand;
}
.gwt-PushButton-up-disabled {
  border: 1px outset #ccc;
  cursor: default;
  opacity: .5;
  filter: alpha(opacity=40);
  zoom: 1;
}
.gwt-PushButton-down,
.gwt-PushButton-down-hovering,
.gwt-PushButton-down-disabled {
  padding: 4px 4px 2px 6px;
}
.gwt-PushButton-down {
  border: 1px inset #666;
  cursor: pointer;
  cursor: hand;
}
.gwt-PushButton-down-hovering {
  border: 1px inset;
  border-color: #9cf #69e #69e #7af;
  cursor: pointer;
  cursor: hand;
}
.gwt-PushButton-down-disabled {
  border: 1px outset #ccc;
  cursor: default;
  opacity: 0.5;
  filter: alpha(opacity=40);
  zoom: 1;
}

.gwt-RadioButton {
}
.gwt-RadioButton-disabled {
  color: #888;
}

.gwt-RichTextArea {
}
.hasRichTextToolbar {
  border: 0px;
}
.gwt-RichTextToolbar {
  background: #e3e8f3 url(images/hborder.png) repeat-x 0px -2003px;
  border-bottom: 1px solid #BBBBBB;
  padding: 3px;
  margin: 0px;
}
.gwt-RichTextToolbar .gwt-PushButton-up {
  padding: 0px 0px 0px 1px;
  margin-left: 4px;
  margin-bottom: 4px;
  border-width: 1px;
}
.gwt-RichTextToolbar .gwt-PushButton-up-hovering {
  margin-left: 4px;
  margin-bottom: 4px;
  padding: 0px 0px 0px 1px;
  border-width: 1px;
}
.gwt-RichTextToolbar .gwt-PushButton-down {
  margin-left: 4px;
  margin-bottom: 4px;
  padding: 0px 1px 0px 0px;
  border-width: 1px;
}
.gwt-RichTextToolbar .gwt-PushButton-down-hovering {
  margin-left: 4px;
  margin-bottom: 4px;
  padding: 0px 1px 0px 0px;
  border-width: 1px;
}
.gwt-RichTextToolbar .gwt-ToggleButton-up {
  margin-left: 4px;
  margin-bottom: 4px;
  padding: 0px 0px 0px 1px;
  border-width: 1px;
}
.gwt-RichTextToolbar .gwt-ToggleButton-up-hovering {
  margin-left: 4px;
  margin-bottom: 4px;
  padding: 0px 0px 0px 1px;
  border-width: 1px;
}
.gwt-RichTextToolbar .gwt-ToggleButton-down {
  margin-left: 4px;
  margin-bottom: 4px;
  padding: 0px 1px 0px 0px;
  border-width: 1px;
}
.gwt-RichTextToolbar .gwt-ToggleButton-down-hovering {
  margin-left: 4px;
  margin-bottom: 4px;
  padding: 0px 1px 0px 0px;
  border-width: 1px;
}

.gwt-StackPanel {
  border-bottom: 1px solid #bbbbbb;
}
.gwt-StackPanel .gwt-StackPanelItem {
  cursor: pointer;
  cursor: hand;
  font-weight: bold;
  font-size: 1.3em;
  padding: 3px;
  border: 1px solid #bbbbbb;
  border-bottom: 0px;
  background: #d3def6 url(images/hborder.png) repeat-x 0px -989px;
}
.gwt-StackPanel .gwt-StackPanelContent {
  border: 1px solid #bbbbbb;
  border-bottom: 0px;
  background: white;
  padding: 2px 2px 10px 5px;
}

.gwt-DecoratedStackPanel {
  border-bottom: 1px solid #bbbbbb;
}
.gwt-DecoratedStackPanel .gwt-StackPanelContent {
  border: 1px solid #bbbbbb;
  border-bottom: 0px;
  background: white;
  padding: 2px 5px 10px 2px;
}
.gwt-DecoratedStackPanel .gwt-StackPanelItem {
  cursor: pointer;
  cursor: hand;
}
.gwt-DecoratedStackPanel .stackItemTopLeft,
.gwt-DecoratedStackPanel .stackItemTopRight {
  height: 6px;
  width: 6px;
  zoom: 1;
}
.gwt-DecoratedStackPanel .stackItemTopLeft {
  border-left: 1px solid #bbbbbb;
  background: #d3def6 url(images/corner.png) no-repeat 0px -49px;
  -background: #d3def6 url(images/corner_ie6.png) no-repeat 0px -49px;
}
.gwt-DecoratedStackPanel .stackItemTopRight {
  border-right: 1px solid #bbbbbb;
  background: #d3def6 url(images/corner.png) no-repeat -6px -49px;
  -background: #d3def6 url(images/corner_ie6.png) no-repeat -6px -49px;
}
.gwt-DecoratedStackPanel .stackItemTopLeftInner,
.gwt-DecoratedStackPanel .stackItemTopRightInner {
  width: 1px;
  height: 1px;
}
* html .gwt-DecoratedStackPanel .stackItemTopLeftInner,
* html .gwt-DecoratedStackPanel .stackItemTopRightInner {
  width: 6px;
  height: 6px;
  overflow: hidden;
}
.gwt-DecoratedStackPanel .stackItemTopCenter {
  background: url(images/hborder.png) 0px -21px repeat-x;
}
.gwt-DecoratedStackPanel .stackItemMiddleLeft {
  background: #d3def6 url(images/hborder.png) repeat-x 0px -989px;
  border-left: 1px solid #bbbbbb;
}
.gwt-DecoratedStackPanel .stackItemMiddleLeftInner,
.gwt-DecoratedStackPanel .stackItemMiddleRightInner {
  width: 1px;
  height: 1px;
}
.gwt-DecoratedStackPanel .stackItemMiddleRight {
  background: #d3def6 url(images/hborder.png) repeat-x 0px -989px;
  border-right: 1px solid #bbbbbb;
}
.gwt-DecoratedStackPanel .stackItemMiddleCenter {
  font-weight: bold;
  font-size: 1.3em;
  background: #d3def6 url(images/hborder.png) repeat-x 0px -989px;
}
.gwt-DecoratedStackPanel .gwt-StackPanelItem-first .stackItemTopRight,
.gwt-DecoratedStackPanel .gwt-StackPanelItem-first .stackItemTopLeft {
  border: 0px;
  background-color: white;
}
.gwt-DecoratedStackPanel .gwt-StackPanelItem-below-selected .stackItemTopLeft,
.gwt-DecoratedStackPanel .gwt-StackPanelItem-below-selected .stackItemTopRight {
  background-color: white;
}

.gwt-SuggestBox {
  padding: 2px;
}
.gwt-SuggestBoxPopup {
  margin-right: 3px;
}
.gwt-SuggestBoxPopup .item {
  padding: 2px 6px;
  color: #424242;
  cursor: default;
}
.gwt-SuggestBoxPopup .item-selected {
  background: #b7d6f6;
}
.gwt-SuggestBoxPopup .suggestPopupContent {
  background: white;
}
.gwt-SuggestBoxPopup .suggestPopupTopCenter {
  background: url(images/hborder.png) repeat-x;
}
.gwt-SuggestBoxPopup .suggestPopupBottomCenter {
  background: url(images/hborder.png) repeat-x 0px -4px;
  -background: url(images/hborder_ie6.png) repeat-x 0px -4px;
}
.gwt-SuggestBoxPopup .suggestPopupMiddleLeft {
  background: url(images/vborder.png) repeat-y;
}
.gwt-SuggestBoxPopup .suggestPopupMiddleRight {
  background: url(images/vborder.png) repeat-y -4px 0px;
  -background: url(images/vborder_ie6.png) repeat-y -4px 0px;
}
.gwt-SuggestBoxPopup .suggestPopupTopLeftInner {
  width: 5px;
  height: 5px;
  zoom: 1;
}
.gwt-SuggestBoxPopup .suggestPopupTopRightInner {
  width: 8px;
  height: 5px;
  zoom: 1;
}
.gwt-SuggestBoxPopup .suggestPopupBottomLeftInner {
  width: 5px;
  height: 8px;
  zoom: 1;
}
.gwt-SuggestBoxPopup .suggestPopupBottomRightInner {
  width: 8px;
  height: 8px;
  zoom: 1;
}
.gwt-SuggestBoxPopup .suggestPopupTopLeft {
  background: url(images/corner.png) no-repeat 0px -23px;
  -background: url(images/corner_ie6.png) no-repeat 0px -23px;
}
.gwt-SuggestBoxPopup .suggestPopupTopRight {
  background: url(images/corner.png) no-repeat -5px -23px;
  -background: url(images/corner_ie6.png) no-repeat -5px -23px;
}
.gwt-SuggestBoxPopup .suggestPopupBottomLeft {
  background: url(images/corner.png) no-repeat 0px -28px;
  -background: url(images/corner_ie6.png) no-repeat 0px -28px;
}
.gwt-SuggestBoxPopup .suggestPopupBottomRight {
  background: url(images/corner.png) no-repeat -5px -28px;
  -background: url(images/corner_ie6.png) no-repeat -5px -28px;
}
* html .gwt-SuggestBoxPopup .suggestPopupTopLeftInner {
  width: 5px;
  height: 5px;
  overflow: hidden;
}
* html .gwt-SuggestBoxPopup .suggestPopupTopRightInner {
  width: 8px;
  height: 5px;
  overflow: hidden;
}
* html .gwt-SuggestBoxPopup .suggestPopupBottomLeftInner {
  width: 5px;
  height: 8px;
  overflow: hidden;
}
* html .gwt-SuggestBoxPopup .suggestPopupBottomRightInner {
  width: 8px;
  height: 8px;
  overflow: hidden;
}

.gwt-TabBar {
}
.gwt-TabBar .gwt-TabBarFirst {
  width: 5px;  /* first tab distance from the left */
}
.gwt-TabBar .gwt-TabBarRest {
}
.gwt-TabBar .gwt-TabBarItem {
  margin-left: 6px;
  padding: 3px 6px 3px 6px;
  cursor: pointer;
  cursor: hand;
  color: black;
  font-weight: bold;
  text-align: center;
  background: #d0e4f6;
}
.gwt-TabBar .gwt-TabBarItem-selected {
  cursor: default;
  background: #92c1f0;
}
.gwt-TabBar .gwt-TabBarItem-disabled {
  cursor: default;
  color: #999999;
}
.gwt-TabPanel {
}
.gwt-TabPanelBottom {
  border-color: #92c1f0;
  border-style: solid;
  border-width: 3px 2px 2px;
  overflow: hidden;
  padding: 6px;
}

.gwt-DecoratedTabBar {
}
.gwt-DecoratedTabBar .gwt-TabBarFirst {
  width: 5px;  /* first tab distance from the left */
}
.gwt-DecoratedTabBar .gwt-TabBarRest {
}
.gwt-DecoratedTabBar .gwt-TabBarItem {
  border-collapse: collapse;
  margin-right: 6px;
}
.gwt-DecoratedTabBar .tabTopCenter {
  padding: 0px;
  background: #d0e4f6;
}
.gwt-DecoratedTabBar .tabTopLeft,
.gwt-DecoratedTabBar .tabTopRight {
  padding: 0px;
  zoom: 1;
}
.gwt-DecoratedTabBar .tabTopLeftInner,
.gwt-DecoratedTabBar .tabTopRightInner {
  width: 6px;
  height: 6px;
}
.gwt-DecoratedTabBar .tabTopLeft {
  background: url(images/corner.png) no-repeat 0px -55px;
  -background: url(images/corner_ie6.png) no-repeat 0px -55px;
}
.gwt-DecoratedTabBar .tabTopRight {
  background: url(images/corner.png) no-repeat -6px -55px;
  -background: url(images/corner_ie6.png) no-repeat -6px -55px;
}
* html .gwt-DecoratedTabBar .tabTopLeftInner,
* html .gwt-DecoratedTabBar .tabTopRightInner {
  width: 6px;
  height: 6px;
  overflow: hidden;
}
.gwt-DecoratedTabBar .tabMiddleLeft,
.gwt-DecoratedTabBar .tabMiddleRight {
  width: 6px;
  padding: 0px;
  background: #d0e4f6;
}
.gwt-DecoratedTabBar .tabMiddleLeftInner,
.gwt-DecoratedTabBar .tabMiddleRightInner {
  width: 1px;
  height: 1px;
}
.gwt-DecoratedTabBar .tabMiddleCenter {
  padding: 0px 4px 2px 4px;
  cursor: pointer;
  cursor: hand;
  color: black;
  font-weight: bold;
  text-align: center;
  background: #d0e4f6;
}
.gwt-DecoratedTabBar .gwt-TabBarItem-selected .tabTopCenter {
  background: #92c1f0;
}
.gwt-DecoratedTabBar .gwt-TabBarItem-selected .tabTopLeft {
  background-position: 0px -61px;
}
.gwt-DecoratedTabBar .gwt-TabBarItem-selected .tabTopRight {
  background-position: -6px -61px;
}
.gwt-DecoratedTabBar .gwt-TabBarItem-selected .tabMiddleLeft,
.gwt-DecoratedTabBar .gwt-TabBarItem-selected .tabMiddleRight {
  background: #92c1f0;
}
.gwt-DecoratedTabBar .gwt-TabBarItem-selected .tabMiddleCenter {
  cursor: default;
  background: #92c1f0;
}
.gwt-DecoratedTabBar .gwt-TabBarItem-disabled .tabMiddleCenter {
  cursor: default;
  color: #999999;
}

.gwt-TextArea {
  padding: 2px;
}
.gwt-TextArea-readonly {
  color: #888;
}

.gwt-TextBox {
  padding: 2px;
}
.gwt-TextBox-readonly {
  color: #888;
}

.gwt-ToggleButton-up,
.gwt-ToggleButton-up-hovering,
.gwt-ToggleButton-up-disabled,
.gwt-ToggleButton-down,
.gwt-ToggleButton-down-hovering,
.gwt-ToggleButton-down-disabled {
  margin: 0;
  text-decoration: none;
  background: url("images/hborder.png") repeat-x 0px -27px;
}
.gwt-ToggleButton-up,
.gwt-ToggleButton-up-hovering,
.gwt-ToggleButton-up-disabled {
  padding: 3px 5px 3px 5px;
}
.gwt-ToggleButton-up {
  border: 1px outset #ccc;
  cursor: pointer;
  cursor: hand;
}
.gwt-ToggleButton-up-hovering {
  border: 1px outset;
  border-color: #9cf #69e #69e #7af;
  cursor: pointer;
  cursor: hand;
}
.gwt-ToggleButton-up-disabled {
  border: 1px outset #ccc;
  cursor: default;
  opacity: .5;
  zoom: 1;
  filter: alpha(opacity=40);
}
.gwt-ToggleButton-down,
.gwt-ToggleButton-down-hovering,
.gwt-ToggleButton-down-disabled {
  padding: 4px 4px 2px 6px;
}
.gwt-ToggleButton-down {
  background-position: 0 -513px;
  border: 1px inset #ccc;
  cursor: pointer;
  cursor: hand;
}
.gwt-ToggleButton-down-hovering {
  background-position: 0 -513px;
  border: 1px inset;
  border-color: #9cf #69e #69e #7af;
  cursor: pointer;
  cursor: hand;
}
.gwt-ToggleButton-down-disabled {
  background-position: 0 -513px;
  border: 1px inset #ccc;
  cursor: default;
  opacity: .5;
  zoom: 1;
  filter: alpha(opacity=40);
}

.gwt-Tree .gwt-TreeItem {
  padding: 1px 0px;
  margin: 0px;
  white-space: nowrap;
  cursor: hand;
  cursor: pointer;
  zoom: 1;
}
.gwt-Tree .gwt-TreeItem-selected {
  background: #93c2f1 url(images/hborder.png) repeat-x 0px -1463px;
}
.gwt-TreeItem .gwt-RadioButton input,
.gwt-TreeItem .gwt-CheckBox input {
  margin-right: 0px;
}
* html .gwt-TreeItem .gwt-RadioButton input,
* html .gwt-TreeItem .gwt-CheckBox input {
  margin-right: -4px;
}

.gwt-DateBox input {
  width: 8em;
}
.dateBoxFormatError {
  background: #ffcccc;
}
.dateBoxPopup {
}

.gwt-DatePicker {
  border: 1px solid #A2BBDD;
  cursor: default;
}
.gwt-DatePicker td,
.datePickerMonthSelector td:focus {
  outline: none
}
.datePickerDays {
  width: 100%;
  background: white;
}
.datePickerDay,
.datePickerWeekdayLabel,
.datePickerWeekendLabel {
  font-size: 75%;
  text-align: center;
  padding: 4px;
  outline: none;
}
.datePickerWeekdayLabel,
.datePickerWeekendLabel {
  background: #C3D9FF;
  padding: 0px 4px 2px;
  cursor: default;
}
.datePickerDay {
  padding: 4px;
  cursor: hand;
  cursor: pointer;
}
.datePickerDayIsToday {
  border: 1px solid black;
  padding: 3px;
}
.datePickerDayIsWeekend {
  background: #EEEEEE;
}
.datePickerDayIsFiller {
  color: #888888;
}
.datePickerDayIsValue {
  background: #aaccee;
}
.datePickerDayIsDisabled {
  color: #AAAAAA;
  font-style: italic;
}
.datePickerDayIsHighlighted {
  background: #F0E68C;
}
.datePickerDayIsValueAndHighlighted {
  background: #bbddd9;
}
.datePickerMonthSelector {
  background: #C3D9FF;
  width: 100%;
}
td.datePickerMonth {
  text-align: center;
  vertical-align: center;
  white-space: nowrap;
  font-size: 70%;
  font-weight: bold;
  color: blue;
}
.datePickerPreviousButton,
.datePickerNextButton {
  font-size: 120%;
  line-height: 1em;
  color: blue;
  cursor: hand;
  cursor: pointer;
  padding: 0px 4px;
}

.gwt-StackLayoutPanel {
  border-bottom: 1px solid #bbbbbb;
}
.gwt-StackLayoutPanel .gwt-StackLayoutPanelHeader {
  cursor: pointer;
  cursor: hand;
  font-weight: bold;
  font-size: 1.3em;
  padding: 3px;
  border: 1px solid #bbbbbb;
  border-bottom: 0px;
  background: #d3def6 url(images/hborder.png) repeat-x 0px -989px;
}
.gwt-StackLayoutPanel .gwt-StackLayoutPanelHeader-hovering {
  background: #d3def6 url(images/hborder.png) repeat-x 0px -1464px;
}
.gwt-StackLayoutPanel .gwt-StackLayoutPanelContent {
  border: 1px solid #bbbbbb;
  border-bottom: 0px;
  background: white;
  padding: 2px 5px 10px 2px;
}

.gwt-TabLayoutPanel {
}
.gwt-TabLayoutPanel .gwt-TabLayoutPanelTabs {
}
.gwt-TabLayoutPanel .gwt-TabLayoutPanelContent {
  border-color: #92c1f0;
  border-style: solid;
  border-width: 3px 2px 2px;
  overflow: hidden;
  padding: 6px;
}
.gwt-TabLayoutPanel .gwt-TabLayoutPanelTab {
  margin-left: 6px;
  padding: 3px 6px 3px 6px;
  cursor: pointer;
  cursor: hand;
  color: black;
  font-weight: bold;
  text-align: center;
  background: #d0e4f6;
}
.gwt-TabLayoutPanel .gwt-TabLayoutPanelTab-selected {
  cursor: default;
  background: #92c1f0;
}

.gwt-SplitLayoutPanel-HDragger {
  background: #d0e4f6 url(images/splitPanelThumb.png) center center no-repeat;
  cursor: col-resize;
}

.gwt-SplitLayoutPanel-VDragger {
  background: #d0e4f6 url(images/splitPanelThumb.png) center center no-repeat;
  cursor: row-resize;
}


text:
![screenshot](screen.png)

Alice in Clicheland is a game developed for Digital Games Development course, taken during our Computer Science grad school at UFMG. It is an action RPG game, where the action takes place in real time. With its 2D graphics and aerial view, Alice in Clicheland recalls SNES RPG games, like Final Fantasy and Zelda.

The game was made using C++ and Allegro 4 library.

## How to play

#### Player 1:
 - arrows: walk
 - A: attack
 - S: magic
 - Z: talk/examine
 - hold X: use stamina (runs, attacks faster)
 - 1, 2, 3, 4: select magic
 - Esc: quit the game
 - Tab: Change between multiplayer/single player

#### Player 2:
 - I, J, K, L: walk
 - D: attack
 - F: magic
 - C: talk/examine
 - hold V: use stamina (runs, attacks faster)
 - 5, 6, 7, 8: select magic

The keys used by player 2 are not very good, but that's because we made the game in a notebook without numeric keyboard. You can use a joystick with Xpadder to make things easier.

## Plot

Alice in Clicheland is a game set on a fantasy world, where two dimensions coexist. Those dimensions were separated by a great hero during Primordial War. For some reason, though, the seal that used to keep the dimensions apart was broken, chaining a new war, as Dark Clicheland's beings tried to invade the human world: Clicheland.

Alice is a young girl that joined the human army with her brother, Bob, seeking fame and money, that were promised by the governors during the crisis. After two long years of battle, her brother was brutally killed by the enemy forces, on Berun Battle. Her army went through many losses, being forced to flee from the battlefield. Suffering the loss of her brother, Alice gave up the soldier's carrier and went back to her quiet life as a seller...

## Developers

 - Matheus Silva Vilela (matheusv@dcc.ufmg.br)
 - Thiago Silva Vilela (thiagov@dcc.ufmg.br)
 - Vinicius Graciano Santos (vgs@dcc.ufmg.br)


text:
self.onmessage = function (msg) {
  let fun = msg.data.fun;
  if (fun in self)
    self[fun](msg.data.arg);
}

let lib;
let artcw_create, artcw_start_listening, artcw_stop_listening, artcw_destroy;
let artcw;

function init(libPath) {
  lib = ctypes.open(libPath);

  artcw_create = lib.declare("artcw_create", ctypes.default_abi, ctypes.voidptr_t);
  artcw_start_listening = lib.declare("artcw_start_listening", ctypes.default_abi, ctypes.void_t, ctypes.voidptr_t);
  artcw_stop_listening = lib.declare("artcw_stop_listening", ctypes.default_abi, ctypes.void_t, ctypes.voidptr_t);
  artcw_destroy = lib.declare("artcw_destroy", ctypes.default_abi, ctypes.void_t, ctypes.voidptr_t);

  artcw = artcw_create();
  let artcwAddressAsDecimalString = ctypes.cast(artcw, ctypes.uintptr_t).value.toString();

  if (ctypes.CDataFinalizer) {
    artcw = ctypes.CDataFinalizer(artcw, artcw_destroy);
  }

  listenerWorker = new ChromeWorker("AppleRemoteListenerWorker.js");
  listenerWorker.postMessage({
    artcwAddressAsDecimalString: artcwAddressAsDecimalString,
    libPath: libPath
  });
  listenerWorker.addEventListener("message", function workerSentMessage(msg) {
    let e = {
      type: msg.data.pressedDown ? "buttondown" : "buttonup",
      button: msg.data.type
    };
    self.postMessage(e);
    if (e.type == "buttondown")
      startAutorepeat(e.button);
    else
      stopAutorepeat(e.button);
  });
}

function startListening() {
  artcw_start_listening(artcw);
}

function stopListening() {
  artcw_stop_listening(artcw);
}

function shutdown() {
  if (ctypes.CDataFinalizer) {
    // XXX This shouldn't be necessary; this should happen automatically when
    // the worker is garbage collected, but it doesn't
    artcw.dispose();
  } else {
    artcw_destroy(artcw);
  }
  lib.close();
  self.close();
}

// Autorepeat stuff
// This automatically sends repeating buttonpress events while the button is
// down.

const kAutorepeatInitialDelay = 500; // ms
const kAutorepeatInterval = 100; // ms

let autorepeatTimers = {};

function startAutorepeat(button) {
  stopAutorepeat(button);
  autorepeatTimers[button] = setTimeout(function () {
    repeatButtonPress(button);
  }, kAutorepeatInitialDelay);
  sendButtonPress(button);
}

function sendButtonPress(button) {
  self.postMessage({
    type: "buttonpress",
    button: button
  });
}

function repeatButtonPress(button) {
  sendButtonPress(button);
  autorepeatTimers[button] = setTimeout(function () {
    repeatButtonPress(button);
  }, kAutorepeatInterval);
}

function stopAutorepeat(button) {
  if (button in autorepeatTimers) {
    clearTimeout(autorepeatTimers[button]);
    delete autorepeatTimers[button];
  }
}


text:
/** \file fastformat/sinks/iostream.hpp
 *
 * [C++ only] Shorthand header that includes the FastFormat sink for
 *   IOStreams' std::ostream and the standard header
 * \<iostream\>.
 */

#ifndef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_IOSTREAM
#define FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_IOSTREAM

/* /////////////////////////////////////////////////////////////////////////
 * Version information
 */

#ifndef FASTFORMAT_DOCUMENTATION_SKIP_SECTION
# define FASTFORMAT_VER_FASTFORMAT_SINK_HPP_IOSTREAM_MAJOR      1
# define FASTFORMAT_VER_FASTFORMAT_SINK_HPP_IOSTREAM_MINOR      0
# define FASTFORMAT_VER_FASTFORMAT_SINK_HPP_IOSTREAM_REVISION   1
# define FASTFORMAT_VER_FASTFORMAT_SINK_HPP_IOSTREAM_EDIT       2
#endif /* !FASTFORMAT_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * Language
 */

#ifndef __cplusplus
# error This file can only be included in C++ compilation units
#endif /* !__cplusplus */

/* /////////////////////////////////////////////////////////////////////////
 * Includes
 */

#include <fastformat/fastformat.h>
#include <fastformat/sinks/ostream.hpp>

#include <iostream>

/* ////////////////////////////////////////////////////////////////////// */

#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_IOSTREAM */

/* ///////////////////////////// end of file //////////////////////////// */


text:
"""
Created on Sun Feb 01 13:52:23 2015
Some helper methods

@author: Seb
"""

import math
import numpy as np
import mieMonteCarlo
import subprocess
import os
from setup import systemPaths

import contextlib

@contextlib.contextmanager
def cd(newPath):
    savedPath = os.getcwd()
    os.chdir(newPath)
    yield
    os.chdir(savedPath)

def createSimulationFile(infile, replacements, simulationFileName):
    infile.seek(0);
    simulationFile = open(simulationFileName, 'w')

    for line in infile:
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        simulationFile.write(line)

    simulationFile.close()

def calcUa(BVF, cHb, SaO2, eHbO2, eHb, wavelength):
    # determine ua [1/m] as combination of extinction coefficients.
    # For more on this equation, please refer to
    # http://omlc.org/spectra/hemoglobin/
    return math.log(10) * cHb * \
        (SaO2 * eHbO2(wavelength) +  (1-SaO2) * eHb(wavelength)) \
        / 64500 * BVF

def calcUsMuscle(wavelength):
    return 168.52 * (wavelength * 10**9)**-0.332 / (1 - 0.96) * 100

def getReflectanceFromFile(fileName):
    '''
    extract reflectance from a specific monte carlo output file.

    Attention: this is kept very simple and assumes that the reflectance output
    starts at a specific line and keeps till eof. This might be subject to change,
    e.g., when you alter the numbers of layers the line number there reflectance
    values start will change.
    Error handling etc. needed.
    '''

    with open(fileName) as myFile:
        for num, line in enumerate(myFile, 1):
            if "Rd_r #Rd[0], [1],..Rd[nr-1]. [1/cm2]" in line:
                break

    #print 'found at line:', num

    reflectances = np.loadtxt(fileName, skiprows=num)

    return sum(reflectances)

from setup import simulation

def normalizeIntegral(data):
    # normalize data
    # first sort by wavelength:
    ourWavelengths = simulation.wavelengths
    #ourWavelengths = np.delete(simulation.getWavelengths(), [2,7])

    sortedIndices = sorted(range(len(ourWavelengths)), key=lambda k: ourWavelengths[k])

    norms = np.trapz(data[:,sortedIndices], ourWavelengths[sortedIndices], axis=1)
    return data / norms[:,None]

def normalizeSum(data):
    return data/data.sum(axis=1)[:,None]

def normalizeMean(data):
    return data - data.mean(axis=1)[:,None]

iqBand = 2

def normalizeImageQuotient(data):

    # use line iqBand as image quotient
    normData = data / data[:,iqBand][:,None]
    # discard it
    normData = np.delete(normData, iqBand, axis=1)

    #normData = normalizeMean(normData)

    return normData
    #return normalizeIntegral(data)

    #return normalizeMean(firstNorm)

def removeIqWavelength(wavelenghts):
    #return wavelenghts
    return np.delete(wavelenghts, iqBand)

def runOneSimulation(wavelength, eHbO2, eHb,
                     infile, simulationOutputFolderName, gpumcmlDirectory, gpumcmlExecutable,
                     BVF=0.1, Vs=0.4, d=500 * 10**-6,
                     r=0.4 * 10**-6, SaO2=0.7, cHb=120,
                     submucosa_BVF=0.1, submucosa_Vs=0.3, submucosa_r = 2*10**-6, submucosa_SaO2=0.7,
                     Fwhm = 20 * 10**-9, nrPhotons = 10**6,
                     ):
    """
    Args:
    _____
    cHb:
        concentration of haemoglobin per unit volume of blood in colon [g/L],
        taken from: "Modelling and validation of spectral reflectance for the colon"
    """
    outputFilename = \
            simulationOutputFolderName + \
            "BVF" + repr(BVF) + \
            "Vs" + repr(Vs) + \
            "d" + repr(d) + \
            "SaO2" + repr(SaO2) + \
            "r" + repr(r) + \
            "photons" + repr(nrPhotons) + \
            "wavelength" + repr(wavelength) + \
            ".mco"

    usg = mieMonteCarlo.mieMonteCarlo_FWHM(wavelength, r, Vs, FWHM = Fwhm)

    ua  = calcUa(BVF, cHb, SaO2, eHbO2, eHb, wavelength)
    # calculate ua, us for submucosa, values taken from
    # "Model based inversion for deriving maps of
    # histological parameters characteristic of cancer
    # from ex-vivo multispectral images of the colon"
    ua_sm  = calcUa(submucosa_BVF, cHb, submucosa_SaO2, eHbO2, eHb, wavelength)
    usg_sm = mieMonteCarlo.mieMonteCarlo_FWHM(wavelength,submucosa_r, submucosa_Vs, FWHM = Fwhm)

    # now create us and ua for muscle layer according to
    # "Modelling and validation of spectral reflectance for the colon"
    us_mus = calcUsMuscle(wavelength)
    A      = 1.7923385088285804 # calculated to retrieve an absorption of 11.2 cm-1
    # at 515nm
    ua_mus = calcUa(A*0.1, 120, 0.7, eHbO2, eHb, wavelength)

    # factors are due to the program expecting [cm] instead of [m]
    replacements = {'muc_c_ua':str(ua / 100), 'muc_c_us':str(usg['us'] / 100),
        'muc_c_g':str(usg['g']), 'muc_c_d':str(d * 100),
        'sm_c_ua':str(ua_sm / 100), 'sm_c_us':str(usg_sm['us'] / 100),
        'sm_c_g':str(usg_sm['g']),
        'mus_c_ua':str(ua_mus / 100), 'mus_c_us':str(us_mus / 100),
        'outputFilename':outputFilename,
        'c_ph': str(nrPhotons)}

    createSimulationFile(infile, replacements,
                         systemPaths.getOutputFolder() + "simulationFile.mci")

    args = ("./" + gpumcmlExecutable, "-A", systemPaths.getOutputFolder() + "simulationFile.mci")

    with cd(gpumcmlDirectory):
        popen = subprocess.Popen(args, stdout=subprocess.PIPE)
        popen.wait()

    # outside the context manager we are back wherever we started.

    # this function is error prone, please refer to documentation to see
    # if problematic for you
    return getReflectanceFromFile(gpumcmlDirectory + outputFilename)

if __name__ == "__main__":

    us515 = calcUsMuscle(515 * 10**-9)
    print ("calculated us [cm-1] for muscle layer at 515nm: " + str(us515 / 100) + " expected ca. 530")
    us1064 = calcUsMuscle(1064 * 10**-9)
    print ("calculated us [cm-1] for muscle layer at 1064nm: " + str(us1064 / 100))


text:
window.onload = function () {

	'use strict';

	console.log('main.js');

	var dsystem = {
		DiceSides: 100,
		Percentual: false,
		BaseSkill: 50,
		OpenRoll: true,
		BonusSkill: 0,
		HistoryBox: 'RollBox',

		CriticalTreshold: 10,
		CriticalMultiplier: 2, //Critical damage multiplier
		CriticalPierceArmor: true, //critical hits ignores armor

		SpecialRoll: true,
		SpecialRollMultiplier: 1.5,
		SpecialRollTreshold: 20,
		SpecialRollPierceArmor: true,

		EpicFail: true,
		EpicFailTreshold: 10,
		EpicFailMaxTreshold: 96,
		EpicFailMinTreshold: 100,

		DirectFail: 96,
		TagElement : 'p',
		StyleCSS : 'lround lround'

	};

	var system = D(dsystem);

	var armor = {
			physic : [ { Name: 'Physic', Sides : 6, Fixed : 2, Rolls : 1 } ],
			dmgreduction : [ { Name: 'Damage Reduction', Sides : 0, Fixed : 1, Rolls : 1 } ],
			arcane : [ { Name: 'Arcane', Sides : 8, Fixed : 1, Rolls : 3 } ],
			fire : [ { Name: 'Fire', Sides : 10, Fixed : 0, Rolls : 1 } ],
			frost : [ { Name: 'Frost', Sides : 6, Fixed : 0, Rolls : 2 } ],
			electric : [ { Name: 'Electric', Sides : 0, Fixed : 4, Rolls : 0 } ],
			poison : [ { Name: 'Poison', Sides : 0, Fixed : 1, Rolls : 0 } ]
		};

	var listenclick1 = document.getElementById('button1');
	var listenclick2 = document.getElementById('button2');
	var listenclick3 = document.getElementById('button3');
	var listenclick4 = document.getElementById('button4');
	var listenclick5 = document.getElementById('button5');
	var listenclick6 = document.getElementById('button6');
	var listenclick7 = document.getElementById('button7');
	var listenclick8 = document.getElementById('button8');
	var listenclick9 = document.getElementById('button9');

	var listencheckbox1 = document.getElementById('ChkTechDamage');

	listenclick1.addEventListener('click',function(){
		D(dsystem).roll(3,6,0);
	}, true);

	listenclick2.addEventListener('click', function(){
		system.Percentual = false;
		system.damage({
			Sides : 20,
			ModDamage: 10,
			Rolls: 1,
			TypeDamage:'Physic'
		},
			system.skill(1,0,10,false,false), true);

	}, true);

	listenclick3.addEventListener('click',function(){
		system.Percentual = false;

		var DmgResult = system.damage({
			Sides : [ 100, 100, 8, 4 ],
			ModDamage: [ 20, -25, -1, -3 ],
			Rolls: [ 2, 1, 2, 1 ],
			TypeDamage:['Physic', 'arcane', 'fire', 'poison']
		},
			system.skill(1,0,10,false,false), true);

		system.armor(armor, DmgResult, true);

	}, true);

	listenclick4.addEventListener('click', function(){

		var DmgResult = {
			Damage: 15,
			ModDamage: 20,
			Rolls: 1,
			Sides: 100,
			Critical: true,
			Special: false,
			TypeDamage: "Physic"
		};

		system.armor(armor, DmgResult, true);

	});
	listenclick5.addEventListener('click',function(){

		dsystem.Percentual = true;

		D(dsystem).skill(1,0,10,50,50);

	}, true);
	listenclick6.addEventListener('click',function(){
		/**
		 * dx(sides, rolls, difficulty, wildDice)
		 */
		D().dx(6,8,20,true);
	}, true);
	listenclick7.addEventListener('click', function(){
		D().vda(10,6,8);
	});

	listenclick8.addEventListener('click', function(){

		var crit =  15;

		D().d20({
			Sides: 20,
			Rolls: 1,
			Mod: 5,
			Difficulty: 20,
			Critical: crit,
			EpicFail: true
		});

	}, false);

	listenclick9.addEventListener('click', function(){
		var critical = 10,
			special = 20,
			epicfail = 5;
		D(dsystem).confront(15,15);
	}, false );

};


text:
using System;

public class CorrectBrackets
{
    public static void Main(string[] args)
    {
        var expression = Console.ReadLine();
        var counter = 0;

        for (int i = 0; i < expression.Length; i++)
        {
            if (expression[i] == '(')
            {
                ++counter;
            }
            else if (expression[i] == ')')
            {
                --counter;
            }
        }

        var result = counter == 0 ? "Correct" : "Incorrect";
        Console.WriteLine(result);
    }
}