text:
This is the code for a two different versions of a 3 species theoretical metacommunity.  Its rules
are based on competition / colonization trade-off rules.
A talk describing the rules used can be found here http://www.slideshare.net/DistribEcology/modeling-metacommunties
There are two verisions, one with simple visualizations in NetLogo and a full version in R.

Usage:

```R
$ Rscript Agent_Based_Metacommunity.R 10
```

This will run the model for 10 time steps


text:
package cz.sparko.speakup.events;

import org.springframework.web.socket.messaging.SessionConnectEvent;

public class LoginEvent {
    private final SessionConnectEvent sessionConnectEvent;

    public LoginEvent(SessionConnectEvent sessionConnectEvent) {
        this.sessionConnectEvent = sessionConnectEvent;
    }

    public SessionConnectEvent getSessionConnectEvent() {
        return sessionConnectEvent;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.planet_ink.coffee_mud.Abilities.Fighter;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Fighter_ImprovedShieldDefence extends FighterSkill
{
	public String ID() { return "Fighter_ImprovedShieldDefence"; }
	public String name(){ return "Improved Shield Defence";}
	public String displayText(){ return "";}
	protected int canAffectCode(){return CAN_MOBS;}
	protected int canTargetCode(){return 0;}
	public int abstractQuality(){return Ability.QUALITY_BENEFICIAL_SELF;}
    public int classificationCode(){return Ability.ACODE_SKILL|Ability.DOMAIN_SHIELDUSE;}
	public boolean isAutoInvoked(){return true;}
	public boolean canBeUninvoked(){return false;}
    protected boolean gettingBonus=false;

	public void affectEnvStats(Environmental affected, EnvStats affectableStats)
	{
		gettingBonus=false;
		if((affected==null)||(!(affected instanceof MOB))) return;
		Item w=((MOB)affected).fetchFirstWornItem(Wearable.WORN_HELD);
		if((w==null)||(!(w instanceof Shield))) return;
		gettingBonus=true;
		affectableStats.setArmor(affectableStats.armor()-((int)Math.round(CMath.mul(w.envStats().armor(),(CMath.div(proficiency(),100.0+(5.0*getXLEVELLevel(invoker()))))))));
	}
	public void executeMsg(Environmental myHost, CMMsg msg)
	{
		super.executeMsg(myHost,msg);

		if((affected==null)||(!(affected instanceof MOB)))
			return;

		MOB mob=(MOB)affected;

		if((msg.amITarget(mob))
		&&(gettingBonus)
		&&(msg.targetMinor()==CMMsg.TYP_WEAPONATTACK)
		&&(mob.isInCombat())
		&&(CMLib.dice().rollPercentage()==1)
		&&(!mob.amDead()))
			helpProficiency(mob);
	}

}


text:
package cz.zcu.fav.remotestimulatorcontrol.ui.configurations.detail.rea;

import android.databinding.BindingAdapter;
import android.support.v7.widget.AppCompatRadioButton;

import cz.zcu.fav.remotestimulatorcontrol.model.configuration.rea.ConfigurationREA;

/**
 * Knihovní třída obsahující metody týkající se "data bindingu"
 */
public final class ConfigurationREABindings {

    // region Constructors
    /**
     * Privátní konstruktor k zabránění vytvoření instance knihovní třídy
     */
    private ConfigurationREABindings() {
        throw new AssertionError();
    }
    // endregion

    @BindingAdapter({"value", "flag"})
    public static void setCompatRadioButtonChecked(AppCompatRadioButton view, ConfigurationREA.Gender value , ConfigurationREA.Gender flag) {
        view.setChecked(value == flag);
    }

    @BindingAdapter({"value", "flag"})
    public static void setCompatRadioButtonChecked(AppCompatRadioButton view, ConfigurationREA.OnFail value , ConfigurationREA.OnFail flag) {
        view.setChecked(value == flag);
    }

}


text:
declare function foo(): void;
declare function bar(): void;

//// [parser509698.js]


text:
{-# LANGUAGE CPP                       #-}
{-# LANGUAGE DeriveDataTypeable        #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts          #-}
{-# LANGUAGE FlexibleInstances         #-}
{-# LANGUAGE MultiParamTypeClasses     #-}
{-# LANGUAGE RankNTypes                #-}
{-# LANGUAGE RecordWildCards           #-}
{-# LANGUAGE TypeFamilies              #-}
{-# LANGUAGE FunctionalDependencies    #-}

{-# LANGUAGE UndecidableInstances      #-}
{-# LANGUAGE ConstraintKinds           #-}

{-# LANGUAGE StandaloneDeriving        #-}

{-# OPTIONS_GHC -fno-warn-orphans #-}

module Plots.Types.Line
  ( -- * Trail plot
    mkTrail
  , mkTrailOf

    -- * Path plot
  , mkPath
  , mkPathOf

    -- * GLinePlot plot
  , GLinePlot
  , _LinePlot
  , mkGLinePlotOf
  , mkGLinePlot

    -- * Line plot
  , LinePlot
  , mkLinePlotOf
  , mkLinePlot

    -- * Helper functions
  , createStepData

    -- * Lenses
  , dotsonPoint
  , pathStyle

    -- * Line Plot
  , linePlot
  , linePlot'
  , linePlot''
  , linePlotL
  , linePlotOf
  , linePlotOf'
  , linePlotLOf

  , pathPlot''

  --, createstep
    -- * Step plot
  , stepPlot
  , stepPlot'
  , stepPlotL

    -- * Gline plot
  , glinePlot
  , glinePlot'
  , glinePlotL
  ) where

import           Control.Lens     hiding (transform, ( # ), lmap)
import           Control.Monad.State.Lazy

import qualified Data.Foldable    as F
import           Data.Typeable

import           Diagrams.Coordinates.Isomorphic
import           Diagrams.Prelude  hiding (view)

import           Plots.Themes
import           Plots.Types
import           Plots.API

------------------------------------------------------------------------
-- Trail and path
------------------------------------------------------------------------

mkTrail :: (PointLike v n p, OrderedField n, F.Foldable f) => f p -> Located (Trail v n)
mkTrail = mkTrailOf folded

mkTrailOf :: (PointLike v n p, OrderedField n) => Fold s p -> s -> Located (Trail v n)
mkTrailOf f ps = fromVertices $ toListOf (f . unpointLike) ps

mkPathOf :: (PointLike v n p, OrderedField n) => Fold s t -> Fold t p -> s -> Path v n
mkPathOf f1 f2 as = Path $ map (mkTrailOf f2) (toListOf f1 as)

mkPath :: (PointLike v n p, OrderedField n, F.Foldable f, F.Foldable g) => g (f p) -> Path v n
mkPath = mkPathOf folded folded

instance (TypeableFloat n, Renderable (Path V2 n) b) => Plotable (Path V2 n) b where
  renderPlotable s path pp
    = stroke path
        # transform (s^.specTrans)
        # applyLineStyle pp

  defLegendPic _ pp
    = (p2 (-10,0) ~~ p2 (10,0))
        # applyLineStyle pp

------------------------------------------------------------------------
-- GLine plot
------------------------------------------------------------------------

data GLinePlot v n a = forall s. GLinePlot
  { sData :: s
  , sFold :: Fold s a
  , sPos  :: a -> Point v n
  , sSty  :: Maybe (a -> Style V2 n)
  , cPnt  :: Bool
  } deriving Typeable

type instance V (GLinePlot v n a) = v
type instance N (GLinePlot v n a) = n

instance (Metric v, OrderedField n) => Enveloped (GLinePlot v n a) where
  getEnvelope GLinePlot {..} = foldMapOf (sFold . to sPos) getEnvelope sData

instance (Typeable a, Typeable b, TypeableFloat n, Renderable (Path V2 n) b)
    => Plotable (GLinePlot V2 n a) b where
  renderPlotable s GLinePlot {..} pp =
      fromVertices (toListOf (sFold . to sPos . to (logPoint ls)) sData)
        # transform t
        # applyLineStyle pp
   <> if cPnt
        then foldMapOf sFold mk sData # applyMarkerStyle pp
        else mempty
    where
      t = s ^. specTrans
      ls = s ^. specScale
      mk a = marker # maybe id (applyStyle . ($ a)) sSty
                    # moveTo (specPoint s $ sPos a)
      marker = pp ^. plotMarker

  defLegendPic GLinePlot {..} pp
      = (p2 (-10,0) ~~ p2 (10,0))
          # applyLineStyle pp

_LinePlot :: (Plotable (LinePlot v n) b, Typeable b)
             => Prism' (Plot b v n) (LinePlot v n)
_LinePlot = _Plot

------------------------------------------------------------------------
-- Line Plot
------------------------------------------------------------------------

type LinePlot v n = GLinePlot v n (Point v n)

-- | Make a line plot.
mkLinePlot :: (PointLike v n p, F.Foldable f, Num n)
              => f p -> LinePlot v n
mkLinePlot = mkLinePlotOf folded

-- | Make a line plot using the given fold.
mkLinePlotOf :: (PointLike v n p, Num n)
                => Fold s p -> s -> LinePlot v n
mkLinePlotOf f a = GLinePlot
  { sData = a
  , sFold = f . unpointLike
  , sPos  = id
  , sSty  = Nothing
  , cPnt  = False
  }

------------------------------------------------------------------------
-- Helper functions
------------------------------------------------------------------------

-- | Create a data for step plots.
createStepData :: [(a,a)] -> [(a,a)]
createStepData [] = []
createStepData (x1:[]) = x1:[]
createStepData (x1:x2:xs) = (x1):(fst x1, snd x2):(x2):(createStepData (x2:xs))

-- type StepPlot v n = GLinePlot v n (Point v n)

-- mkStepPlotOf :: (PointLike v n p, Fractional n)
--                => Fold s p -> s -> StepPlot v n
-- mkStepPlotOf f a = GLinePlot
--   { sData = a
--   , sFold = f . unpointLike
--   , sPos  = id
--   , sSty  = Nothing
--   , cPnt  = False
--   }

-- mkStepPlot :: (PointLike v n p, F.Foldable f, Fractional n)
--              => f p -> StepPlot v n
-- mkStepPlot = mkStepPlotOf folded

------------------------------------------------------------------------
-- General Line Plot
------------------------------------------------------------------------

-- | Plot a general line plot.
mkGLinePlot :: (PointLike v n p, F.Foldable f, Fractional n)
               => f a -> (a -> p) -> GLinePlot v n a
mkGLinePlot = mkGLinePlotOf folded

-- | Plot a general line plot give a fold
mkGLinePlotOf :: (PointLike v n p, Fractional n)
                 => Fold s a -> s -> (a -> p) -> GLinePlot v n a
mkGLinePlotOf f a pf = GLinePlot
  { sData = a
  , sFold = f
  , sPos  = view unpointLike . pf
  , sSty  = Nothing
  , cPnt = False
  }

------------------------------------------------------------------------
-- Line plot lenses
------------------------------------------------------------------------

class HasPath a v n d | a -> v n, a -> d where
  line :: Lens' a (GLinePlot v n d)

  pathStyle :: Lens' a (Maybe (d -> Style V2 n))
  pathStyle  = line . lens sSty (\sp sty -> sp {sSty = sty})

  dotsonPoint :: Lens' a Bool
  dotsonPoint = line . lens cPnt (\s b -> (s {cPnt = b}))

instance HasPath (GLinePlot v n d) v n d where
  line = id

instance HasPath (PropertiedPlot (GLinePlot v n d) b) v n d where
  line = _pp

------------------------------------------------------------------------
-- Line plot
------------------------------------------------------------------------

-- $ line
-- line plots display data as dots. There are several representations
-- for line plots for extra parameters. Line plots have the
-- following lenses:
--
-- @
-- * 'dotsonPoint' :: 'Lens'' ('LinePlot' v n) 'Bool' - False
-- * 'lineStyle'   :: 'Maybe' ('Point' v n -> 'Style' 'V2' n) - Nothing
-- @
--
-- | Add a 'LinePlot' to the 'AxisState' from a data set.
--
-- @
--   myaxis = r2Axis ~&
--     linePlot data1
-- @
-- === __Example__
--
-- <<plots/line.png#diagram=line&width=300>>
--
-- @
--
-- myaxis :: Axis B V2 Double
-- myaxis = r2Axis &~ do
--          linePlot  mydata1
--          linePlot' mydata2 $ do
--               addLegendEntry "data 2"
--               plotColor .= black
--               dotsonPoint .= False
--          linePlotL "data 3" mydata3
--
--          axisPlots . each . _LinePlot' . dotsonPoint .= True
--
-- @

linePlot
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      Plotable (LinePlot v n) b,
      F.Foldable f)
  => f p -> m ()
linePlot d = addPlotable (mkLinePlot d)

-- | Make a 'LinePlot' and take a 'State' on the plot to alter it's
--   options
--
linePlot'
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      Plotable (LinePlot v n) b,
      F.Foldable f)
  => f p -> PlotState (LinePlot v n) b -> m ()
linePlot' d = addPlotable' (mkLinePlot d)

-- | Add a 'LinePlot' with the given name for the legend entry.
--
-- @
--   myaxis = r2Axis &~ do
--     linePlotL "blue team" pointData1
--     linePlotL "red team" pointData2
-- @
linePlotL
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      Plotable (LinePlot v n) b,
      F.Foldable f)
  => String -> f p -> m ()
linePlotL l d = addPlotableL l (mkLinePlot d)

-- | mkTrail version of line plot

linePlot''
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      R2Backend b n,
      Plotable (Path v n) b,
      F.Foldable f)
  => f p -> m ()
linePlot'' d = addPlotable (mkPath $ Identity d)

pathPlot'' :: (R2Backend b n, MonadState (Axis b V2 n) m) => Path V2 n -> m ()
pathPlot'' = addPlotable

-- Fold variants

linePlotOf
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      Plotable (LinePlot v n) b)
  => Fold s p -> s -> m ()
linePlotOf f s = addPlotable (mkLinePlotOf f s)

linePlotOf'
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      Plotable (LinePlot v n) b)
  => Fold s p -> s -> PlotState (LinePlot v n) b -> m ()
linePlotOf' f s = addPlotable' (mkLinePlotOf f s)

linePlotLOf
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      Plotable (LinePlot v n) b)
  => String -> Fold s p -> s -> m ()
linePlotLOf l f s = addPlotableL l (mkLinePlotOf f s)

------------------------------------------------------------------------
--Step
------------------------------------------------------------------------

stepPlot :: (RealFloat n, Typeable n, Typeable b, Renderable (Path V2 n) b,
             MonadState (Axis b c n) m, BaseSpace c ~ V2)
         => [(n, n)] -> m ()
stepPlot  a   = linePlot (createStepData a)

stepPlot' :: (RealFloat n, Typeable n, Typeable b, Renderable (Path V2 n) b,
              MonadState (Axis b c n) m, BaseSpace c ~ V2) =>
             [(n, n)] -> PlotState (LinePlot V2 n) b -> m ()
stepPlot' a   = linePlot' (createStepData a)

stepPlotL :: (RealFloat n, Typeable n, Typeable b, Renderable (Path V2 n) b,
              MonadState (Axis b c n) m, BaseSpace c ~ V2) =>
             String -> [(n, n)] -> m ()
stepPlotL l a = linePlotL l (createStepData a)

------------------------------------------------------------------------
-- General Line Plot
------------------------------------------------------------------------

glinePlot
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      Plotable (GLinePlot v n a) b,
      F.Foldable f)
  => f a -> (a -> p) -> m ()
glinePlot d pf = addPlotable (mkGLinePlot d pf)

glinePlot'
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      Plotable (GLinePlot v n a) b,
      F.Foldable f)
  => f a -> (a -> p) -> PlotState (GLinePlot v n a) b -> m ()
glinePlot' d pf = addPlotable' (mkGLinePlot d pf)

glinePlotL
  :: (v ~ BaseSpace c,
      PointLike v n p,
      MonadState (Axis b c n) m,
      Plotable (GLinePlot v n a) b,
      F.Foldable f)
  => String -> f a -> (a -> p) -> m ()
glinePlotL l d pf = addPlotableL l (mkGLinePlot d pf)


text:
from cStringIO import StringIO

from pandas.core.frame import DataFrame
from pandas.core.matrix import DataMatrix
from pandas.core.series import Series
import pandas.lib.tseries as tseries

class GroupDict(dict):
    def __repr__(self):
        stringDict = dict([(str(x), x) for x in self])
        sortedKeys = sorted(stringDict)

        maxLen = max([len(x) for x in stringDict])

        output = StringIO()
        output.write(str(self.__class__))

        for k in sortedKeys:
            key = stringDict[k]
            size = len(self[key])
            output.write('\n %s -> %d values' % (str(k).ljust(maxLen), size))

        return output.getvalue()

def groupby(obj, grouper, **kwds):
    """
    Intercepts creation and dispatches to the appropriate class based
    on type.
    """
    if isinstance(obj, Series):
        klass = SeriesGroupBy
    elif isinstance(obj, DataMatrix):
        klass = DataMatrixGroupBy
    elif isinstance(obj, DataFrame):
        klass = DataFrameGroupBy
    else: # pragma: no cover
        raise TypeError('invalid type: %s' % type(obj))

    return klass(obj, grouper, **kwds)

class GroupBy(object):
    """
    Class for grouping and aggregating relational data.

    Supported classes: Series, DataFrame, DataMatrix
    """
    _groups = None
    _group_indices = None

    def __init__(self, obj, grouper):
        self.obj = obj
        if hasattr(grouper, 'get'):
            grouper = grouper.get
        self.grouper = grouper

    @property
    def groups(self):
        if self._groups is None:
            axis = self._group_axis
            self._groups = tseries.groupby(axis, self.grouper,
                                           output=GroupDict())

        return self._groups

    @property
    def group_indices(self):
        if self._group_indices is None:
            axis = self._group_axis
            self._group_indices = tseries.groupby_indices(axis,
                                                          self.grouper)

        return self._group_indices

    @property
    def _group_axis(self):
        # default
        return self.obj.index

    def getGroup(self, groupList):
        return self.obj.reindex(groupList)

    def __iter__(self):
        """
        Groupby iterator

        Returns
        -------
        Generator yielding sequence of (groupName, subsetted object)
        for each group
        """
        try:
            groupNames = sorted(self.groups)
        except Exception: # pragma: no cover
            groupNames = self.groups.keys()

        for groupName in groupNames:
            yield groupName, self[groupName]

    def aggregate(self, func):
        raise NotImplementedError

    def agg(self, func):
        return self.aggregate(func)

    def _aggregate_generic(self, getter, agger, axis=0):
        result = {}
        for name, group in self.groups.iteritems():
            data = getter(self.obj, group)

            try:
                result[name] = agger(data)
            except Exception:
                result[name] = data.apply(agger, axis=axis)

        return result

    def transform(self, func):
        raise NotImplementedError

    def __getitem__(self, key):
        return self.getGroup(self.groups[key])

class SeriesGroupBy(GroupBy):

    def aggregate(self, applyfunc):
        """
        See doc for DataFrame.groupby, group series using mapper (dict or key
        function, apply given function to group, return result as series).

        Main difference here is that applyfunc must return a value, so that the
        result is a sensible series.

        Parameters
        ----------
        mapper : function
            Called on each element of the Series index to determine the groups
        applyfunc : function
            Function to use to aggregate each group

        Returns
        -------
        Series or DataFrame
        """
        if hasattr(applyfunc,'__iter__'):
            retVal = self._aggregate_multiple(applyfunc)
        else:
            try:
                result = self._aggregate_simple(applyfunc)
            except Exception:
                result = self._aggregate_named(applyfunc)

            retVal = Series(result)

        return retVal

    def _aggregate_multiple(self, applyfunc):
        if not isinstance(applyfunc, dict):
            applyfunc = dict((func.__name__, func) for func in applyfunc)

        results = {}

        for name, func in applyfunc.iteritems():
            result = self.aggregate(func)
            results[name] = result

        return DataFrame(results)

    def _aggregate_simple(self, applyfunc):
        values = self.obj.values
        result = {}
        for k, v in self.group_indices.iteritems():
            result[k] = applyfunc(values.take(v))

        return result

    def _aggregate_named(self, applyfunc):
        result = {}
        for groupName in self.groups:
            grp = self[groupName]
            grp.groupName = groupName
            output = applyfunc(grp)

            if isinstance(output, Series):
                raise Exception('Given applyfunc did not return a '
                                'value from the subseries as expected!')

            result[groupName] = output

        return result

    def transform(self, applyfunc):
        """
        For given Series, group index by given mapper function or dict, take
        the sub-Series (reindex) for this group and call apply(applyfunc)
        on this sub-Series. Return a Series of the results for each
        key.

        Parameters
        ----------
        mapper : function
            on being called on each element of the Series
            index, determines the groups.

        applyfunc : function to apply to each group

        Note
        ----
        This function does not aggregate like groupby/tgroupby,
        the results of the given function on the subSeries should be another
        Series.

        Example
        -------
        series.fgroupby(lambda x: mapping[x],
                        lambda x: (x - mean(x)) / std(x))

        Returns
        -------
        Series standardized by each unique value of mapping
        """

        result = {}
        for val, subseries in self:
            subseries.groupName = val
            result[val] = applyfunc(subseries)

        if not isinstance(result.values()[0], Series):
            raise Exception('Given applyfunc did not return a Series from '
                            ' the subseries as expected!')

        allSeries = {}
        for val, subseries in result.iteritems():
            allSeries.update(subseries.iteritems())

        return Series(allSeries)

class DataFrameGroupBy(GroupBy):
    _klass = DataFrame

    def __init__(self, obj, grouper, axis=0):
        if isinstance(grouper, basestring):
            grouper = obj[grouper].get

        self.axis = axis

        if axis not in (0, 1): # pragma: no cover
            raise Exception('invalid axis')

        GroupBy.__init__(self, obj, grouper)

    @property
    def _group_axis(self):
        if self.axis == 0:
            return self.obj.index
        else:
            return self.obj.columns

    def aggregate(self, applyfunc):
        """
        For given DataFrame, group index by given mapper function or dict, take
        the sub-DataFrame (reindex) for this group and call apply(applyfunc)
        on this sub-DataFrame. Return a DataFrame of the results for each
        key.

        Parameters
        ----------
        mapper : function, dict-like, or string
            Mapping or mapping function. If string given, must be a column
            name in the frame
        applyfunc : function
            Function to use for aggregating groups

        N.B.: applyfunc must produce one value from a Series, otherwise
        an error will occur.

        Optional: provide set mapping as dictionary
        """
        axis_name = 'columns' if self.axis else 'index'
        getter = lambda df, group: df.reindex(**{axis_name : group})
        result_d = self._aggregate_generic(getter, applyfunc,
                                           axis=self.axis)

        result = DataMatrix(result_d)

        if self.axis == 0:
            result = result.T

        return result

    def getGroup(self, groupList):
        if self.axis == 0:
            return self.obj.reindex(groupList)
        else:
            return self.obj.reindex(columns=groupList)

    def transform(self, applyfunc):
        """
        For given DataFrame, group index by given mapper function or dict, take
        the sub-DataFrame (reindex) for this group and call apply(applyfunc)
        on this sub-DataFrame. Return a DataFrame of the results for each
        key.

        Note: this function does not aggregate like groupby/tgroupby,
        the results of the given function on the subDataFrame should be another
        DataFrame.

        Parameters
        ----------
        mapper : function, dict-like, or string
            Mapping or mapping function. If string given, must be a column
            name in the frame
        applyfunc : function
            Function to apply to each subframe

        Note
        ----
        Each subframe is endowed the attribute 'groupName' in case
        you need to know which group you are working on.

        Example
        --------
        df.fgroupby(lambda x: mapping[x],
                    lambda x: (x - x.apply(mean)) / x.apply(std))

            DataFrame standardized by each unique value of mapping
        """
        result = {}
        for val, group in self.groups.iteritems():
            subframe = self.obj.reindex(list(group))
            subframe.groupName = val
            result[val] = applyfunc(subframe).T

        allSeries = {}
        for val, frame in result.iteritems():
            allSeries.update(frame._series)

        return self._klass(data=allSeries).T

class DataMatrixGroupBy(DataFrameGroupBy):
    _klass = DataMatrix


text:
import axios from 'axios';
import { setRelationships } from '../../relationships/relationships.reducer';

/* ------- ACTION TYPES/CONTSTANTS --------*/
const SET_ACTIVITIES = 'SET_ACTIVITIES';
const TOGGLE_ADD_ACTIVITY = 'TOGGLE_ADD_ACTIVITY';

/* ------- ACTION CREATORS --------*/
export const setActivities = (activities) => ({
  type: SET_ACTIVITIES,
  activities
});

export const toggleAddActivity = (bool) => ({
  type: TOGGLE_ADD_ACTIVITY,
  bool
});

/* ------- DISPATCHERS --------*/
export const postNewActivity = ({ type, date, relationshipId }) => (dispatch, getState) => {
  console.log(relationshipId);
  return axios.post(`/api/activity`, {
    date: date,
    relationshipId,
    type
  })
  .then(() => {
    let userId = getState().loggedInUser.id;
    return axios.get(`/api/relationship/user/${userId}`)
  })
  .then((relationships) => {
    dispatch(setRelationships(relationships.data));
  })
  .catch(err => console.error(err))
};

/* ------- INITIAL STATE --------*/
const initialState = {
  open: false
};

/* ------- REDUCER --------*/
const reducer = (state = initialState, action ) => {
  switch (action.type) {
    case TOGGLE_ADD_ACTIVITY:
      return Object.assign({}, state, { open: action.bool });
    default:
      return state;
  }
};

export default reducer;


text:
package org.killbill.billing.util.security;

import java.lang.annotation.Annotation;

import javax.inject.Inject;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler;

import org.killbill.billing.security.Permission;
import org.killbill.billing.security.RequiresPermissions;
import org.killbill.billing.security.SecurityApiException;
import org.killbill.billing.security.api.SecurityApi;
import org.killbill.billing.callcontext.DefaultTenantContext;
import org.killbill.billing.util.callcontext.TenantContext;

import com.google.common.collect.ImmutableList;

public class PermissionAnnotationHandler extends AuthorizingAnnotationHandler {

    private final TenantContext context = new DefaultTenantContext(null);

    @Inject
    SecurityApi securityApi;

    public PermissionAnnotationHandler() {
        super(RequiresPermissions.class);
    }

    public void assertAuthorized(final Annotation annotation) throws AuthorizationException {
        if (!(annotation instanceof RequiresPermissions)) {
            return;
        }

        final RequiresPermissions requiresPermissions = (RequiresPermissions) annotation;
        try {
            securityApi.checkCurrentUserPermissions(ImmutableList.<Permission>copyOf(requiresPermissions.value()), requiresPermissions.logical(), context);
        } catch (SecurityApiException e) {
            if (e.getCause() != null && e.getCause() instanceof AuthorizationException) {
                throw (AuthorizationException) e.getCause();
            } else if (e.getCause() != null) {
                throw new AuthorizationException(e.getCause());
            } else {
                throw new AuthorizationException(e);
            }
        }
    }
}


text:
Source code for https://www.nicolabs.net

## Setup

- Install jekyll
- [Install plantuml and a `plantuml` command in the PATH](https://github.com/yegor256/jekyll-plantuml#install-plantumljar) (requirement of *jekyll-plantuml*) (and probably *dot* : `apt install graphviz`)
- Run `bundle install`

## Assets/blog folder

The [assets/blog](assets/blog) folder gathers asset files used in articles.

It keeps the same layout as the previous wesite located from http://www.nicobo.net/sites/default/files in order to ease migration of URLs, but the `pictures` subfolder may not be used for new assets.

The new layout is :

    3rdparty/       # local copy of remote pictures, some modified (e.g. resized)
        \_ logos/   # icons & logos of third party products
        \_ images/  # photos & pictures taken from external sources
    screenshots/    # screen captures or alike used to illustrate some articles

## Previewing locally

Run `bundle exec jekyll serve --livereload -H '*' --drafts` to start a local server with automatic reload and drafts preview.

## Drafts

**Jekyll drafts** (articles in `_drafts/`) are *absolutely not ready* for publication. Some of them are *still* old documents I've never finished...
On the other hand, **articles tagged with _draft_** (in `_posts/`) are published with a special mention so that they hopefully can be useful to anybody : old drafts are slowly being published with this *draft* mention.
There are other mentions (*unpublished*, *draft*, *good*, *stable*, *deprecated*) to indicate articles' maturity.

See [Migrating from Drupal to Jekyll](_posts/Migrating-from-Drupal-to-Jekyll.md) for the explanation.
Most of the code lies in `_includes/maturity.html` and `_sass/nicolabs/*.scss` in order to :
- display the maturity label in each article's header
- advertise unstable articles in indexes (`index.html`, `tags.html`)
- remove drafts from the default feed

Drafts don't appear in the RSS feed, as this would trigger false updates until the article is ready for release (the publication date would change all the time).
The current workaround is to put those articles in a *preposts* collection until ready.

## Fullscreen pictures & PlantUML diagrams

I found it to be necessary to better display PlantUML diagrams.

This is implemented with :
- a [modified version](_plugins/jekyll-plantuml.rb) of [jekyll-plantuml](https://github.com/yegor256/jekyll-plantuml)
    - because it is the Jekyll integration advertized on plantuml.com
    - however it generates only `<svg>` inside `<object>`, which is not fullscreen-compatible OOTB => I replaced with `<img>` using the generated SVG as source
    - and it generated files in the root of the project
    - TODO anyway a replacement that uses Markdown standard ` ```plantuml` rather than Jekyll-specific `{% plantuml %}` syntax should be found
- assets/lib/[screenfull.js polyfill](https://github.com/sindresorhus/screenfull.js) (seen at *Modernizr*) and [a few lines of code](/_includes/head.html) to activate it
- [very few CSS](_sass/nicolabs/layout.css)

Based on :
- https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
- https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API/Guide
- https://caniuse.com/#feat=fullscreen
- https://developer.mozilla.org/fr/docs/Apprendre/HTML/Comment/Ajouter_des_images_vectorielles_%C3%A0_une_page_web

## Publishing

1. Update Ruby gems & build the final site without drafts :

    bundle update
    bundle exec jekyll build

2. Add, commit & push files [into the *master* git branch](https://help.github.com/en/github/working-with-github-pages/about-github-pages#publishing-sources-for-github-pages-sites), including the `docs` directory (same as Jekyll's `_site` directory, but renamed for github pages)

See [Bypassing GitHub's Jekyll limitations](_posts/2020-04-13-Bypassing-GitHub-Jekyll-limitations.md) for more informations.


text:
package horizon

import (
	"net/http"

	"github.com/stellar/go-horizon/actions"
	"github.com/zenazn/goji/web"
)

type Action struct {
	actions.Base
	App *App
}

func (action *Action) Prepare(c web.C, w http.ResponseWriter, r *http.Request) {
	base := &action.Base
	base.Prepare(c, w, r)
	action.App = action.GojiCtx.Env["app"].(*App)
}


text:
#include <aws/elasticbeanstalk/model/FailureType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace ElasticBeanstalk
  {
    namespace Model
    {
      namespace FailureTypeMapper
      {

        static const int UpdateCancelled_HASH = HashingUtils::HashString("UpdateCancelled");
        static const int CancellationFailed_HASH = HashingUtils::HashString("CancellationFailed");
        static const int RollbackFailed_HASH = HashingUtils::HashString("RollbackFailed");
        static const int RollbackSuccessful_HASH = HashingUtils::HashString("RollbackSuccessful");
        static const int InternalFailure_HASH = HashingUtils::HashString("InternalFailure");
        static const int InvalidEnvironmentState_HASH = HashingUtils::HashString("InvalidEnvironmentState");
        static const int PermissionsError_HASH = HashingUtils::HashString("PermissionsError");

        FailureType GetFailureTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == UpdateCancelled_HASH)
          {
            return FailureType::UpdateCancelled;
          }
          else if (hashCode == CancellationFailed_HASH)
          {
            return FailureType::CancellationFailed;
          }
          else if (hashCode == RollbackFailed_HASH)
          {
            return FailureType::RollbackFailed;
          }
          else if (hashCode == RollbackSuccessful_HASH)
          {
            return FailureType::RollbackSuccessful;
          }
          else if (hashCode == InternalFailure_HASH)
          {
            return FailureType::InternalFailure;
          }
          else if (hashCode == InvalidEnvironmentState_HASH)
          {
            return FailureType::InvalidEnvironmentState;
          }
          else if (hashCode == PermissionsError_HASH)
          {
            return FailureType::PermissionsError;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<FailureType>(hashCode);
          }

          return FailureType::NOT_SET;
        }

        Aws::String GetNameForFailureType(FailureType enumValue)
        {
          switch(enumValue)
          {
          case FailureType::UpdateCancelled:
            return "UpdateCancelled";
          case FailureType::CancellationFailed:
            return "CancellationFailed";
          case FailureType::RollbackFailed:
            return "RollbackFailed";
          case FailureType::RollbackSuccessful:
            return "RollbackSuccessful";
          case FailureType::InternalFailure:
            return "InternalFailure";
          case FailureType::InvalidEnvironmentState:
            return "InvalidEnvironmentState";
          case FailureType::PermissionsError:
            return "PermissionsError";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace FailureTypeMapper
    } // namespace Model
  } // namespace ElasticBeanstalk
} // namespace Aws


text:
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Theater.Interfaces.Presentation;
using MediaBrowser.Theater.Interfaces.ViewModels;
using System;
using System.Threading;
using System.Windows.Media.Imaging;

namespace MediaBrowser.Theater.Presentation.ViewModels
{
    public class ItemPersonViewModel : BaseViewModel, IDisposable
    {
        private readonly IApiClient _apiClient;
        private readonly IImageManager _imageManager;

        private BaseItemPerson _person;
        public BaseItemPerson Person
        {
            get { return _person; }

            set
            {
                var changed = _person != value;

                _person = value;

                if (changed)
                {
                    OnPropertyChanged("Person");
                    OnPropertyChanged("Name");
                    OnPropertyChanged("Id");
                    OnPropertyChanged("Role");
                    OnPropertyChanged("PersonType");
                }
            }
        }

        public string Role
        {
            get { return _person == null ? null : _person.Role; }
        }

        public string PersonType
        {
            get
            {
                if (_person == null)
                {
                    return null;
                }

                if (string.Equals(_person.Type, Model.Entities.PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
                {
                    return "Guest Star";
                }

                return _person.Type;
            }
        }

        public string Id
        {
            get { return _person == null ? null : _person.Id; }
        }
        public string Name
        {
            get { return _person == null ? null : _person.Name; }
        }

        private bool _hasImage;
        public bool HasImage
        {
            get { return _hasImage; }

            set
            {
                var changed = _hasImage != value;
                _hasImage = value;

                if (changed)
                {
                    OnPropertyChanged("HasImage");
                }
            }
        }

        private int? _imageWidth;
        public int? ImageWidth
        {
            get { return _imageWidth; }

            set
            {
                var changed = _imageWidth != value;
                _imageWidth = value;

                if (changed)
                {
                    OnPropertyChanged("ImageWidth");
                }
            }
        }

        private int? _imageHeight;
        public int? ImageHeight
        {
            get { return _imageHeight; }

            set
            {
                var changed = _imageHeight != value;
                _imageHeight = value;

                if (changed)
                {
                    OnPropertyChanged("ImageHeight");
                }
            }
        }

        private CancellationTokenSource _imageCancellationTokenSource;

        private BitmapImage _image;

        public ItemPersonViewModel(BaseItemPerson person, IApiClient apiClient, IImageManager imageManager)
        {
            _person = person;
            _apiClient = apiClient;
            _imageManager = imageManager;
        }

        public BitmapImage Image
        {
            get
            {
                var img = _image;

                var tokenSource = _imageCancellationTokenSource;

                if (img == null && (tokenSource == null || tokenSource.IsCancellationRequested))
                {
                    DownloadImage();
                }

                return _image;
            }

            private set
            {
                var changed = !Equals(_image, value);

                _image = value;

                if (value == null)
                {
                    var tokenSource = _imageCancellationTokenSource;

                    if (tokenSource != null)
                    {
                        tokenSource.Cancel();
                    }
                }

                if (changed)
                {
                    OnPropertyChanged("Image");
                }
            }
        }

        public async void DownloadImage()
        {
            _imageCancellationTokenSource = new CancellationTokenSource();

            if (Person.PrimaryImageTag != null)
            {
                try
                {
                    var options = new ImageOptions
                    {
                        Height = ImageHeight,
                        Width = ImageWidth,
                        ImageType = ImageType.Primary,
                        Tag = Person.PrimaryImageTag
                    };

                    Image = await _imageManager.GetRemoteBitmapAsync(_apiClient.GetPersonImageUrl(Person, options), _imageCancellationTokenSource.Token);

                    DisposeCancellationTokenSource();

                    HasImage = true;
                }
                catch
                {
                    // Logged at lower levels
                    HasImage = false;
                }
            }
            else
            {
                HasImage = false;
            }

        }

        public void Dispose()
        {
            DisposeCancellationTokenSource();
        }

        private void DisposeCancellationTokenSource()
        {
            if (_imageCancellationTokenSource != null)
            {
                _imageCancellationTokenSource.Cancel();
                _imageCancellationTokenSource.Dispose();
                _imageCancellationTokenSource = null;
            }
        }
    }
}


text:
var start = new Date(),
    prevDay,
    startHours = 9;

// // // 09:00
// start.setHours(9);
// start.setMinutes(0);

// $dp.datepicker().data('datepicker').update('minHours', startHours);

var $dp = $('.datepicker-here');

var dpOptns = {
  altField: $('.alt-datepicker'),
  altFieldDateFormat: 'dd.mm.yyyy',
  dateFormat: 'dd.mm.yyyy',
  // timepicker: true,
  // startDate: start,
  // minHours: startHours,
  // maxHours: 18,
  autoClose: true,
  // setDate: $(this).val(),
  // startDate: $(this).val(),
  // selectDate: $(this).el.value,
  onSelect: function(fd, d, picker) {
      // Ничего не делаем если выделение было снято
      if (!d) return;

      var day = d.getDay();

      // Обновляем состояние календаря только если была изменена дата
      if (prevDay != undefined && prevDay == day) return;
      prevDay = day;
  }
}

$dp.datepicker(dpOptns);

// console.log($dp.data('datepicker').el.value);
// // $('.datepicker-here').data('datepicker').selectDate();
// $dp.data('datepicker').selectDate(new Date(Date.parse($dp.data('datepicker').el.value)));


text:
<?php

namespace Drupal\ds\Form;

use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\ConfigFormBaseTrait;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Provides a form to delete a DS field.
 */
class FieldDeleteForm extends ConfirmFormBase implements ContainerInjectionInterface {

  use ConfigFormBaseTrait;

  /**
   * Holds the cache invalidator.
   *
   * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
   */
  protected $cacheInvalidator;

  /**
   * The field being deleted.
   *
   * @var array
   */
  protected $field;

  /**
   * Constructs a FieldDeleteForm object.
   *
   * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_invalidator
   *   The cache invalidator.
   */
  public function __construct(CacheTagsInvalidatorInterface $cache_invalidator) {
    $this->cacheInvalidator = $cache_invalidator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('cache_tags.invalidator'));
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->t('Are you sure you want to delete @field ?', array('@field' => $this->field['label']));
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('ds.fields_list');
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'field_delete_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL, $field_key = '') {
    $config = $this->config('ds.field.' . $field_key);
    $this->field = $config->get();

    if (empty($this->field)) {
      drupal_set_message(t('Field not found.'));
      return new RedirectResponse('/admin/structure/ds/fields');
    }

    return parent::buildForm($form, $form_state, $request);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $field = $this->field;

    // Remove field and clear caches.
    $this->config('ds.field.' . $field['id'])->delete();
    $this->cacheInvalidator->invalidateTags(array('ds_fields_info'));

    // Also clear the ds plugin cache.
    \Drupal::service('plugin.manager.ds')->clearCachedDefinitions();

    // Redirect.
    $url = new Url('ds.fields_list');
    $form_state->setRedirectUrl($url);
    drupal_set_message(t('The field @field has been deleted.', array('@field' => $field['label'])));
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return array(
      'ds.field.' . $this->field['id'],
    );
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.academy</groupId>
	<artifactId>quiz</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>quiz</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.1.8.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>junit</groupId>
					<artifactId>junit</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>6.8.8</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.google.code.findbugs</groupId>
			<artifactId>jsr305</artifactId>
			<version>3.0.0</version>
		</dependency>

		<dependency>
			<groupId>org.mariadb.jdbc</groupId>
			<artifactId>mariadb-java-client</artifactId>
			<version>1.1.7</version>
		</dependency>
	</dependencies>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<start-class>org.academy.quiz.Application</start-class>
		<java.version>1.8</java.version>
		<tomcat.version>8.0.14</tomcat.version>
		<spring.version>4.1.1.RELEASE</spring.version>
	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
require_relative "spec_helper"

RSpec.describe Uvm do
  context "#dispatch" do
    it "creates dispatch object" do
      expect(Uvm::CLIDispatch).to receive(:new).and_return(instance_double(Uvm::CLIDispatch, {dispatch: true}))
      described_class.dispatch({})
    end

    it "calls dispatch on new instance" do
      double = instance_double(Uvm::CLIDispatch, {dispatch: true})
      allow(Uvm::CLIDispatch).to receive(:new).and_return(double)
      expect(double).to receive(:dispatch)
      described_class.dispatch({})
    end
  end
end

RSpec.describe Uvm::CLIDispatch do

  let(:uvm) {double(Uvm::Uvm)}
  let(:options) {{}}
  let(:subject) {described_class.new uvm, options }

  it { is_expected.not_to be_nil }

  context "#dispatch" do
    context "when options are empty" do
      it "throws error" do
        expect { subject.dispatch }.to raise_exception(RuntimeError, "No options provided")
      end
    end

    context "when options are nil" do
      let(:options) {nil}
      it "throws error" do
        expect { subject.dispatch }.to raise_exception(RuntimeError, "No options provided")
      end
    end

    context "with valid options" do
      context "and multiple commands in options" do
        let(:options) {
          {
            "clear" => true,
            "use" => true,
            "<version>" => "some version"
          }
        }

        it "breaks after first dispatch" do
          expect(uvm).to receive(:current)
          expect(uvm).to receive(:clear)
          expect(uvm).not_to receive(:use)

          subject.dispatch
        end
      end

      context "and unknown command in options" do

        let(:options) {
          {
            "disrupt" => true,
            "<version>" => "some version"
          }
        }

        it "throws error" do
          expect { subject.dispatch }.to raise_exception(RuntimeError, "Unknown command")
        end
      end
    end
  end

  RSpec.shared_context "install/uninstall" do
    let(:options) {{"<version>" => "1.2.3f1", delegate_method.to_s => true}}

    it "calls uvm install/uninstall with version" do
      expect(uvm).to receive(delegate_method).with(version: "1.2.3f1")
      subject.dispatch
    end

    [:ios, :android, :webgl, :linux, :windows].each do |i|
      context "with option --#{i}" do
        it "calls uvm install/uninstall  with version and platform support option #{i}" do
          options = {
            "<version>" => "1.2.3f1",
            "--#{i}" => true,
            delegate_method.to_s => true
          }

          subject = described_class.new uvm, options
          expect(uvm).to receive(delegate_method).with(version: "1.2.3f1", i => true)
          subject.dispatch
        end
      end
    end

    {
      "--mobile" => {ios: true, android: true, webgl: true},
      "--desktop" => {linux: true, windows:true},
      "--all" => {ios: true, android: true, webgl: true, linux: true, windows:true}
    }.each_pair do |option, expected_options|

      context "with meta option #{option}" do
        it "calls uvm install/uninstall  with version and platform support option #{expected_options.keys}" do
          options = {
            "<version>" => "1.2.3f1",
            option => true,
            delegate_method.to_s => true
          }

          subject = described_class.new uvm, options
          expect(uvm).to receive(delegate_method).with(version: "1.2.3f1", **expected_options)
          subject.dispatch
        end
      end
    end
  end

  describe "#dispatch_install" do
    let(:dispatch_method_name) {"dispatch_install"}
    let(:delegate_method) {:install}
    include_context "install/uninstall"
  end

  describe "#dispatch_uninstall" do
    let(:dispatch_method_name) {"dispatch_uninstall"}
    let(:delegate_method) {:uninstall}
    include_context "install/uninstall"
  end

  describe "#dispatch_use" do
    include_context "mock stderr stdout"
    let(:options) {{"use" => true, "<version>" => "1.2.3f1"}}

    it "calls uvm use and prints output message" do
      allow(uvm).to receive(:use).and_return("new_path")
      expect(stdout_double).to receive(:puts).with(/Using 1.2.3f1.*new_path/)
      subject.dispatch
    end

    context "when use throws error" do
      before(:each) {
        allow(uvm).to receive(:use).and_raise("random error")
        allow(uvm).to receive(:list).and_return(["1.3.2f1"])
      }

      it "prints help message" do
        expect(stderr_double).to receive(:puts).with(/Version .* isn't available/)
        expect(stderr_double).to receive(:puts).with(duck_type(:each))
        expect { subject.dispatch }.to raise_error(SystemExit)
      end

      it "aborts" do
        expect { subject.dispatch }.to raise_error(SystemExit)
      end
    end

    context "when use throws ArgumentError" do
      before(:each) {
        allow(uvm).to receive(:use).and_raise(ArgumentError)
      }

      it "aborts" do
        expect { subject.dispatch }.to raise_error(SystemExit)
      end
    end
  end

  describe "#dispatch_clear" do
    include_context "mock stderr stdout"
    let(:options) {{"clear" => true}}

    it "calls uvm clear" do
      allow(uvm).to receive(:current).and_return("1.2.3f1")
      expect(uvm).to receive(:clear)
      subject.dispatch
    end

    it "prints message" do
      allow(uvm).to receive(:current).and_return("1.2.3f1")
      allow(uvm).to receive(:clear)
      expect(stdout_double).to receive(:puts).with(/Clear active Unity version old:/)
      subject.dispatch
    end

    context "when clear throws Error" do
      before(:each) {
        allow(uvm).to receive(:current).and_return("1.2.3f1")
        allow(uvm).to receive(:clear).and_raise(ArgumentError)
      }

      it "aborts" do
        expect { subject.dispatch }.to raise_error(SystemExit)
      end
    end
  end

  describe "#dispatch_detect" do
    include_context "mock stderr stdout"
    let(:options) {{"detect" => true}}

    it "calls uvm detect" do
      expect(uvm).to receive(:detect)
      subject.dispatch
    end

    it "prints message" do
      allow(uvm).to receive(:detect).and_return("1.2.3f1")
      expect(stdout_double).to receive(:puts).with("1.2.3f1")
      subject.dispatch
    end

    context "when detect throws Error" do
      before(:each) {
        allow(uvm).to receive(:detect).and_raise(ArgumentError)
      }

      it "aborts" do
        expect { subject.dispatch }.to raise_error(SystemExit)
      end
    end
  end

  describe "#dispatch_launch" do
    include_context "mock stderr stdout"
    let(:options) {{"launch" => true}}

    ["project-path", "platform"].each do |i|
      context "with option <#{i}>" do
        it "calls uvm launch with #{i.sub("-","_")}" do
          options = {
            "launch" => true,
            "<#{i}>" => "value"
          }

          subject = described_class.new uvm, options
          expect(uvm).to receive(:launch).with(i.sub("-","_").to_sym => "value")
          subject.dispatch
        end
      end
    end
  end

  describe "#dispatch_list" do
    include_context "mock stderr stdout"
    let(:options) {{"list" => true}}

    let(:local_versions) {
      [
        "1.2.3f1",
        "1.3.0f1",
        "1.3.1f1",
      ]
    }

    before(:each) {
      allow(uvm).to receive(:list).and_return(local_versions)
    }

    it "prints header" do
      expect(stderr_double).to receive(:puts).with("Installed Unity versions:")
      subject.dispatch
    end

    it "prints list of versions" do
      expect(stdout_double).to receive(:puts).with(local_versions)
      subject.dispatch
    end

    context "when versions are empty" do
      let(:local_versions) {[]}

      it "prints special message" do
        expect(stderr_double).to receive(:puts).with("None")
        subject.dispatch
      end
    end
  end

  describe "#dispatch_versions" do
    include_context "mock stderr stdout"
    let(:options) {{"versions" => true}}

    let(:remote_versions) {
      [
        "1.2.3f1",
        "1.3.0f1",
        "1.3.1f1",
      ]
    }

    let(:local_versions) {[]}

    before(:each) {
      allow(uvm).to receive(:versions).and_return(remote_versions)
      allow(uvm).to receive(:list).and_return(local_versions)
    }

    it "prints header" do
      expect(stderr_double).to receive(:puts).with("Available Unity versions:")
      subject.dispatch
    end

    it "prints list of versions" do
      expect(stdout_double).to receive(:puts).with(remote_versions)
      subject.dispatch
    end

    context "when versions are installed" do
      let(:local_versions) {
        [
          "1.3.0f1"
        ]
      }

      it "removes local versions from remote versions" do
        expect(stdout_double).to receive(:puts).with(remote_versions - local_versions)
        subject.dispatch
      end
    end

    context "when versions are empty" do
      let(:local_versions) { remote_versions }

      it "prints special message" do
        expect(stderr_double).to receive(:puts).with("None")
        subject.dispatch
      end
    end
  end

  describe "#dispatch_current" do
    include_context "mock stderr stdout"

    let(:options) {{"current" => true}}

    it "calls uvm current" do
      expect(uvm).to receive(:current)
      subject.dispatch
    end

    it "prints result" do
      expect(uvm).to receive(:current).and_return("1.2.3f1")
      expect(stdout_double).to receive(:puts).with("1.2.3f1")
      subject.dispatch
    end

    context "when current throws error" do
      it "aborts" do
        allow(uvm).to receive(:current).and_throw
        expect { subject.dispatch }.to raise_error(SystemExit)
      end
    end
  end
end


text:
//
//  Created by XueYulun on 15/8/10.
//  Copyright © 2015年 __Dylan. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

typedef NS_ENUM(NSUInteger, WAxis)
{
    WAxisX = 0,
    WAxisY,
    WAxisZ
};

// Degrees to radians
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))

@interface CAAnimation (DLAnimation)

/**
 *  breathing forever
 *
 *  @param time duritaion, from clear to fully seen
 *
 *  @return animation obj
 */
+(CABasicAnimation *)opacityForever_Animation:(float)time;

/**
 *  breathing with fixed repeated times
 *
 *  @param repeatTimes times
 *  @param time        duritaion, from clear to fully seen
 *
 *  @return animation obj
 */
+(CABasicAnimation *)opacityTimes_Animation:(float)repeatTimes durTimes:(float)time;

/**
 *  //rotate
 *
 *  @param dur         duration
 *  @param degree      rotate degree in radian(弧度)
 *  @param axis        axis
 *  @param repeatCount repeat count
 *
 *  @return animation obj
 */
+(CABasicAnimation *)rotation:(float)dur degree:(float)degree direction:(WAxis)axis repeatCount:(int)repeatCount;

/**
 *  scale animation
 *
 *  @param fromScale   the original scale value, 1.0 by default
 *  @param toScale     target scale
 *  @param time        duration
 *  @param repeatTimes repeat counts
 *
 *  @return animaiton obj
 */
+(CABasicAnimation *)scaleFrom:(CGFloat)fromScale toScale:(CGFloat)toScale durTimes:(float)time rep:(float)repeatTimes;
/**
 *  shake
 *
 *  @param repeatTimes time
 *  @param time        duration
 *  @param obj         always be CALayer at present
 *  @return aniamtion obj
 */
+(CAKeyframeAnimation *)shake_AnimationRepeatTimes:(float)repeatTimes durTimes:(float)time forObj:(id)obj;

@end