text:
Z EDSL mamy do czynienia wtedy, kiedy wykorzystując elementy języka tworzymy w nim zestaw narzędzi, którymi łatwiej jest operować w danej dziedzinie wiedzy. Idea jest taka, żeby analityk biznesowy mógł razem z programistą stworzyć wspólny język, który będzie zrozumiały dla obu stron. Kompilowane zasady biznesowe.

Jednym podejściem jest stworzenie lub dołączenie zewnętrznego języka skryptowego.

Przykładem zewnętrznego języka domenowego, o którym prawdopodobnie wszyscy słyszeliście, jest **SQL**. Jest to język domenowy do manipulacji obszernymi zbiorami danych z bazie relacynej.

Można tez pod tę definicję podciągnąć języki skryptowe używane w grach do programowania zachowań przeciwników (np. wybór najlepszej ścieżki; sam algorytm jej wyznaczania będzie zaimplementowany w głównym języku) lub modelowania zachowań środowiska (np. kiedy ma zacząć padać deszcz). **Lua** jest przykładem języka, który został zastosowany w wielu grach własnie do tego celu (Wikipedia wymienia 151 gier, które go wykorzystują, m. in.: Angry Birds, Baldur's Gate, Freeciv, Saints Row 2/3/4, Warhammer 40k: Dawn of War 1/2).

Jeśli język oferuje wystarczającą ekspresywność, można ominąć wprowadzenie zwenętrznego języka (i pisanie parsera albo wciąganie frameworku, jak [xText](https://eclipse.org/Xtext/) dla Javy).

## Przykład EDSL dla jednostek
Przykład poniżej zapożyczyłem z książki [Real World Haskell](http://book.realworldhaskell.org/read/), a reprezentuje on EDSL wspomagający obliczenia za pomocą implementacji matematyki jednostek

Przykład w działaniu:
```haskell
ghci> ((units 50 "m") * sin (units 90 "deg")) :: Units (SymbolicManip Double)
50.0*sin(((2.0*pi)*90.0)/360.0)_m
ghci> prettyShow $ dropUnits $ (units 50 "m") * sin (units 90 "deg")
"50.0*sin(((2.0*pi)*90.0)/360.0)"
ghci> rpnShow $ dropUnits $ (units 50 "m") * sin (units 90 "deg")
"50.0 2.0 pi * 90.0 * 360.0 / sin *"
ghci> (units (Symbol "x") "m") * sin (units 90 "deg")
x*sin(((2.0*pi)*90.0)/360.0)_m
```

Kod implementujący obliczenia (uwaga, bogaty przykład; ch13/num.hs)
```haskell
import Data.List

--------------------------------------------------
-- Symbolic/units manipulation
--------------------------------------------------

-- The "operators" that we're going to support
data Op = Plus | Minus | Mul | Div | Pow
        deriving (Eq, Show)

{- The core symbolic manipulation type.  It can be a simple number,
a symbol, a binary arithmetic operation (such as +), or a unary
arithmetic operation (such as cos)

Notice the types of BinaryArith and UnaryArith: it's a recursive
type.  So, we could represent a (+) over two SymbolicManips. -}
data SymbolicManip a =
          Number a           -- Simple number, such as 5
        | Symbol String      -- A symbol, such as x
        | BinaryArith Op (SymbolicManip a) (SymbolicManip a)
        | UnaryArith String (SymbolicManip a)
          deriving (Eq)

{- SymbolicManip will be an instance of Num.  Define how the Num
operations are handled over a SymbolicManip.  This will implement things
like (+) for SymbolicManip. -}
instance Num a => Num (SymbolicManip a) where
    a + b = BinaryArith Plus a b
    a - b = BinaryArith Minus a b
    a * b = BinaryArith Mul a b
    negate a = BinaryArith Mul (Number (-1)) a
    abs a = UnaryArith "abs" a
    signum _ = error "signum is unimplemented"
    fromInteger i = Number (fromInteger i)

{- Make SymbolicManip an instance of Fractional -}
instance (Fractional a) => Fractional (SymbolicManip a) where
    a / b = BinaryArith Div a b
    recip a = BinaryArith Div (Number 1) a
    fromRational r = Number (fromRational r)

{- Make SymbolicManip an instance of Floating -}
instance (Floating a) => Floating (SymbolicManip a) where
    pi = Symbol "pi"
    exp a = UnaryArith "exp" a
    log a = UnaryArith "log" a
    sqrt a = UnaryArith "sqrt" a
    a ** b = BinaryArith Pow a b
    sin a = UnaryArith "sin" a
    cos a = UnaryArith "cos" a
    tan a = UnaryArith "tan" a
    asin a = UnaryArith "asin" a
    acos a = UnaryArith "acos" a
    atan a = UnaryArith "atan" a
    sinh a = UnaryArith "sinh" a
    cosh a = UnaryArith "cosh" a
    tanh a = UnaryArith "tanh" a
    asinh a = UnaryArith "asinh" a
    acosh a = UnaryArith "acosh" a
    atanh a = UnaryArith "atanh" a

{- Show a SymbolicManip as a String, using conventional
algebraic notation -}
prettyShow :: (Show a, Num a) => SymbolicManip a -> String

-- Show a number or symbol as a bare number or serial
prettyShow (Number x) = show x
prettyShow (Symbol x) = x

prettyShow (BinaryArith op a b) =
    let pa = simpleParen a
        pb = simpleParen b
        pop = op2str op
        in pa ++ pop ++ pb
prettyShow (UnaryArith opstr a) =
    opstr ++ "(" ++ show a ++ ")"

op2str :: Op -> String
op2str Plus = "+"
op2str Minus = "-"
op2str Mul = "*"
op2str Div = "/"
op2str Pow = "**"

{- Add parenthesis where needed.  This function is fairly conservative
and will add parenthesis when not needed in some cases.

Haskell will have already figured out precedence for us while building
up the SymbolicManip. -}
simpleParen :: (Show a, Num a) => SymbolicManip a -> String
simpleParen (Number x) = prettyShow (Number x)
simpleParen (Symbol x) = prettyShow (Symbol x)
simpleParen x@(BinaryArith _ _ _) = "(" ++ prettyShow x ++ ")"
simpleParen x@(UnaryArith _ _) = prettyShow x

{- Showing a SymbolicManip calls the prettyShow function on it -}
instance (Show a, Num a) => Show (SymbolicManip a) where
    show a = prettyShow a

{- Show a SymbolicManip using RPN.  HP calculator users may
find this familiar. -}
rpnShow :: (Show a, Num a) => SymbolicManip a -> String
rpnShow i =
    let toList (Number x) = [show x]
        toList (Symbol x) = [x]
        toList (BinaryArith op a b) = toList a ++ toList b ++
           [op2str op]
        toList (UnaryArith op a) = toList a ++ [op]
        join :: [a] -> [[a]] -> [a]
        join delim l = concat (intersperse delim l)
    in join " " (toList i)

{- Perform some basic algebraic simplifications on a SymbolicManip. -}
simplify :: (Num a) => SymbolicManip a -> SymbolicManip a
simplify (BinaryArith op ia ib) =
    let sa = simplify ia
        sb = simplify ib
        in
        case (op, sa, sb) of
                (Mul, Number 1, b) -> b
                (Mul, a, Number 1) -> a
                (Mul, Number 0, b) -> Number 0
                (Mul, a, Number 0) -> Number 0
                (Div, a, Number 1) -> a
                (Plus, a, Number 0) -> a
                (Plus, Number 0, b) -> b
                (Minus, a, Number 0) -> a
                _ -> BinaryArith op sa sb
simplify (UnaryArith op a) = UnaryArith op (simplify a)
simplify x = x

--------------------------------------------------
-- Units of measure support
--------------------------------------------------
{- New data type: Units.  A Units type contains a number
and a SymbolicManip, which represents the units of measure.
A simple label would be something like (Symbol "m") -}
data Num a => Units a = Units a (SymbolicManip a)
           deriving (Eq)

{- Implement Units for Num.  We don't know how to convert between
arbitrary units, so we generate an error if we try to add numbers with
different units.  For multiplication, generate the appropriate
new units. -}
instance (Num a) => Num (Units a) where
    (Units xa ua) + (Units xb ub)
        | ua == ub = Units (xa + xb) ua
        | otherwise = error "Mis-matched units in add or subtract"
    (Units xa ua) - (Units xb ub) = (Units xa ua) + (Units (xb * (-1)) ub)
    (Units xa ua) * (Units xb ub) = Units (xa * xb) (ua * ub)
    negate (Units xa ua) = Units (negate xa) ua
    abs (Units xa ua) = Units (abs xa) ua
    signum (Units xa _) = Units (signum xa) (Number 1)
    fromInteger i = Units (fromInteger i) (Number 1)

{- Make Units an instance of Fractional -}
instance (Fractional a) => Fractional (Units a) where
    (Units xa ua) / (Units xb ub) = Units (xa / xb) (ua / ub)
    recip a = 1 / a
    fromRational r = Units (fromRational r) (Number 1)

{- Floating implementation for Units.

Use some intelligence for angle calculations: support deg and rad
-}
instance (Floating a) => Floating (Units a) where
    pi = (Units pi (Number 1))
    exp _ = error "exp not yet implemented in Units"
    log _ = error "log not yet implemented in Units"
    (Units xa ua) ** (Units xb ub)
        | ub == Number 1 = Units (xa ** xb) (ua ** Number xb)
        | otherwise = error "units for RHS of ** not supported"
    sqrt (Units xa ua) = Units (sqrt xa) (sqrt ua)
    sin (Units xa ua)
        | ua == Symbol "rad" = Units (sin xa) (Number 1)
        | ua == Symbol "deg" = Units (sin (deg2rad xa)) (Number 1)
        | otherwise = error "Units for sin must be deg or rad"
    cos (Units xa ua)
        | ua == Symbol "rad" = Units (cos xa) (Number 1)
        | ua == Symbol "deg" = Units (cos (deg2rad xa)) (Number 1)
        | otherwise = error "Units for cos must be deg or rad"
    tan (Units xa ua)
        | ua == Symbol "rad" = Units (tan xa) (Number 1)
        | ua == Symbol "deg" = Units (tan (deg2rad xa)) (Number 1)
        | otherwise = error "Units for tan must be deg or rad"
    asin (Units xa ua)
        | ua == Number 1 = Units (rad2deg $ asin xa) (Symbol "deg")
        | otherwise = error "Units for asin must be empty"
    acos (Units xa ua)
        | ua == Number 1 = Units (rad2deg $ acos xa) (Symbol "deg")
        | otherwise = error "Units for acos must be empty"
    atan (Units xa ua)
        | ua == Number 1 = Units (rad2deg $ atan xa) (Symbol "deg")
        | otherwise = error "Units for atan must be empty"
    sinh = error "sinh not yet implemented in Units"
    cosh = error "cosh not yet implemented in Units"
    tanh = error "tanh not yet implemented in Units"
    asinh = error "asinh not yet implemented in Units"
    acosh = error "acosh not yet implemented in Units"
    atanh = error "atanh not yet implemented in Units"

{- A simple function that takes a number and a String and returns an
appropriate Units type to represent the number and its unit of measure -}
units :: (Num z) => z -> String -> Units z
units a b = Units a (Symbol b)

{- Extract the number only out of a Units type -}
dropUnits :: (Num z) => Units z -> z
dropUnits (Units x _) = x

{- Utilities for the Unit implementation -}
deg2rad x = 2 * pi * x / 360
rad2deg x = 360 * x / (2 * pi)

{- Showing units: we show the numeric component, an underscore,
then the prettyShow version of the simplified units -}
instance (Show a, Num a) => Show (Units a) where
    show (Units xa ua) = show xa ++ "_" ++ prettyShow (simplify ua)
```

---
## Przykład EDSL dla giełdy
Znalazłem bardzo ładny choć ograniczony przykład EDSL w Scali, który przetłumaczyłem do Haskella. Sam nie jestem ekspertem od rynków, więc wszelkie niedopowiedzenia i niedosokonałości musicie mi wybaczyć.

Źródło: [DSL for the Uninitiated](http://cacm.acm.org/magazines/2011/7/109910-dsl-for-the-uninitiated/fulltext)

```haskell
{-# LANGUAGE ViewPatterns #-}

type Account = String
type Instrument = String
type Money = Integer
type DateTime = (String, String)
type TaxId = Int

newtype Tax = Tax (TaxId, Rational)

data Trade = Trade {
    getAccount    :: Account,
    getInstrument :: Instrument,
    getRefNo      :: String,
    getMarket     :: Market,
    getUnitPrice  :: Money,
    getQuantity   :: Int,
    getTradeDate  :: DateTime,
    getValueDate  :: Maybe DateTime,
    getTaxFees    :: [Tax],
    getNetAmount  :: Maybe Money
}

data Market = HongKong | Singapore | NewYork | Tokyo

class RealTrade a where
    market :: a -> Market

class StockMarket a where
    cashValue :: RealTrade a => a -> Money

instance RealTrade Trade where
    market = getMarket

instance StockMarket Trade where
    cashValue trade@(market -> HongKong) =
        let qty   = fromIntegral $ getQuantity trade
            price = getUnitPrice trade
        in qty * price

    cashValue trade@(market -> Singapore) =
        undefined

    cashValue trade =
        undefined

main :: IO ()
main = print $ cashValue
    (Trade "123" "A" "AV2/3" HongKong 10 2 ("2015-08-19","10:03:44") Nothing [] Nothing)
```


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <link rel="stylesheet" href="../dist/sequence-diagram-min.css">

<textarea class="language" rows="10" cols="35">
Title: Here is a title
A->B:
B->C:
C->C:
A->B: Normal line
B-->C: Dashed line
C->>D: Open arrow
D-->>A: Dashed open arrow
D->D: Self
D->D: Many\nLines
</textarea>
<textarea class="language" rows="10" cols="35">
# Example of a comment.
Note left of A: Note to the\n left of A
Note right of A: Note to the\n right of A
Note over A: Note over A
Note over A,B: Note over both A and B
</textarea>
<textarea class="language" rows="10" cols="35">
participant long name\nC as C
participant B
participant A
Note right of A: By listing the participants\n you can change their order
</textarea>

redpajama_set_name: RedPajamaGithub


text:
"""Wrapper for sigprocmask(2) operations."""

import logging
import os

import ctypes
from ctypes import (
    c_int,
    c_void_p,
)

from ctypes.util import find_library

import enum

from ._sigsetops import (
    SigSet,
    sigaddset,
    sigfillset,
)

_LOGGER = logging.getLogger(__name__)

###############################################################################
# Map the C interface

_LIBC_PATH = find_library('c')
_LIBC = ctypes.CDLL(_LIBC_PATH, use_errno=True)

if getattr(_LIBC, 'sigprocmask', None) is None:
    raise ImportError('Unsupported libc version found: %s' % _LIBC_PATH)

# int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);
_SIGPROCMASK_DECL = ctypes.CFUNCTYPE(c_int, c_int, c_void_p, c_void_p,
                                     use_errno=True)
_SIGPROCMASK = _SIGPROCMASK_DECL(('sigprocmask', _LIBC))

def sigprocmask(how, sigset, save_mask=True):
    """Examine and change blocked signals.
    """
    how = SigProcMaskHow(how)

    if isinstance(sigset, SigSet):
        new_set = sigset

    elif sigset == 'all':
        new_set = SigSet()
        sigfillset(new_set)

    else:
        new_set = SigSet()
        for signum in sigset:
            sigaddset(new_set, signum)

    if save_mask:
        old_set = SigSet()
    else:
        # pylint - Redefinition of old_set type from
        #          treadmill.syscall._sigsetops.SigSet to int
        old_set = 0  # pylint: disable=R0204

    new_set_p = ctypes.pointer(new_set)
    old_set_p = ctypes.pointer(old_set)
    res = _SIGPROCMASK(how, new_set_p, old_set_p)
    if res < 0:
        err = ctypes.get_errno()
        raise OSError(
            err, os.strerror(err),
            'sigprocmask(%r, %r, %r)' % (how, new_set, old_set)
        )

    return old_set

###############################################################################
# Constants copied from bits/sigaction.h
#
# See man sigprocmask(2) for more details.
#
# /* Values for the HOW argument to `sigprocmask'.  */
# #define SIG_BLOCK     0   /* Block signals.  */
# #define SIG_UNBLOCK   1   /* Unblock signals.  */
# #define SIG_SETMASK   2   /* Set the set of blocked signals.  */
#
class SigProcMaskHow(enum.IntEnum):
    """How option supported by sigprocmask."""

    #: Block signals.
    SIG_BLOCK = 0

    #: Unblock signals.
    SIG_UNBLOCK = 1

    #: Set the set of blocked signals.
    #: Set the O_NONBLOCK file status flag on the new open file description.
    SIG_SETMASK = 2

SIG_BLOCK = SigProcMaskHow.SIG_BLOCK
SIG_UNBLOCK = SigProcMaskHow.SIG_UNBLOCK
SIG_SETMASK = SigProcMaskHow.SIG_SETMASK

###############################################################################
__all__ = [
    'sigprocmask',
    'SIG_BLOCK',
    'SIG_UNBLOCK',
    'SIG_SETMASK',
]


text:
package com.wso2telco.workflow.utils;

public class Constants {

	public static final String CLAIM_EMAIL = "email";

	// Email subjects.
	public static final String SUBJECT_HUB_ADMIN_APP_APPROVAL_NOTIFICATION = "HUB Level Application Approval Request";
	public static final String SUBJECT_HUB_ADMIN_SUB_APPROVAL_NOTIFICATION = "HUB Level Subscription Approval Request";
	public static final String SUBJECT_PLUGIN_ADMIN_APP_APPROVAL_NOTIFICATION = "PLUGIN Level Application Approval Request";
	public static final String SUBJECT_PLUGIN_ADMIN_SUB_APPROVAL_NOTIFICATION = "PLUGIN Level Subscription Approval Request";
	public static final String SUBJECT_APP_APPROVAL_STATUS_SP_NOTIFICATION = "Application Approval Status Notification";
	public static final String SUBJECT_SUB_APPROVAL_STATUS_SP_NOTIFICATION = "Subscription Approval Status Notification";
    public static final String SUBJECT_PUBLISHER_SUB_APPROVAL_NOTIFICATION= "Publisher Subscription Approval Request";
    public static final String SUBJECT_OPE_ADMIN_SUB_APPROVAL_NOTIFICATION = "Subscription Approval Request";

	// workflow.properties file entries: Email sending configs.
	public static final String WORKFLOW_PROPERTIES_FILE = "workflow.properties";
	public static final String KEY_WORKFLOW_EMAIL_NOTIFICATION_HOST = "workflow.email.notification.host";
	public static final String KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_ADDRESS = "workflow.email.notification.from.address";
	public static final String KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_PASSWORD = "workflow.email.notification.from.password";

	// workflow.properties file entries: Remote userstore manager service configs.
	public static final String REMOTE_USERSTORE_MANAGER_HOST = "userstoremanager.service.host";
	public static final String REMOTE_USERSTORE_MANAGER_USERNAME = "userstoremanager.service.username";

}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace TechEd.Services
{
    public interface ISearchService
    {
        Task<IList<SearchResult>> SearchAsync(string term);

        SearchResult GetResult(string itemLink);
    }
}


text:
#include <aws/ssm/model/MaintenanceWindowLambdaParameters.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/HashingUtils.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SSM
{
namespace Model
{

MaintenanceWindowLambdaParameters::MaintenanceWindowLambdaParameters() :
    m_clientContextHasBeenSet(false),
    m_qualifierHasBeenSet(false),
    m_payloadHasBeenSet(false)
{
}

MaintenanceWindowLambdaParameters::MaintenanceWindowLambdaParameters(JsonView jsonValue) :
    m_clientContextHasBeenSet(false),
    m_qualifierHasBeenSet(false),
    m_payloadHasBeenSet(false)
{
  *this = jsonValue;
}

MaintenanceWindowLambdaParameters& MaintenanceWindowLambdaParameters::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ClientContext"))
  {
    m_clientContext = jsonValue.GetString("ClientContext");

    m_clientContextHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Qualifier"))
  {
    m_qualifier = jsonValue.GetString("Qualifier");

    m_qualifierHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Payload"))
  {
    m_payload = HashingUtils::Base64Decode(jsonValue.GetString("Payload"));
    m_payloadHasBeenSet = true;
  }

  return *this;
}

JsonValue MaintenanceWindowLambdaParameters::Jsonize() const
{
  JsonValue payload;

  if(m_clientContextHasBeenSet)
  {
   payload.WithString("ClientContext", m_clientContext);

  }

  if(m_qualifierHasBeenSet)
  {
   payload.WithString("Qualifier", m_qualifier);

  }

  if(m_payloadHasBeenSet)
  {
   payload.WithString("Payload", HashingUtils::Base64Encode(m_payload));
  }

  return payload;
}

} // namespace Model
} // namespace SSM
} // namespace Aws


text:
using System;
using System.Collections.Generic;
using Entitas;
using UnityEngine;

public class AddGameObjectSystem : IReactiveSystem, ISetPool {
    public TriggerOnEvent trigger { get { return Matcher.Resource.OnEntityAdded(); } }

    readonly Transform container = new GameObject("Views").transform;

	Group _poolGroup;

	public void SetPool(Pool pool) {
		_poolGroup = pool.GetGroup(Matcher.PoolableGO);
	}

    public void Execute(List<Entity> entities) {
        for (int i = 0; i < entities.Count; i++) {
			Entity e = entities[i];
			string resourceName = e.resource.name;
            GameObject gameObject = getFromPool(resourceName);
			if (gameObject == null) {
				GameObject res = Resources.Load<GameObject>("Prefab/" + resourceName);
				try {
					gameObject = UnityEngine.Object.Instantiate(res);
				}
				catch (Exception) {
					Debug.Log("Cannot instantiate " + resourceName);
				}
			}

            gameObject.transform.SetParent(container, false);
			e.AddGameObject(gameObject, resourceName, true);
		}
    }

    GameObject getFromPool(string name) {
		foreach (Entity e in _poolGroup.GetEntities()) {
			PoolableGOComponent poolGo = e.poolableGO;
			if (poolGo.name.Equals(name) && poolGo.queue.Count > 0) {
				GameObject gameObject = poolGo.queue.Dequeue();
				gameObject.SetActive(true);
				return gameObject;
			}
		}
		return null;
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.togglz.servlet.util (Togglz 2.0.1.Final API)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.togglz.servlet.util

Classes

HttpServletRequestHolder

HttpServletRequestHolderListener


text:
- Add tests to check if publications are created
- Do not allow subscription to any feed_id (somehow let the user define how to restrict access)


text:
package javax.ws.rs.ext;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

public interface ParamConverterProvider {

    public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation annotations[]);
}


text:
var mboxCopyright = "Copyright 1996-2014. Adobe Systems Incorporated. All rights reserved.";
var TNT = TNT || {};
TNT.a = TNT.a || {};
TNT.a.nestedMboxes = [];

TNT.a.b = {
 "companyName": "Test&Target",
 "isProduction": true,
 "adminUrl": "//admin5.testandtarget.omniture.com/admin",
 "clientCode": "omniture",
 "serverHost": "omniture.tt.omtrdc.net",
 "mboxTimeout": 15000,
 "mboxLoadedTimeout": 16,
 "mboxFactoryDisabledTimeout": 60 * 60,
 "bodyPollingTimeout": 16,
 "sessionExpirationTimeout": 31 * 60,
 "experienceManagerDisabledTimeout": 30 * 60,
 "experienceManagerTimeout": 5000,
 "tntIdLifetime": 1209600,
 "crossDomain": "disabled",
 "trafficDuration": 10368000,
 "trafficLevelPercentage": 100,
 "clientSessionIdSupport": false,
 "clientTntIdSupport": false,
 "passPageParameters": true,
 "usePersistentCookies": true,
 "crossDomainEnabled": false,
 "crossDomainXOnly": false,
 "imsOrgId": "2A5D3BC75244638C0A490D4D@AdobeOrg",
 "includeExperienceManagerPlugin": true,
 "globalMboxName": "target-global-mbox",
 "globalMboxLocationDomId": "",
 "globalMboxAutoCreate": true,
 "experienceManagerPluginUrl": "//cdn.tt.omtrdc.net/cdn/target.js",
 "siteCatalystPluginName": "tt",
 "includeSiteCatalystPlugin": false,
 "mboxVersion": 56,
 "mboxIsSupportedFunction": function() {
  return true;
 },
 "clientJavascriptFunction": function() {
  var mboxFactoryAdmin = new mboxFactory("mbox5.tt.omtrdc.net","omniture","admin"); mboxCreateAdmin = function(c ) { var d = mboxFactoryAdmin.create(c, mboxShiftArray(arguments)); if (d) { d.load(); } return d; };
 },
 "parametersFunction": function() {
  return "";
 },
 "cookieDomainFunction": function() {
  return mboxCookiePageDomain();
 }
};

TNT.a.e = {};
TNT.a.e.f = "mboxPage";
TNT.a.e.g = "mboxMCGVID";
TNT.a.e.h = "mboxMCGLH";
TNT.a.e.i = "mboxAAMB";
TNT.a.e.j = "mboxMCAVID";
TNT.a.e.k = "mboxMCSDID";
TNT.a.e.l = "mboxCount";
TNT.a.e.m = "mboxHost";
TNT.a.e.n = "mboxFactoryId";
TNT.a.e.o = "mboxPC";
TNT.a.e.p = "screenHeight";
TNT.a.e.q = "screenWidth";
TNT.a.e.r = "browserWidth";
TNT.a.e.s = "browserHeight";
TNT.a.e.t = "browserTimeOffset";
TNT.a.e.u = "colorDepth";
TNT.a.e.v = "mboxXDomain";
TNT.a.e.w = "mboxURL";
TNT.a.e.x = "mboxReferrer";
TNT.a.e.y = "mboxVersion";
TNT.a.e.c = "mbox";
TNT.a.e.z = "mboxId";
TNT.a.e.A = "mboxDOMLoaded";
TNT.a.e.B = "mboxTime";
TNT.a.e.C = "scPluginVersion";

TNT.a.D = {};
TNT.a.D.E = "mboxDisable";
TNT.a.D.F = "mboxSession";
TNT.a.D.G = "mboxEnv";
TNT.a.D.H = "mboxDebug";

TNT.a.I = {};
TNT.a.I.E = "disable";
TNT.a.I.F = "session";
TNT.a.I.o = "PC";
TNT.a.I.J = "level";
TNT.a.I.K = "check";
TNT.a.I.H = "debug";
TNT.a.I.L = "em-disabled";

TNT.a.M = {};
TNT.a.M.N = "default";
TNT.a.M.O = "mbox";
TNT.a.M.P = "mboxImported-";
TNT.a.M.Q = 60000;
TNT.a.M.R = "mboxDefault";
TNT.a.M.S = "mboxMarker-";
TNT.a.M.T = 250;
TNT.a.M.C = 1;

TNT.getGlobalMboxName = function () {
 return TNT.a.b.globalMboxName;
};

TNT.getGlobalMboxLocation = function () {
 return TNT.a.b.globalMboxLocationDomId;
};

TNT.isAutoCreateGlobalMbox = function () {
 return TNT.a.b.globalMboxAutoCreate;
};

TNT.getClientMboxExtraParameters = function () {
 return TNT.a.b.parametersFunction();
};

TNT.a.U = {};

TNT.a.U.V = function(W) {
 var X = {}.toString;

 return X.call(W) === '[object Undefined]';
};

TNT.a.U.Y = function(W) {
 var X = {}.toString;

 return X.call(W) === '[object Null]';
};

TNT.a.U.Z = function(W) {
 var U = TNT.a.U;

 if (U.V(W) || U.Y(W)) {
  return true;
 }

 return W.length === 0;
};

TNT.a.U._ = function(W) {
 var X = {}.toString;

 return X.call(W) === '[object Function]';
};

TNT.a.U.ab = function(W) {
 var X = {}.toString;

 return X.call(W) === '[object Array]';
};

TNT.a.U.bb = function(W) {
 var X = {}.toString;

 return X.call(W) === '[object String]';
};

TNT.a.U.cb = function(W) {
 var X = {}.toString;

 return X.call(W) === '[object Object]';
};

TNT.getTargetPageParameters = function () {
 var U = TNT.a.U;
 var db = window.targetPageParams;

 if (!U._(db)) {
  return [];
 }

 var eb = null;

 try {
  eb = db();
 } catch (fb) {}

 if (U.Y(eb)) {
  return [];
 }

 if (U.ab(eb)) {
  return eb;
 }

 if (U.bb(eb) && !U.Z(eb)) {
  return TNT.a.gb(eb);
 }

 if (U.cb(eb)) {
  return TNT.a.hb(eb, []);
 }

 return [];
};

TNT.a.gb = function(ib) {
 var eb = [];
 var jb = /([^&=]+)=([^&]*)/g;
 var kb = decodeURIComponent;
 var lb = jb.exec(ib);

 while (lb) {
  eb.push([kb(lb[1]), kb(lb[2])].join('='));
  lb = jb.exec(ib);
 }

 return eb;
};

TNT.a.hb = function (mb, nb) {
 var U = TNT.a.U;
 var eb = [];

 for (var ob in mb) {
  if (!mb.hasOwnProperty(ob)) {
   continue;
  }

  var W = mb[ob];

  if (U.cb(W)) {
   nb.push(ob);
   eb = eb.concat(TNT.a.hb(W, nb));
   nb.pop();
  } else {
   if (nb.length > 0) {
    eb.push([nb.concat(ob).join('.'), W].join('='));
   } else {
    eb.push([ob, W].join('='));
   }
  }
 }

 return eb;
};

mboxUrlBuilder = function(pb, qb) {
 this.pb = pb;
 this.qb = qb;
 this.rb = [];
 this.sb = function(w) { return w; };
 this.tb = null;
};

mboxUrlBuilder.prototype.addNewParameter = function (ub, W) {
 this.rb.push({name: ub, value: W});
 return this;
};

mboxUrlBuilder.prototype.addParameterIfAbsent = function (ub, W) {
 if (W) {
  for (var vb = 0; vb < this.rb.length; vb++) {
   var wb = this.rb[vb];
   if (wb.name === ub) {
    return this;
   }
  }

  this.checkInvalidCharacters(ub);
  return this.addNewParameter(ub, W);
 }
};

mboxUrlBuilder.prototype.addParameter = function(ub, W) {
 this.checkInvalidCharacters(ub);

 for (var vb = 0; vb < this.rb.length; vb++) {
  var wb = this.rb[vb];
  if (wb.name === ub) {
   wb.value = W;
   return this;
  }
 }

 return this.addNewParameter(ub, W);
};

mboxUrlBuilder.prototype.addParameters = function(rb) {
 if (!rb) {
  return this;
 }
 for (var vb = 0; vb < rb.length; vb++) {
  var xb = rb[vb].indexOf('=');
  if (xb === -1 || xb === 0) {
   continue;
  }
  this.addParameter(rb[vb].substring(0, xb),
    rb[vb].substring(xb + 1, rb[vb].length));
 }
 return this;
};

mboxUrlBuilder.prototype.setServerType = function(yb) {
 this.zb = yb;
};

mboxUrlBuilder.prototype.setBasePath = function(tb) {
 this.tb = tb;
};

mboxUrlBuilder.prototype.setUrlProcessAction = function(Ab) {
 this.sb = Ab;
};

mboxUrlBuilder.prototype.buildUrl = function() {
 var Bb = this.tb ? this.tb : '/m2/' + this.qb + '/mbox/' + this.zb;
 var Cb = document.location.protocol == 'file:' ? 'http:' : document.location.protocol;
 var w = Cb + "//" + this.pb + Bb;
 var Db = w.indexOf('?') != -1 ? '&' : '?';

 for (var vb = 0; vb < this.rb.length; vb++) {
  var wb = this.rb[vb];
  w += Db + encodeURIComponent(wb.name) + '=' + encodeURIComponent(wb.value);
  Db = '&';
 }

 return this.Eb(this.sb(w));
};

mboxUrlBuilder.prototype.getParameters = function() {
 return this.rb;
};

mboxUrlBuilder.prototype.setParameters = function(rb) {
 this.rb = rb;
};

mboxUrlBuilder.prototype.clone = function() {
 var Fb = new mboxUrlBuilder(this.pb, this.qb);

 Fb.setServerType(this.zb);
 Fb.setBasePath(this.tb);
 Fb.setUrlProcessAction(this.sb);

 for (var vb = 0; vb < this.rb.length; vb++) {
  Fb.addParameter(this.rb[vb].name, this.rb[vb].value);
 }

 return Fb;
};

mboxUrlBuilder.prototype.Eb = function(Gb) {
 return Gb.replace(/\"/g, '"').replace(/>/g, '>');
};

mboxUrlBuilder.prototype.checkInvalidCharacters = function (ub) {
 var Hb = new RegExp('(\'|")');

 if (Hb.exec(ub)) {
  throw "Parameter '" + ub + "' contains invalid characters";
 }
};

mboxStandardFetcher = function() { };

mboxStandardFetcher.prototype.getType = function() {
 return 'standard';
};

mboxStandardFetcher.prototype.fetch = function(Ib) {
 Ib.setServerType(this.getType());

 document.write('<' + 'scr' + 'ipt src="' + Ib.buildUrl() + '"><' + '\/scr' + 'ipt>');
};

mboxStandardFetcher.prototype.cancel = function() { };

mboxAjaxFetcher = function() { };

mboxAjaxFetcher.prototype.getType = function() {
 return 'ajax';
};

mboxAjaxFetcher.prototype.fetch = function(Ib) {
 Ib.setServerType(this.getType());
 var w = Ib.buildUrl();

 this.Jb = document.createElement('script');
 this.Jb.src = w;

 document.body.appendChild(this.Jb);
};

mboxAjaxFetcher.prototype.cancel = function() { };

mboxMap = function() {
 this.Kb = {};
 this.nb = [];
};

mboxMap.prototype.put = function(ob, W) {
 if (!this.Kb[ob]) {
  this.nb[this.nb.length] = ob;
 }

 this.Kb[ob] = W;
};

mboxMap.prototype.get = function(ob) {
 return this.Kb[ob];
};

mboxMap.prototype.remove = function(ob) {
 this.Kb[ob] = undefined;
 var Lb = [];

 for (var i = 0; i < this.nb.length; i++) {
  if (this.nb[i] !== ob) {
   Lb.push(this.nb[i]);
  }
 }

 this.nb = Lb;
};

mboxMap.prototype.each = function(Ab) {
 for (var vb = 0; vb < this.nb.length; vb++ ) {
  var ob = this.nb[vb];
  var W = this.Kb[ob];

  if (W) {
   var eb = Ab(ob, W);

   if (eb === false) {
    break;
   }
  }
 }
};

mboxMap.prototype.isEmpty = function() {
 return this.nb.length === 0;
};

mboxFactory = function(Mb, qb, Nb, Ob) {
 var b = TNT.a.b;
 var I = TNT.a.I;
 var D = TNT.a.D;
 var M = TNT.a.M;

 this.Pb = false;
 this.Nb = Nb;
 this.Qb = new mboxList();

 mboxFactories.put(Nb, this);

 this.Rb = b.mboxIsSupportedFunction() &&
 typeof (window.attachEvent || document.addEventListener || window.addEventListener) != 'undefined';

 this.Sb = this.Rb && mboxGetPageParameter(D.E) === null;

 var Tb = Nb == M.N;
 var Ub = M.O + (Tb ? '' : ('-' + Nb));
 this.Vb = new mboxCookieManager(Ub, b.cookieDomainFunction());

 if (b.crossDomainXOnly) {
  this.Sb = this.Sb && this.Vb.isEnabled();
 }

 this.Sb = this.Sb && (this.Vb.getCookie(I.E) === null);

 if (this.isAdmin()) {
  this.enable();
 }

 this.Wb();
 this.Xb = mboxGenerateId();
 this.Yb = mboxScreenHeight();
 this.Zb = mboxScreenWidth();
 this._b = mboxBrowserWidth();
 this.ac = mboxBrowserHeight();
 this.bc = mboxScreenColorDepth();
 this.cc = mboxBrowserTimeOffset();
 this.dc = new mboxSession(this.Xb, D.F, I.F,
   b.sessionExpirationTimeout, this.Vb);

 this.ec = new mboxPC(I.o, b.tntIdLifetime, this.Vb);
 this.Ib = new mboxUrlBuilder(Mb, qb);

 this.fc(this.Ib, Tb, Ob);

 this.gc = new Date().getTime();
 this.hc = this.gc;

 var ic = this;
 this.addOnLoad(function() { ic.hc = new Date().getTime(); });

 if (this.Rb) {

  this.addOnLoad(function() {
   ic.Pb = true;
   ic.getMboxes().each(function(d) {
    d.jc();
    d.setFetcher(new mboxAjaxFetcher());
    d.finalize(); });
   TNT.a.nestedMboxes = [];
  });

  if (this.Sb) {
   this.limitTraffic(b.trafficLevelPercentage, b.trafficDuration);

   this.kc();

   this.lc = new mboxSignaler(this);
  }
  else {
   if (!b.isProduction) {
    if (this.isAdmin()) {
     if (!this.isEnabled()) {
      alert("mbox disabled, probably due to timeout\n" +
      "Reset your cookies to re-enable\n(this message will only appear in administrative mode)");
     } else {
      alert("It looks like your browser will not allow " +
      b.companyName +
      " to set its administrative cookie. To allow setting the" +
      " cookie please lower the privacy settings of your browser.\n" +
      "(this message will only appear in administrative mode)");
     }
    }
   }
  }
 }
};

mboxFactory.prototype.forcePCId = function(mc) {
 if (!TNT.a.b.clientTntIdSupport) {
  return;
 }

 if (this.ec.forceId(mc)) {
  this.dc.forceId(mboxGenerateId());
 }
};

mboxFactory.prototype.forceSessionId = function(mc) {
 if (!TNT.a.b.clientSessionIdSupport) {
  return;
 }

 this.dc.forceId(mc);
};

mboxFactory.prototype.isEnabled = function() {
 return this.Sb;
};

mboxFactory.prototype.getDisableReason = function() {
 return this.Vb.getCookie(TNT.a.I.E);
};

mboxFactory.prototype.isSupported = function() {
 return this.Rb;
};

mboxFactory.prototype.disable = function(nc, oc) {
 if (typeof nc == 'undefined') {
  nc = 60 * 60;
 }

 if (typeof oc == 'undefined') {
  oc = 'unspecified';
 }

 if (!this.isAdmin()) {
  this.Sb = false;
  this.Vb.setCookie(TNT.a.I.E, oc, nc);
 }
};

mboxFactory.prototype.enable = function() {
 this.Sb = true;
 this.Vb.deleteCookie(TNT.a.I.E);
};

mboxFactory.prototype.isAdmin = function() {
 return document.location.href.indexOf(TNT.a.D.G) != -1;
};

mboxFactory.prototype.limitTraffic = function(pc, nc) {
 if (TNT.a.b.trafficLevelPercentage != 100) {
  if (pc == 100) {
   return;
  }

  var qc = true;

  if (parseInt(this.Vb.getCookie(TNT.a.I.J)) != pc) {
   qc = (Math.random() * 100) <= pc;
  }

  this.Vb.setCookie(TNT.a.I.J, pc, nc);

  if (!qc) {
   this.disable(60 * 60, 'limited by traffic');
  }
 }
};

mboxFactory.prototype.addOnLoad = function(rc) {

 if (this.isDomLoaded()) {
  rc();
 } else {
  var sc = false;
  var tc = function() {
   if (sc) {
    return;
   }
   sc = true;
   rc();
  };

  this.uc.push(tc);

  if (this.isDomLoaded() && !sc) {
   tc();
  }
 }
};

mboxFactory.prototype.getEllapsedTime = function() {
 return this.hc - this.gc;
};

mboxFactory.prototype.getEllapsedTimeUntil = function(B) {
 return B - this.gc;
};

mboxFactory.prototype.getMboxes = function() {
 return this.Qb;
};

mboxFactory.prototype.get = function(c, z) {
 return this.Qb.get(c).getById(z || 0);
};

mboxFactory.prototype.update = function(c, rb) {
 if (!this.isEnabled()) {
  return;
 }

 var ic = this;

 if (!this.isDomLoaded()) {
  this.addOnLoad(function() { ic.update(c, rb); });
  return;
 }

 if (this.Qb.get(c).length() === 0) {
  throw "Mbox " + c + " is not defined";
 }

 this.Qb.get(c).each(function(d) {
  var Ib = d.getUrlBuilder();

  Ib.addParameter(TNT.a.e.f, mboxGenerateId());

  ic.vc(Ib);
  ic.wc(Ib, c);

  ic.setVisitorIdParameters(Ib, c);

  d.load(rb);
 });
};

mboxFactory.prototype.setVisitorIdParameters = function(w, c) {
 if (typeof Visitor == 'undefined' || !TNT.a.b.imsOrgId) {
  return;
 }

 var visitor = Visitor.getInstance(TNT.a.b.imsOrgId);

 if (visitor.isAllowed()) {

  var addVisitorValueToUrl = function(param, getter, mboxName) {
   if (visitor[getter]) {
    var callback = function(value) {
     if (value) {
      w.addParameter(param, value);
     }
    };
    var value;
    if (typeof mboxName != 'undefined') {
     value = visitor[getter]("mbox:" + mboxName);
    } else {
     value = visitor[getter](callback);
    }
    callback(value);
   }
  };

  addVisitorValueToUrl(TNT.a.e.g, "getMarketingCloudVisitorID");
  addVisitorValueToUrl(TNT.a.e.h, "getAudienceManagerLocationHint");
  addVisitorValueToUrl(TNT.a.e.i, "getAudienceManagerBlob");
  addVisitorValueToUrl(TNT.a.e.j, "getAnalyticsVisitorID");
  addVisitorValueToUrl(TNT.a.e.k, "getSupplementalDataID", c);
 }
};

mboxFactory.prototype.create = function(c, rb, xc) {
 if (!this.isSupported()) {
  return null;
 }

 var yc = new Date();
 var B = yc.getTime() - (yc.getTimezoneOffset() * TNT.a.M.Q);
 var Ib = this.Ib.clone();

 Ib.addParameter(TNT.a.e.l, this.Qb.length() + 1);
 Ib.addParameter(TNT.a.e.B, B);
 Ib.addParameters(rb);

 this.vc(Ib);
 this.wc(Ib, c);

 this.setVisitorIdParameters(Ib, c);

 var z, zc, d;

 if (xc) {
  zc = new mboxLocatorNode(xc);
 } else {
  if (this.Pb) {
   throw 'The page has already been loaded, can\'t write marker';
  }

  zc = new mboxLocatorDefault(this.Ac(c));
 }

 try {
  z = this.Qb.get(c).length();
  d = new mbox(c, z, Ib, zc, this.Bc(c), this);

  if (this.Sb) {
   d.setFetcher(this.Pb ? new mboxAjaxFetcher() : new mboxStandardFetcher());
  }

  var ic = this;

  d.setOnError(function(Cc, yb) {
   d.setMessage(Cc);
   d.activate();

   if (!d.isActivated()) {
    ic.disable(TNT.a.b.mboxFactoryDisabledTimeout, Cc);
    window.location.reload(false);
   }
  });

  this.Qb.add(d);
 } catch (Dc) {
  this.disable();
  throw 'Failed creating mbox "' + c + '", the error was: ' + Dc;
 }

 return d;
};

mboxFactory.prototype.vc = function(Ib) {
 var o = this.ec.getId();

 if (o) {
  Ib.addParameter(TNT.a.e.o, o);
 }
};

mboxFactory.prototype.wc = function(Ib, c) {
 var Ec = !TNT.isAutoCreateGlobalMbox() && TNT.getGlobalMboxName() === c;

 if (Ec) {
  Ib.addParameters(TNT.getTargetPageParameters());
 }
};

mboxFactory.prototype.getCookieManager = function() {
 return this.Vb;
};

mboxFactory.prototype.getPageId = function() {
 return this.Xb;
};

mboxFactory.prototype.getPCId = function() {
 return this.ec;
};

mboxFactory.prototype.getSessionId = function() {
 return this.dc;
};

mboxFactory.prototype.getSignaler = function() {
 return this.lc;
};

mboxFactory.prototype.getUrlBuilder = function() {
 return this.Ib;
};

mboxFactory.prototype.Fc = function(c) {
 return this.Nb + '-' + c + '-' + this.Qb.get(c).length();
};

mboxFactory.prototype.Ac = function(c) {
 return TNT.a.M.S + this.Fc(c);
};

mboxFactory.prototype.Bc = function(c) {
 return TNT.a.M.P + this.Fc(c);
};

mboxFactory.prototype.fc = function(Ib, Tb, Ob) {
 Ib.addParameter(TNT.a.e.m, document.location.hostname);
 Ib.addParameter(TNT.a.e.f, this.Xb);
 Ib.addParameter(TNT.a.e.p, this.Yb);
 Ib.addParameter(TNT.a.e.q, this.Zb);
 Ib.addParameter(TNT.a.e.r, this._b);
 Ib.addParameter(TNT.a.e.s, this.ac);
 Ib.addParameter(TNT.a.e.t, this.cc);
 Ib.addParameter(TNT.a.e.u, this.bc);
 Ib.addParameter(TNT.a.D.F, this.dc.getId());

 if (!Tb) {
  Ib.addParameter(TNT.a.e.n, this.Nb);
 }

 this.vc(Ib);

 if (TNT.a.b.crossDomainEnabled) {
  Ib.addParameter(TNT.a.e.v, TNT.a.b.crossDomain);
 }

 var e = TNT.getClientMboxExtraParameters();

 if (e) {
  Ib.addParameters(e.split('&'));
 }

 Ib.setUrlProcessAction(function(w) {
  if (TNT.a.b.passPageParameters) {
   w += '&';
   w += TNT.a.e.w;
   w += '=' + encodeURIComponent(document.location);

   var x = encodeURIComponent(document.referrer);

   if (w.length + x.length < 2000) {
    w += '&';
    w += TNT.a.e.x;
    w += '=' + x;
   }
  }

  w += '&';
  w += TNT.a.e.y;
  w += '=' + Ob;

  return w;
 });
};

mboxFactory.prototype.kc = function() {
 document.write('<style>.' + TNT.a.M.R + ' { visibility:hidden; }</style>');
};

mboxFactory.prototype.isDomLoaded = function() {
 return this.Pb;
};

mboxFactory.prototype.Wb = function() {
 if (this.uc) {
  return;
 }

 this.uc = [];

 var ic = this;
 (function() {
  var Gc = document.addEventListener ? "DOMContentLoaded" : "onreadystatechange";
  var Hc = false;
  var Ic = function() {
   if (Hc) {
    return;
   }
   Hc = true;
   for (var i = 0; i < ic.uc.length; ++i) {
    ic.uc[i]();
   }
  };

  if (document.addEventListener) {
   document.addEventListener(Gc, function() {
    document.removeEventListener(Gc, arguments.callee, false);
    Ic();
   }, false);

   window.addEventListener("load", function(){
    document.removeEventListener("load", arguments.callee, false);
    Ic();
   }, false);

  } else if (document.attachEvent) {
   if (self !== self.top) {
    document.attachEvent(Gc, function() {
     if (document.readyState === 'complete') {
      document.detachEvent(Gc, arguments.callee);
      Ic();
     }
    });
   } else {
    var Jc = function() {
     try {
      document.documentElement.doScroll('left');
      Ic();
     } catch (Kc) {
      setTimeout(Jc, 13);
     }
    };
    Jc();
   }
  }

  if (document.readyState === "complete") {
   Ic();
  }

 })();
};

mboxSignaler = function(Lc) {
 this.Mc = document;
 this.Lc = Lc;
};

mboxSignaler.prototype.signal = function(Nc, c ) {
 if (!this.Lc.isEnabled()) {
  return;
 }

 var Oc = this.Pc(this.Lc.Ac(c));

 this.Qc(this.Mc.body, Oc);

 var d = this.Lc.create(c, mboxShiftArray(arguments), Oc);
 var Ib = d.getUrlBuilder();

 Ib.addParameter(TNT.a.e.f, mboxGenerateId());

 d.load();
};

mboxSignaler.prototype.Pc = function(Rc) {
 var eb = this.Mc.createElement('DIV');
 eb.id = Rc;
 eb.style.visibility = 'hidden';
 eb.style.display = 'none';

 return eb;
};

mboxSignaler.prototype.Qc = function(Sc, Tc) {
 Sc.appendChild(Tc);
};

mboxList = function() {
 this.Qb = [];
};

mboxList.prototype.add = function(d) {
 var U = TNT.a.U;

 if (U.V(d) || U.Y(d)) {
  return;
 }

 this.Qb[this.Qb.length] = d;
};

mboxList.prototype.get = function(c) {
 var eb = new mboxList();

 for (var vb = 0; vb < this.Qb.length; vb++) {
  var d = this.Qb[vb];

  if (d.getName() == c) {
   eb.add(d);
  }
 }

 return eb;
};

mboxList.prototype.getById = function(Uc) {
 return this.Qb[Uc];
};

mboxList.prototype.length = function() {
 return this.Qb.length;
};

mboxList.prototype.each = function(Ab) {
 if (typeof Ab !== 'function') {
  throw 'Action must be a function, was: ' + typeof(Ab);
 }

 for (var vb = 0; vb < this.Qb.length; vb++) {
  Ab(this.Qb[vb]);
 }
};

mboxLocatorDefault = function(Vc) {
 this.Vc = Vc;

 document.write('<div id="' + this.Vc + '" style="visibility:hidden;display:none"> <\/div>');
};

mboxLocatorDefault.prototype.locate = function() {
 var Wc = 1;
 var Tc = document.getElementById(this.Vc);

 while (Tc) {
  if (Tc.nodeType == Wc) {
   if (Tc.className == 'mboxDefault') {
    return Tc;
   }
  }
  Tc = Tc.previousSibling;
 }

 return null;
};

mboxLocatorDefault.prototype.force = function() {

 var Xc = document.createElement('div');
 Xc.className = 'mboxDefault';

 var Yc = document.getElementById(this.Vc);

 if (Yc) {
  Yc.parentNode.insertBefore(Xc, Yc);
 }

 return Xc;
};

mboxLocatorNode = function(Tc) {
 this.Tc = Tc;
};

mboxLocatorNode.prototype.locate = function() {
 return typeof this.Tc == 'string' ? document.getElementById(this.Tc) : this.Tc;
};

mboxLocatorNode.prototype.force = function() {
 return null;
};

mboxCreate = function(c ) {
 var d = mboxFactoryDefault.create( c, mboxShiftArray(arguments));

 if (d && mboxFactoryDefault.isEnabled()) {
  d.load();
 }

 return d;
};

mboxDefine = function(xc, c ) {
 var d = mboxFactoryDefault.create(c, mboxShiftArray(mboxShiftArray(arguments)), xc);

 return d;
};

mboxUpdate = function(c ) {
 mboxFactoryDefault.update(c, mboxShiftArray(arguments));
};

mbox = function(ub, Rc, Ib, Zc, _c, Lc) {
 this.ad = null;
 this.bd = 0;
 this.zc = Zc;
 this._c = _c;
 this.cd = null;

 this.dd = new mboxOfferContent();
 this.Xc = null;
 this.Ib = Ib;

 this.message = '';
 this.ed = {};
 this.fd = 0;

 this.Rc = Rc;
 this.ub = ub;

 this.gd();

 Ib.addParameter(TNT.a.e.c, ub);
 Ib.addParameter(TNT.a.e.z, Rc);

 this.hd = function() {};
 this.id = function() {};

 this.jd = null;

 this.kd = document.documentMode >= 10 && !Lc.isDomLoaded();

 if (this.kd) {
  this.ld = TNT.a.nestedMboxes;
  this.ld.push(this.ub);
 }
};

mbox.prototype.getId = function() {
 return this.Rc;
};

mbox.prototype.gd = function() {
 var maxLength = TNT.a.M.T;

 if (this.ub.length > maxLength) {
  throw "Mbox Name " + this.ub + " exceeds max length of " + maxLength + " characters.";
 } else if (this.ub.match(/^\s+|\s+$/g)) {
  throw "Mbox Name " + this.ub + " has leading/trailing whitespace(s).";
 }
};

mbox.prototype.getName = function() {
 return this.ub;
};

mbox.prototype.getParameters = function() {
 var rb = this.Ib.getParameters();
 var eb = [];

 for (var vb = 0; vb < rb.length; vb++) {

  if (rb[vb].name.indexOf('mbox') !== 0) {
   eb[eb.length] = rb[vb].name + '=' + rb[vb].value;
  }
 }

 return eb;
};

mbox.prototype.setOnLoad = function(Ab) {
 this.id = Ab;
 return this;
};

mbox.prototype.setMessage = function(Cc) {
 this.message = Cc;
 return this;
};

mbox.prototype.setOnError = function(hd) {
 this.hd = hd;
 return this;
};

mbox.prototype.setFetcher = function(md) {
 if (this.cd) {
  this.cd.cancel();
 }
 this.cd = md;
 return this;
};

mbox.prototype.getFetcher = function() {
 return this.cd;
};

mbox.prototype.load = function(rb) {
 if (this.cd === null) {
  return this;
 }

 this.setEventTime("load.start");
 this.cancelTimeout();
 this.bd = 0;

 var Ib = (rb && rb.length > 0) ?
   this.Ib.clone().addParameters(rb) : this.Ib;
 this.cd.fetch(Ib);

 var ic = this;
 this.nd = setTimeout(function() {
  ic.hd('browser timeout', ic.cd.getType());
 }, TNT.a.b.mboxTimeout);

 this.setEventTime("load.end");

 return this;
};

mbox.prototype.loaded = function() {
 this.cancelTimeout();
 if (!this.activate()) {
  var ic = this;
  setTimeout(function() { ic.loaded(); }, TNT.a.b.mboxLoadedTimeout);
 }
};

mbox.prototype.activate = function() {
 if (this.bd) {
  return this.bd;
 }
 this.setEventTime('activate' + (++this.fd) + '.start');

 if (this.kd && this.ld[this.ld.length - 1] !== this.ub) {
  return this.bd;
 }

 if (this.show()) {
  this.cancelTimeout();
  this.bd = 1;
 }
 this.setEventTime('activate' + this.fd + '.end');

 if (this.kd) {
  this.ld.pop();
 }
 return this.bd;
};

mbox.prototype.isActivated = function() {
 return this.bd;
};

mbox.prototype.setOffer = function(dd) {
 if (dd && dd.show && dd.setOnLoad) {
  this.dd = dd;
 } else {
  throw 'Invalid offer';
 }
 return this;
};

mbox.prototype.getOffer = function() {
 return this.dd;
};

mbox.prototype.show = function() {
 this.setEventTime('show.start');
 var eb = this.dd.show(this);
 this.setEventTime(eb == 1 ? "show.end.ok" : "show.end");

 return eb;
};

mbox.prototype.showContent = function(od) {
 if (od === null) {

  return 0;
 }

 if (this.Xc === null || !this.Xc.parentNode) {
  this.Xc = this.getDefaultDiv();

  if (this.Xc === null) {

   return 0;
  }
 }

 if (this.Xc !== od) {
  this.pd(this.Xc);
  this.Xc.parentNode.replaceChild(od, this.Xc);
  this.Xc = od;
 }

 this.qd(od);

 this.id();

 return 1;
};

mbox.prototype.hide = function() {
 this.setEventTime('hide.start');
 var eb = this.showContent(this.getDefaultDiv());
 this.setEventTime(eb == 1 ? 'hide.end.ok' : 'hide.end.fail');
 return eb;
};

mbox.prototype.finalize = function() {
 this.setEventTime('finalize.start');
 this.cancelTimeout();

 if (!this.getDefaultDiv()) {
  if (this.zc.force()) {
   this.setMessage('No default content, an empty one has been added');
  } else {
   this.setMessage('Unable to locate mbox');
  }
 }

 if (!this.activate()) {
  this.hide();
  this.setEventTime('finalize.end.hide');
 }
 this.setEventTime('finalize.end.ok');
};

mbox.prototype.cancelTimeout = function() {
 if (this.nd) {
  clearTimeout(this.nd);
 }
 if (this.cd) {
  this.cd.cancel();
 }
};

mbox.prototype.getDiv = function() {
 return this.Xc;
};

mbox.prototype.getDefaultDiv = function() {
 if (this.jd === null) {
  this.jd = this.zc.locate();
 }
 return this.jd;
};

mbox.prototype.setEventTime = function(rd) {
 this.ed[rd] = (new Date()).getTime();
};

mbox.prototype.getEventTimes = function() {
 return this.ed;
};

mbox.prototype.getImportName = function() {
 return this._c;
};

mbox.prototype.getURL = function() {
 return this.Ib.buildUrl();
};

mbox.prototype.getUrlBuilder = function() {
 return this.Ib;
};

mbox.prototype.sd = function(Xc) {
 return Xc.style.display != 'none';
};

mbox.prototype.qd = function(Xc) {
 this.td(Xc, true);
};

mbox.prototype.pd = function(Xc) {
 this.td(Xc, false);
};

mbox.prototype.td = function(Xc, ud) {
 Xc.style.visibility = ud ? "visible" : "hidden";
 Xc.style.display = ud ? "block" : "none";
};

mbox.prototype.jc = function() {
 this.kd = false;
};

mbox.prototype.relocateDefaultDiv = function() {
 this.jd = this.zc.locate();
};

mboxOfferContent = function() {
 this.id = function() {};
};

mboxOfferContent.prototype.show = function(d) {
 var eb = d.showContent(document.getElementById(d.getImportName()));
 if (eb == 1) {
  this.id();
 }
 return eb;
};

mboxOfferContent.prototype.setOnLoad = function(id) {
 this.id = id;
};

mboxOfferAjax = function(od) {
 this.od = od;
 this.id = function() {};
};

mboxOfferAjax.prototype.setOnLoad = function(id) {
 this.id = id;
};

mboxOfferAjax.prototype.show = function(d) {
 var vd = document.createElement('div');

 vd.id = d.getImportName();
 vd.innerHTML = this.od;

 var eb = d.showContent(vd);
 if (eb == 1) {
  this.id();
 }
 return eb;
};

mboxOfferDefault = function() {
 this.id = function() {};
};

mboxOfferDefault.prototype.setOnLoad = function(id) {
 this.id = id;
};

mboxOfferDefault.prototype.show = function(d) {
 var eb = d.hide();
 if (eb == 1) {
  this.id();
 }
 return eb;
};

mboxCookieManager = function mboxCookieManager(ub, wd) {
 this.ub = ub;

 this.wd = wd === '' || wd.indexOf('.') === -1 ? '' : '; domain=' + wd;
 this.xd = new mboxMap();
 this.loadCookies();
};

mboxCookieManager.prototype.isEnabled = function() {
 this.setCookie(TNT.a.I.K, 'true', 60);
 this.loadCookies();
 return this.getCookie(TNT.a.I.K) == 'true';
};

mboxCookieManager.prototype.setCookie = function(ub, W, nc) {
 if (typeof ub != 'undefined' && typeof W != 'undefined' &&
   typeof nc != 'undefined') {
  var yd = {};
  yd.name = ub;
  yd.value = encodeURIComponent(W);

  yd.expireOn = Math.ceil(nc + new Date().getTime() / 1000);
  this.xd.put(ub, yd);
  this.saveCookies();
 }
};

mboxCookieManager.prototype.getCookie = function(ub) {
 var yd = this.xd.get(ub);
 return yd ? decodeURIComponent(yd.value) : null;
};

mboxCookieManager.prototype.deleteCookie = function(ub) {
 this.xd.remove(ub);
 this.saveCookies();
};

mboxCookieManager.prototype.getCookieNames = function(zd) {
 var Ad = [];
 this.xd.each(function(ub, yd) {
  if (ub.indexOf(zd) === 0) {
   Ad[Ad.length] = ub;
  }
 });
 return Ad;
};

mboxCookieManager.prototype.saveCookies = function() {
 var Bd = TNT.a.b.crossDomainXOnly;
 var Cd = TNT.a.I.E;
 var Dd = [];
 var Ed = 0;

 this.xd.each(function(ub, yd) {
  if(!Bd || ub === Cd) {
   Dd[Dd.length] = ub + '#' + yd.value + '#' + yd.expireOn;

   if (Ed < yd.expireOn) {
    Ed = yd.expireOn;
   }
  }
 });

 var Fd = new Date(Ed * 1000);
 var Gd = [];

 Gd.push(this.ub, '=', Dd.join('|'));

 if (TNT.a.b.usePersistentCookies) {
  Gd.push('; expires=', Fd.toGMTString());
 }

 Gd.push('; path=/', this.wd);

 document.cookie = Gd.join("");
};

mboxCookieManager.prototype.loadCookies = function() {
 this.xd = new mboxMap();
 var Hd = document.cookie.indexOf(this.ub + '=');
 if (Hd != -1) {
  var Id = document.cookie.indexOf(';', Hd);
  if (Id == -1) {
   Id = document.cookie.indexOf(',', Hd);
   if (Id == -1) {
    Id = document.cookie.length;
   }
  }
  var Jd = document.cookie.substring(
    Hd + this.ub.length + 1, Id).split('|');

  var Kd = Math.ceil(new Date().getTime() / 1000);
  for (var vb = 0; vb < Jd.length; vb++) {
   var yd = Jd[vb].split('#');
   if (Kd <= yd[2]) {
    var Ld = {};
    Ld.name = yd[0];
    Ld.value = yd[1];
    Ld.expireOn = yd[2];
    this.xd.put(Ld.name, Ld);
   }
  }
 }
};

mboxSession = function(Md, Nd, Ub, Od, Vb) {
 this.Nd = Nd;
 this.Ub = Ub;
 this.Od = Od;
 this.Vb = Vb;
 this.Rc = typeof mboxForceSessionId != 'undefined' ? mboxForceSessionId : mboxGetPageParameter(this.Nd);

 if (this.Rc === null || this.Rc.length === 0) {
  this.Rc = Vb.getCookie(Ub);

  if (this.Rc === null || this.Rc.length === 0) {
   this.Rc = Md;
  }
 }

 this.Vb.setCookie(Ub, this.Rc, Od);
};

mboxSession.prototype.getId = function() {
 return this.Rc;
};

mboxSession.prototype.forceId = function(mc) {
 this.Rc = mc;

 this.Vb.setCookie(this.Ub, this.Rc, this.Od);
};

mboxPC = function(Ub, Od, Vb) {
 this.Ub = Ub;
 this.Od = Od;
 this.Vb = Vb;
 this.Rc = typeof mboxForcePCId != 'undefined' ? mboxForcePCId : Vb.getCookie(Ub);

 if (this.Rc) {
  Vb.setCookie(Ub, this.Rc, Od);
 }

};

mboxPC.prototype.getId = function() {
 return this.Rc;
};

mboxPC.prototype.forceId = function(mc) {
 if (this.Rc != mc) {
  this.Rc = mc;
  this.Vb.setCookie(this.Ub, this.Rc, this.Od);

  return true;
 }

 return false;
};

mboxGetPageParameter = function(ub) {
 var eb = null;
 var Pd = new RegExp("\\?[^#]*" + ub + "=([^\&;#]*)");
 var Qd = Pd.exec(document.location);

 if (Qd && Qd.length >= 2) {
  eb = Qd[1];
 }

 return eb;
};

mboxSetCookie = function(ub, W, nc) {
 return mboxFactoryDefault.getCookieManager().setCookie(ub, W, nc);
};

mboxGetCookie = function(ub) {
 return mboxFactoryDefault.getCookieManager().getCookie(ub);
};

mboxCookiePageDomain = function() {
 var wd = (/([^:]*)(:[0-9]{0,5})?/).exec(document.location.host)[1];
 var Rd = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/;

 if (!Rd.exec(wd)) {
  var Sd = (/([^\.]+\.[^\.]{3}|[^\.]+\.[^\.]+\.[^\.]{2})$/).exec(wd);

  if (Sd) {
   wd = Sd[0];

   if (wd.indexOf("www.") === 0) {
    wd=wd.substr(4);
   }
  }
 }

 return wd ? wd: "";
};

mboxShiftArray = function(Td) {
 var eb = [];

 for (var vb = 1; vb < Td.length; vb++) {
  eb[eb.length] = Td[vb];
 }

 return eb;
};

mboxGenerateId = function() {
 return (new Date()).getTime() + "-" + Math.floor(Math.random() * 999999);
};

mboxScreenHeight = function() {
 return screen.height;
};

mboxScreenWidth = function() {
 return screen.width;
};

mboxBrowserWidth = function() {
 return (window.innerWidth) ? window.innerWidth :
   document.documentElement ? document.documentElement.clientWidth :
     document.body.clientWidth;
};

mboxBrowserHeight = function() {
 return (window.innerHeight) ? window.innerHeight :
   document.documentElement ? document.documentElement.clientHeight :
     document.body.clientHeight;
};

mboxBrowserTimeOffset = function() {
 return -new Date().getTimezoneOffset();
};

mboxScreenColorDepth = function() {
 return screen.pixelDepth;
};

TNT.a.Ud = function(Vd, Wd, Ub, nc, Vb) {
 if (!Wd.targetJSLoaded) {
  Vb.setCookie(Ub, true, nc);
  Vd.location.reload();
 }
};

TNT.a.Xd = function(Vd, Mc, b, I, Vb) {
 var Yd = '_AT';
 var _d = 50;
 var Ub = I.L;
 var nc = b.experienceManagerDisabledTimeout;
 var ad = b.experienceManagerTimeout;
 var w = b.experienceManagerPluginUrl;
 var ae = Vd.setTimeout;
 var be = function(ce){};
 var de = function(ce){ ae(function() {Vd[Yd].applyWhenReady(ce);}, _d); };

 if (Yd in Vd) {
  return;
 }

 Vd[Yd] = {};

 if (Vb.getCookie(Ub) !== 'true') {
  Mc.write('<scr' + 'ipt src="' + w + '"><\/sc' + 'ript>');

  Vd[Yd].applyWhenReady = de;

  ae(function() {
   TNT.a.Ud(Vd, Vd[Yd], Ub, nc, Vb);
  }, ad);
 } else {
  Vd[Yd].applyWhenReady = be;
 }
};

mboxVizTargetUrl = function(c ) {
 if (!mboxFactoryDefault.isEnabled()) {
  return;
 }

 var e = TNT.a.e;
 var Q = TNT.a.M.Q;
 var qb = TNT.a.b.clientCode;
 var yc = new Date();
 var ee = yc.getTimezoneOffset() * Q;
 var Ib = mboxFactoryDefault.getUrlBuilder().clone();

 Ib.setBasePath('/m2/' + qb + '/viztarget');
 Ib.addParameter(e.c, c);
 Ib.addParameter(e.z, 0);
 Ib.addParameter(e.l, mboxFactoryDefault.getMboxes().length() + 1);
 Ib.addParameter(e.B, yc.getTime() - ee);
 Ib.addParameter(e.f, mboxGenerateId());
 Ib.addParameter(e.A, mboxFactoryDefault.isDomLoaded());

 var rb = mboxShiftArray(arguments);

 if (rb && rb.length > 0) {
  Ib.addParameters(rb);
 }

 mboxFactoryDefault.vc(Ib);
 mboxFactoryDefault.wc(Ib, c);
 mboxFactoryDefault.setVisitorIdParameters(Ib, c);

 return Ib.buildUrl();
};

TNT.createGlobalMbox = function () {
 var fe = TNT.getGlobalMboxName();
 var ge = TNT.getGlobalMboxLocation();
 var he;

 if (!ge) {
  ge = "mbox-" + fe + "-" + mboxGenerateId();
  he = document.createElement("div");
  he.className = "mboxDefault";
  he.id = ge;
  he.style.visibility = "hidden";
  he.style.display = "none";

  var ie = setInterval(function(){
   if (document.body) {
    clearInterval(ie);
    document.body.insertBefore(he, document.body.firstChild);
   }
  }, TNT.a.b.bodyPollingTimeout);
 }

 var je = TNT.getTargetPageParameters();
 var ke = mboxFactoryDefault.create(fe, je, ge);

 if (ke && mboxFactoryDefault.isEnabled()) {
  ke.load();
 }
};

TNT.a.le = function(Vb, me, ne) {
 return mboxGetPageParameter(me) || Vb.getCookie(ne);
};

TNT.a.oe = function(b) {
 setTimeout(function() {
  if (typeof mboxDebugLoaded == 'undefined') {
   alert('Could not load the remote debug.\nPlease check your connection to ' + b.companyName + ' servers');
  }
 }, 60*60);

 var w = b.adminUrl + '/mbox/mbox_debug.jsp?mboxServerHost=' + b.serverHost + '&clientCode=' +
   b.clientCode;

 document.write('<' + 'scr' + 'ipt src="' + w + '"><' + '\/scr' + 'ipt>');
};

TNT.a.pe = function(b) {
 var U = TNT.a.U;

 return !U.V(b) && !U.Y(b) && U.cb(b);
};

TNT.a.qe = function(b, re) {
 var U = TNT.a.U;
 var se;
 var te;
 var W;

 for (var ob in b) {
  se = b.hasOwnProperty(ob) && re.hasOwnProperty(ob);
  W = b[ob];
  te = !U.V(W) && !U.Y(W);

  if (se && te) {
   re[ob] = W;
  }
 }

 return re;
};

TNT.a.ue = function() {
 var b = window.targetGlobalSettings;

 if (TNT.a.pe(b)) {
  TNT.a.b = TNT.a.qe(b, TNT.a.b);
 }

 var Ob = TNT.a.b.mboxVersion;
 var ve = TNT.a.b.serverHost;
 var qb = TNT.a.b.clientCode;
 var N = TNT.a.M.N;
 var me = TNT.a.D.H;
 var ne = TNT.a.I.H;

 if (typeof mboxVersion == 'undefined') {

  window.mboxFactories = new mboxMap();
  window.mboxFactoryDefault = new mboxFactory(ve, qb, N, Ob);
  window.mboxVersion = Ob;
 }

 if (TNT.a.le(mboxFactoryDefault.getCookieManager(), me, ne)){
  TNT.a.oe(TNT.a.b);
 }
};

TNT.a.ue();

(function(){
 var b = TNT.a.b;
 var I = TNT.a.I;
 var Vb = mboxFactoryDefault.getCookieManager();

 TNT.a.Xd(window, document, b, I, Vb);
}());

TNT.a.b.clientJavascriptFunction();

if (TNT.isAutoCreateGlobalMbox()) {
 TNT.createGlobalMbox();
}


text:
require 'google/apis/cloudkms_v1/service.rb'
require 'google/apis/cloudkms_v1/classes.rb'
require 'google/apis/cloudkms_v1/representations.rb'

module Google
  module Apis
    # Google Cloud Key Management Service (KMS) API
    #
    # Manages encryption for your cloud services the same way you do on-premise. You
    # can generate, use, rotate, and destroy AES256 encryption keys.
    #
    # @see https://cloud.google.com/kms/
    module CloudkmsV1
      VERSION = 'V1'
      REVISION = '20170425'

      # View and manage your data across Google Cloud Platform services
      AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
    end
  end
end


text:
root = getRootElement ()

local function onResourceStart ( resource )
  local players = exports.pool:getPoolElementsByType("player")
  for k, v in pairs ( players ) do
    setElementData ( v, "parachuting", false )
  end
end
addEventHandler ( "onResourceStart", getResourceRootElement ( getThisResource () ), onResourceStart )

function requestAddParachute ()
	for key,player in ipairs(exports.pool:getPoolElementsByType("player")) do
		if player ~= source then
			triggerClientEvent ( player, "doAddParachuteToPlayer", source )
		end
	end
end
addEvent ( "requestAddParachute", true )
addEventHandler ( "requestAddParachute", root, requestAddParachute )

function requestRemoveParachute ()
	exports.global:takeWeapon ( source, 46 )
	for key,player in ipairs(exports.pool:getPoolElementsByType("player")) do
		if player ~= source then
			triggerClientEvent ( player, "doRemoveParachuteFromPlayer", source )
		end
	end
end
addEvent ( "requestRemoveParachute", true )
addEventHandler ( "requestRemoveParachute", root, requestRemoveParachute )


text:
(function() {
  var __hasProp = Object.prototype.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

  arcs.collections.ResultSet = (function(_super) {

    __extends(ResultSet, _super);

    function ResultSet() {
      ResultSet.__super__.constructor.apply(this, arguments);
    }

    ResultSet.prototype.model = arcs.models.Resource;

    ResultSet.prototype.url = function() {
      return arcs.baseURL + 'resources/search';
    };

    ResultSet.prototype.selected = function() {
      return this.filter(function(result) {
        return result.get('selected');
      });
    };

    ResultSet.prototype.notSelected = function() {
      return this.reject(function(result) {
        return result.get('selected');
      });
    };

    ResultSet.prototype.anySelected = function() {
      return this.any(function(result) {
        return result.get('selected');
      });
    };

    ResultSet.prototype.numSelected = function() {
      return this.selected().length;
    };

    ResultSet.prototype.select = function(result) {
      return this._eachSetSelected(result, function() {
        return true;
      });
    };

    ResultSet.prototype.toggle = function(result) {
      return this._eachSetSelected(result, function(m) {
        return !m.get('selected');
      });
    };

    ResultSet.prototype.unselect = function(result) {
      return this._eachSetSelected(result, function() {
        return false;
      });
    };

    ResultSet.prototype.unselectAll = function() {
      return this.each(function(result) {
        return result.set('selected', false, {
          silent: true
        });
      });
    };

    ResultSet.prototype._eachSetSelected = function(result, func) {
      var id, model, _i, _len, _results;
      if (!_.isArray(result)) result = [result];
      _results = [];
      for (_i = 0, _len = result.length; _i < _len; _i++) {
        id = result[_i];
        model = this.get(id);
        if (!model) continue;
        _results.push(model.set('selected', func(model), {
          silent: true
        }));
      }
      return _results;
    };

    ResultSet.prototype.parse = function(response) {
      this.metadata = response;
      return response.results;
    };

    return ResultSet;

  })(Backbone.Collection);

}).call(this);


text:
kafka-rest
==========

kafka-rest is a node.js library for the Kafka REST Proxy. It provides a thin
wrapper around the REST API, providing a more convenient interface for accessing
cluster metadata and producing and consuming Avro and binary data.

Getting Started
---------------

You can install the `kafka-rest` library via npm:

    npm install kafka-rest

The only required dependency is `async`. However, some additional libraries are
required to run the examples and are included as devDependencies.

Next, make sure you have Kafka, the Schema Registry (if using Avro), and the
Kafka REST Proxy running. The [Confluent Quickstart](http://confluent.io/docs/current/quickstart.html) and
[REST Proxy](http://confluent.io/docs/current/kafka-rest/docs/intro.html#installation)
documentation explains how to do this step-by-step.

API
---

Start by requiring the library and creating a `KafkaRest` object to interact
with the server:

    var KafkaRest = require('kafka-rest');
    var kafka = new KafkaRest({ 'url': 'http://localhost:8082' });

### Metadata

The API mirrors the REST API closely: there are resources for Brokers, Topics,
Partitions, and Consumers, and these are available in the `KafkaRest`
object. For example, to get a list of brokers (we'll skip error checking to keep
things simple):

    // kafka.brokers is a Brokers instance, list() returns a list of Broker instances
    kafka.brokers.list(function(err, brokers) {
        for(var i = 0; i < brokers.length; i++)
            console.log(brokers[i].toString());
    });

Objects generated from API responses will have a field `raw` where you can get
at the raw response data. For the brokers, `brokers[i].raw` would just be a
number because the broker list API only returns broker IDs.

All types have both collection (`Topics`) and singular (`Topic`) types
corresponding to the `/topics` and `/topics/<topic>` API endpoints. The
collection types primary method is `list()` which returns a list of singular
types which are initialize **only with the data returned by the API call to get
the list of objects**. Singular objects can be constructed directly, or there is
a shorthand via the collection type:

    kafka.topics.get('test', function(err, topic) {
        // topic is a Topic object
    });

And you can create an incomplete singular object (i.e. no API call is made, only
its identifying properties are stored):

    kafka.topics.topic('test');

This can be useful when you want to get directly at a nested resource you know
the path to and don't want to do API calls on the intermediate resources
(i.e. get a single partition, but don't look up topic metadata):

    // The complete version makes the resource hierarchy clear
    kafka.topics.topic('test').partitions().partition(0);
    // Or use the shorter version. Under the hood they do the same thing, so you
    // can use whichever is clearer based on context
    kafka.topic('test').partition(0);
    // For partitions there's also:
    kafka.topicPartition('test', 0)

If you have an incomplete singular object returned by a `list()` call, you can
fill request its data using `get()`.

### Producing

You can produce messages by calling `produce()` on `Topic` or `Partition`
objects. They can be incomplete instances, e.g.:

    kafka.topic('test').produce('message')

With this one method you can:

* Specify values by passing them in directly, or records with any combination
  of key, value, and partition fields. (Only `Topic` objects support the
  partition field).
* Send a batch of messages by passing them as separate arguments or as an
  array. Messages may be of mixed form, i.e. some may be raw values, others may
  be records with key and value fields.
* Send raw binary data (`null`, `string`, or `Buffer` objects) or Avro data (in
  JSON form) with a schema. For Avro data, you can pass up to two `AvroSchema`
  objects. If one is included, it is used as the value schema; if two are
  include the first is the key schema, the second is the value schema.
* Add a callback of the form `function(err, res)` anywhere in the argument list
  to be notified when the request completes. `res` is the JSON response returned
  by the proxy.

Here are a few examples showing these features:

    // With binary data:

    // Single message with a string value
    topic.produce('msg1');

    // Single message with key, value, and partition, with callback
    topic.produce({'key': 'key1', 'value': 'msg1', 'partition': 0}, function(err,res){});

    // Any record fields can be omitted
    topic.produce({'partition': 0, 'value': 'msg1'});

    // Multiple messages containing only values
    topic.produce('msg1', 'msg2', 'msg3');

    // Multiple messages containing only values, passed as array
    topic.produce(['msg1', 'msg2', 'msg3']);

    // Multiple messages, mixed format
    topic.produce('msg1', {'partition': 0, 'value': 'msg2'});

    // With Avro data:

    var userIdSchema = new KafkaRest.AvroSchema("int");
    var userInfoSchema = new KafkaRest.AvroSchema({
        "name": "UserInfo",
        "type": "record",
        "fields": [
            { "name": "id", "type": "int" },
            { "name": "name", "type": "string" }]
    });

    // Avro value schema followed by messages containing only values
    topic.produce(userInfoSchema, {'avro': 'record'}, {'avro': 'another record'});

    // Avro key and value schema.
    topic.produce(userIdSchema, userInfoSchema, {'key': 1, 'value': {'id': 1, 'name': 'Bob'}});

To avoid sending schemas with every request, the REST API supports *schema IDs*.
Use of schema IDs is handled transparently for you -- as long as you
use the same `AvroSchema` object across calls to `produce()`, the IDs will be
used instead of the full schemas.

Note that because this API is a thin wrapper around the REST Proxy, you must
batch your messages to improve performance. The `twitter/stream_tweets.js`
example performs this type of batching.

### Consumers

Currently the REST proxy supports the high-level consumer interface using
consumer groups. To start consuming data, join a consumer group, optionally
specifying some configuration options (passed directly to the API call):

    kafka.consumer("my-consumer-group").join({
        "format": "avro",
        "auto.commit.enable": "true",
    }, function(err, consumer_instance) {
        // consumer_instance is a ConsumerInstance object
    });

The group doesn't have to exist yet -- if you use a new consumer group name, it
will be created. You can then subscribe to a topic, resulting in a
`ConsumerStream`, and setup event handlers:

    var stream = consumer_instance.subscribe('my-topic')
    stream.on('read', function(msgs) {
        for(var i = 0; i < msgs.length; i++)
            console.log("Got a message: key=" + msgs[i].key + " value=" + msgs[i].value + " partition=" + msgs[i].partition);
    });
    stream.on('error', function(err) {
        console.log("Something broke: " + err);
    });

The exact type for each messages key/value depends on the data format you're
reading. Binary data will have been decoded from its base64 representation into
a `Buffer` (or `null`). For Avro, you'll get an object.

Finally, when you're ready to clean up, request a graceful shutdown of the
consumer instance, which also cleans up the stream:

    consumer_instance.shutdown(function() {
        console.log("Shutdown complete.");
    });

Examples
--------

A few examples are included in the `examples/` directory:

* `metadata.js` - A simple demo of some of the metadata APIs, covering brokers,
  topics, and partitions.
* `console_producer.js` - Reads from stdin and produces each line as a message
  to a Kafka topic.
* `console_consumer.js` - Consumes a Kafka topic and writes each message to
  stdout.
* `twitter/stream_tweets.js` - Uses Twitter's API to get a realtime feed of
  tweets which it produces to a Kafka topic.
* `twitter/trending.js` - Uses the tweet data produced by the previous example
  to generate a list of trending hashtags, which it prints every 10 seconds to
  stdout.

Contribute
----------

- Source Code: https://github.com/confluentinc/kafka-rest-node
- Issue Tracker: https://github.com/confluentinc/kafka-rest-node/issues

License
-------

The project is licensed under the Apache 2 license.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using Saltarelle.Compiler.JSModel.Expressions;
using Saltarelle.Compiler.ScriptSemantics;

namespace Saltarelle.Compiler {
	public static class Utils {
		/// <summary>
		/// A type is externally visible if it and all its declaring types are public or protected (or protected internal).
		/// </summary>
		public static bool IsExternallyVisible(this ITypeDefinition type) {
			while (type != null) {
				bool isPublic = (type.Accessibility == Accessibility.Public || type.Accessibility == Accessibility.Protected || type.Accessibility == Accessibility.ProtectedOrInternal);
				if (!isPublic)
					return false;
				type = type.DeclaringTypeDefinition;
			}
			return true;
		}

		/// <summary>
		/// A member is externally visible if it is public or protected (or protected internal) and its declaring type is externally visible.
		/// </summary>
		public static bool IsExternallyVisible(this IMember member) {
			return IsExternallyVisible(member.DeclaringType.GetDefinition()) && (member.Accessibility == Accessibility.Public || member.Accessibility == Accessibility.Protected || member.Accessibility == Accessibility.ProtectedOrInternal);
		}

		private static void FindUsedUnusableTypes(IEnumerable<IType> types, IMetadataImporter metadataImporter, HashSet<ITypeDefinition> result) {
			foreach (var t in types) {
				if (t is ITypeDefinition) {
					if (metadataImporter.GetTypeSemantics((ITypeDefinition)t).Type == TypeScriptSemantics.ImplType.NotUsableFromScript)
						result.Add((ITypeDefinition)t);
				}
				else if (t is ParameterizedType) {
					var pt = (ParameterizedType)t;
					FindUsedUnusableTypes(new[] { pt.GetDefinition() }.Concat(pt.TypeArguments), metadataImporter, result);
				}
			}
		}

		public static IEnumerable<ITypeDefinition> FindUsedUnusableTypes(IEnumerable<IType> types, IMetadataImporter metadataImporter) {
			var s = new HashSet<ITypeDefinition>();
			FindUsedUnusableTypes(types, metadataImporter, s);
			return s;
		}

		/// <summary>
		/// For generic types, returns a ParameterizedType with each type argument being a TypeParameter with the name of the type parameter in the type definition. Returns the TypeDefinition itself for non-generic types.
		/// </summary>
		public static IType SelfParameterize(ITypeDefinition type) {
			return type.TypeParameterCount == 0 ? (IType)type : new ParameterizedType(type, type.TypeParameters.Select(tp => new DefaultTypeParameter(type, tp.Index, tp.Name)));
		}
	}
}


text:
package org.apache.flink.table.planner.expressions

import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.table.planner.functions.sql.FlinkSqlOperatorTable
import org.apache.flink.table.planner.typeutils.TypeCoercion
import org.apache.flink.table.planner.typeutils.TypeInfoCheckUtils._
import org.apache.flink.table.planner.validate._
import org.apache.flink.table.runtime.types.TypeInfoLogicalTypeConverter.{fromLogicalTypeToTypeInfo, fromTypeInfoToLogicalType}

import org.apache.calcite.sql.SqlOperator

abstract class BinaryArithmetic extends BinaryExpression {
  private[flink] def sqlOperator: SqlOperator

  override private[flink] def resultType: TypeInformation[_] =
    TypeCoercion.widerTypeOf(
      fromTypeInfoToLogicalType(left.resultType),
      fromTypeInfoToLogicalType(right.resultType)) match {
      case Some(t) => fromLogicalTypeToTypeInfo(t)
      case None =>
        throw new RuntimeException("This should never happen.")
    }

  override private[flink] def validateInput(): ValidationResult = {
    if (!isNumeric(left.resultType) || !isNumeric(right.resultType)) {
      ValidationFailure(s"The arithmetic '$this' requires both operands to be numeric, but was " +
        s"'$left' : '${left.resultType}' and '$right' : '${right.resultType}'.")
    } else {
      ValidationSuccess
    }
  }
}

case class Plus(left: PlannerExpression, right: PlannerExpression) extends BinaryArithmetic {
  override def toString = s"($left + $right)"

  private[flink] val sqlOperator = FlinkSqlOperatorTable.PLUS

  override private[flink] def validateInput(): ValidationResult = {
    if (isString(left.resultType) || isString(right.resultType)) {
      ValidationSuccess
    } else if (isTimeInterval(left.resultType) && left.resultType == right.resultType) {
      ValidationSuccess
    } else if (isTimePoint(left.resultType) && isTimeInterval(right.resultType)) {
      ValidationSuccess
    } else if (isTimeInterval(left.resultType) && isTimePoint(right.resultType)) {
      ValidationSuccess
    } else if (isNumeric(left.resultType) && isNumeric(right.resultType)) {
      ValidationSuccess
    } else {
      ValidationFailure(
        s"The arithmetic '$this' requires input that is numeric, string, time intervals of the " +
        s"same type, or a time interval and a time point type, " +
        s"but was '$left' : '${left.resultType}' and '$right' : '${right.resultType}'.")
    }
  }

  override private[flink] def resultType: TypeInformation[_] = {
    ReturnTypeInference.inferPlus(this)
  }
}

case class UnaryMinus(child: PlannerExpression) extends UnaryExpression {
  override def toString = s"-($child)"

  override private[flink] def resultType = child.resultType

  override private[flink] def validateInput(): ValidationResult = {
    if (isNumeric(child.resultType)) {
      ValidationSuccess
    } else if (isTimeInterval(child.resultType)) {
      ValidationSuccess
    } else {
      ValidationFailure(s"The arithmetic '$this' requires input that is numeric or a time " +
        s"interval type, but was '${child.resultType}'.")
    }
  }
}

case class Minus(left: PlannerExpression, right: PlannerExpression) extends BinaryArithmetic {
  override def toString = s"($left - $right)"

  private[flink] val sqlOperator = FlinkSqlOperatorTable.MINUS

  override private[flink] def validateInput(): ValidationResult = {
    if (isTimeInterval(left.resultType) && left.resultType == right.resultType) {
      ValidationSuccess
    } else if (isTimePoint(left.resultType) && isTimeInterval(right.resultType)) {
      ValidationSuccess
    } else if (isTimeInterval(left.resultType) && isTimePoint(right.resultType)) {
      ValidationSuccess
    } else if (isNumeric(left.resultType) && isNumeric(right.resultType)) {
      ValidationSuccess
    } else {
      ValidationFailure(
        s"The arithmetic '$this' requires inputs that are numeric, time intervals of the same " +
        s"type, or a time interval and a time point type, " +
        s"but was '$left' : '${left.resultType}' and '$right' : '${right.resultType}'.")
    }
  }

  override private[flink] def resultType: TypeInformation[_] = {
    ReturnTypeInference.inferMinus(this)
  }
}

case class Div(left: PlannerExpression, right: PlannerExpression) extends BinaryArithmetic {
  override def toString = s"($left / $right)"

  private[flink] val sqlOperator = FlinkSqlOperatorTable.DIVIDE

  override private[flink] def resultType: TypeInformation[_] = {
    ReturnTypeInference.inferDiv(this)
  }

}

case class Mul(left: PlannerExpression, right: PlannerExpression) extends BinaryArithmetic {
  override def toString = s"($left * $right)"

  private[flink] val sqlOperator = FlinkSqlOperatorTable.MULTIPLY

  override private[flink] def resultType: TypeInformation[_] = {
    ReturnTypeInference.inferMul(this)
  }
}

case class Mod(left: PlannerExpression, right: PlannerExpression) extends BinaryArithmetic {
  override def toString = s"($left % $right)"

  private[flink] val sqlOperator = FlinkSqlOperatorTable.MOD
}


text:
from copy import copy
import urllib
from datetime import datetime, timedelta

from django.template.loader import render_to_string
from django.utils.translation import ugettext_noop
from django.utils.translation import ugettext as _
from custom.bihar.utils import (get_team_members, get_all_owner_ids_from_group, SUPERVISOR_ROLES, FLW_ROLES,
    groups_for_user, get_role)

from corehq.apps.fixtures.models import FixtureDataItem
from corehq.apps.reports.standard import CustomProjectReport
from corehq.apps.reports.generic import GenericTabularReport,\
    SummaryTablularReport, summary_context
from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn
from corehq.apps.reports.dispatcher import CustomProjectReportDispatcher
from dimagi.utils.excel import alphanumeric_sort_key
from dimagi.utils.html import format_html
from corehq.apps.groups.models import Group
from dimagi.utils.decorators.memoized import memoized
from casexml.apps.case.models import CommCareCase
from corehq.apps.adm.reports.supervisor import SupervisorReportsADMSection
from custom.bihar.reports.indicators.mixins import IndicatorConfigMixIn

def shared_bihar_context(report):
    return {
        'home':      MainNavReport.get_url(report.domain, render_as=report.render_next),
        'render_as': report.render_next,
        'mode': report.mode,
    }

class ConvenientBaseMixIn(object):
    # this is everything that's shared amongst the Bihar supervision reports
    # this class is an amalgamation of random behavior and is just
    # for convenience

    base_template_mobile = "bihar/base_template_mobile.html"
    report_template_path = "reports/async/tabular.html"

    hide_filters = True
    flush_layout = True
    mobile_enabled = True
    fields = []

    extra_context_providers = [shared_bihar_context]

    # for the lazy
    _headers = []  # override
    @property
    def headers(self):
        headers = self._headers[self.mode] if isinstance(self._headers, dict) else self._headers
        return DataTablesHeader(*(DataTablesColumn(_(h)) for h in headers))

    @property
    def render_next(self):
        return None if self.rendered_as == "async" else self.rendered_as

    @classmethod
    def show_in_navigation(cls, *args, **kwargs):
        return False

    @property
    @memoized
    def mode(self):
        # sup_roles = ('ANM', 'LS') # todo if we care about these
        man_roles = ('MOIC', 'BHM', 'BCM', 'CDPO')
        if self.request.couch_user.is_commcare_user():
            if get_role(self.request.couch_user) in man_roles:
                return 'manager'
        return 'supervisor'

    @property
    def is_supervisor(self):
        return self.mode == 'supervisor'

    @property
    def is_manager(self):
        return self.mode == 'manager'

def list_prompt(index, value):
    # e.g. 1. Reports
    return u"%s. %s" % (_(str(index+1)), _(value))

class ReportReferenceMixIn(object):
    # allow a report to reference another report

    @property
    def next_report_slug(self):
        return self.request_params.get("next_report")

    @property
    def next_report_class(self):
        return CustomProjectReportDispatcher().get_report(self.domain, self.next_report_slug)

class GroupReferenceMixIn(object):
    # allow a report to reference a group

    @property
    def group_id(self):
        return self.request_params["group"]

    @property
    @memoized
    def group(self):
        g = Group.get(self.group_id)
        assert g.domain == self.domain, "Group %s isn't in domain %s" % (g.get_id, self.domain)
        return g

    @memoized
    def get_team_members(self):
        """
        Get any commcare users that are either "asha" or "aww".
        """
        roles = {
            'supervisor': FLW_ROLES,
            'manager': SUPERVISOR_ROLES,
        }
        return get_team_members(self.group, roles=roles[self.mode])

    @property
    @memoized
    def all_owner_ids(self):
        return get_all_owner_ids_from_group(self.group)

    @property
    @memoized
    def cases(self):
        keys = [[self.domain, owner_id, False] for owner_id in self.all_owner_ids]
        return CommCareCase.view('hqcase/by_owner', keys=keys,
                                 include_docs=True, reduce=False)

    @property
    @memoized
    def group_display(self):
        return {
            'supervisor': u'{group} ({awcc})',
            'manager': u'{group}',
        }[self.mode].format(group=self.group.name, awcc=get_awcc(self.group))

    @property
    def rendered_report_title(self):
        return u"{title} - {group}".format(title=_(self.name),
                                           group=self.group_display)

def team_member_context(report):
    """
    Gets context for adding a team members listing to a report.
    """
    return {
        "team_members": report.get_team_members(),
    }

class BiharSummaryReport(ConvenientBaseMixIn, SummaryTablularReport,
                         CustomProjectReport):
    # this is literally just a way to do a multiple inheritance without having
    # the same 3 classes extended by a bunch of other classes
    base_template_mobile = "bihar/bihar_summary.html"
    report_template_path = "reports/async/summary_tabular.html"
    extra_context_providers = [shared_bihar_context, summary_context]

class BiharNavReport(BiharSummaryReport):
    # this is a bit of a bastardization of the summary report
    # but it is quite DRY

    preserve_url_params = False

    @property
    def reports(self):
        # override
        raise NotImplementedError("Override this!")

    @property
    def _headers(self):
        return [" "] * len(self.reports)

    @property
    def data(self):
        return [default_nav_link(self, i, report_cls) for i, report_cls in enumerate(self.reports)]

class MockEmptyReport(BiharSummaryReport):
    """
    A stub empty report
    """
    _headers = ["Whoops, this report isn't done! Sorry this is still a prototype."]
    data = [""]

class SubCenterSelectionReport(ConvenientBaseMixIn, GenericTabularReport,
                               CustomProjectReport, ReportReferenceMixIn):
    name = ugettext_noop("Select Subcenter")
    slug = "subcenter"
    description = ugettext_noop("Subcenter selection report")

    _headers = {
        'supervisor': [ugettext_noop("Team Name"), ugettext_noop("AWCC")],
        'manager': [ugettext_noop("Subcentre")],
    }

    @memoized
    def _get_groups(self):
        groups = groups_for_user(self.request.couch_user, self.domain)
        return sorted(
            groups,
            key=lambda group: alphanumeric_sort_key(group.name)
        )

    @property
    def rows(self):
        return [self._row(g, i+1) for i, g in enumerate(self._get_groups())]

    def _row(self, group, rank):

        def _link(g, text):
            params = copy(self.request_params)
            params["group"] = g.get_id
            return format_html(u'{text}',
                text=text,
                details=url_and_params(self.next_report_class.get_url(domain=self.domain,
                                                                      render_as=self.render_next),
                                       params))

        return [group.name, _link(group, get_awcc(group))] if self.is_supervisor else [_link(group, group.name)]

class MainNavReport(BiharSummaryReport, IndicatorConfigMixIn):
    name = ugettext_noop("Main Menu")
    slug = "mainnav"
    description = ugettext_noop("Main navigation")

    @classmethod
    def additional_reports(cls):
        from custom.bihar.reports.due_list import DueListSelectionReport
        from custom.bihar.reports.indicators.reports import MyPerformanceReport
        return [WorkerRankSelectionReport, DueListSelectionReport, ToolsNavReport, MyPerformanceReport]

    @classmethod
    def show_in_navigation(cls, *args, **kwargs):
        return True

    @property
    def _headers(self):
        return [" "] * (len(self.indicator_config.indicator_sets) + len(self.additional_reports()))

    @property
    def data(self):
        from custom.bihar.reports.indicators.reports import IndicatorNav

        def _indicator_nav_link(i, indicator_set):
            params = copy(self.request_params)
            params["indicators"] = indicator_set.slug
            params["next_report"] = IndicatorNav.slug
            return format_html(u'{val}',
                val=list_prompt(i, indicator_set.name),
                next=url_and_params(
                    SubCenterSelectionReport.get_url(self.domain,
                                                     render_as=self.render_next),
                    params
            ))
        return [_indicator_nav_link(i, iset) for i, iset in\
                enumerate(self.indicator_config.indicator_sets)] + \
               [default_nav_link(self, len(self.indicator_config.indicator_sets) + i, r) \
                for i, r in enumerate(self.additional_reports())]

class WorkerRankSelectionReport(SubCenterSelectionReport):
    slug = "workerranks"
    name = ugettext_noop("Worker Rank Table")
    # The subreport URL is hard coded here until there's an easier
    # way to get this from configuration
    WORKER_RANK_SLUG = 'worker_rank_table'

    def _row(self, group, rank):
        def _get_url():
            # HACK: hard(ish) code get_url until we fix the render_as bug
            url = SupervisorReportsADMSection.get_url(domain=self.domain,
                                                      subreport=self.WORKER_RANK_SLUG)
            # /a/[domain]/reports/adm/[section]/[subreport]/
            # needs to become
            # /a/[domain]/reports/adm/[render_as]/[section]/[subreport]/
            if self.render_next:
                section_chunk = "/{section}/".format(section=SupervisorReportsADMSection.slug)
                section_with_rendering = "/{render_as}{section_chunk}".format(
                    render_as=self.render_next, section_chunk=section_chunk
                )
                url = url.replace(section_chunk, section_with_rendering)
            return url

        url = _get_url()
        end = datetime.today().date()
        start = end - timedelta(days=30)
        params = {
            "ufilter": 0,
            "startdate": start.strftime("%Y-%m-%d"),
            "enddate": end.strftime("%Y-%m-%d")
        }
        def _awcc_link(g):
            params["group"] = g.get_id
            return format_html(u'{awcc}',
                awcc=get_awcc(g),
                details=url_and_params(url,
                                       params))
        return [group.name, _awcc_link(group)]

class ToolsNavReport(BiharSummaryReport):
    name = ugettext_noop("Tools Menu")
    slug = "tools"

    _headers = [" ", " ", " "]

    @property
    def data(self):
        def _referral_link(i):
            params = copy(self.request_params)
            params["next_report"] = ReferralListReport.slug
            return format_html(u'{val}',
                val=list_prompt(i, _(ReferralListReport.name)),
                next=url_and_params(
                    SubCenterSelectionReport.get_url(self.domain,
                                                     render_as=self.render_next),
                    params
            ))
        return [_referral_link(0),
                default_nav_link(self, 1, EDDCalcReport),
                default_nav_link(self, 2, BMICalcReport),]

class ReferralListReport(GroupReferenceMixIn, MockEmptyReport):
    name = ugettext_noop("Referrals")
    slug = "referrals"

    _headers = []

    @property
    def data(self): # this is being called multiple times

        def render(f):
            title = {
                "public": _("Public Facility"),
                "private": _("Private Facility"),
                "transport": _("Transport")
            }[f.fields_without_attributes["type"]]
            return format_html(u"%s: %s
# %s" % (title, f.fields_without_attributes.get("name", ""), f.fields_without_attributes.get("number", "")))

        fixtures = FixtureDataItem.by_group(self.group)
        _data = []
        self._headers = []
        for f in fixtures:
            _data.append(render(f))
            self._headers.append(" ")

        if not _data:
            _data = ['No referrals for %s' % self.group.name]
            self._headers = [" "]
        return _data

class InputReport(MockEmptyReport):
    name = ""
    slug = ""
    _headers = [" "]
    _inputs = []

    @property
    def form_html(self):
        return render_to_string("bihar/partials/input.html", {"inputs": self._inputs})

    @property
    def data(self):
        for i in self._inputs:
            if not self.request.GET.get(i["name"], None):
                return [self.form_html]
        return self.calc(self.request.GET)

    def calc(self, input):
        return [_("This calculation has not yet been implemented.")]

class EDDCalcReport(InputReport):
    name = ugettext_noop("EDD Calculator")
    slug = "eddcalc"
    _inputs = [
        {
            "name": "lmp",
            "type": "text",
            "label": ugettext_noop("Enter LMP (DD-MM-YYYY)")
        }
    ]

    _headers = [" "]

    def calc(self, input):
        try:
            lmp_date = datetime.strptime(input["lmp"], "%d-%m-%Y")
            edd_date = lmp_date + timedelta(days=280)
            return [_("Estimated Date of Delivery: %s") % edd_date.strftime("%d-%m-%Y")]
        except ValueError:
            self._headers = [" ", " "]
            return [_("Error: We can't parse your input, please try again"), self.form_html]

class BMICalcReport(InputReport):
    name = ugettext_noop("BMI Calculator")
    slug = "bmicalc"
    _inputs = [
        {
            "name": "weight",
            "type": "text",
            "label": ugettext_noop("Enter weight in kilograms:")
        },
        {
            "name": "height",
            "type": "text",
            "label": ugettext_noop("Enter height in meters:")
        }
    ]

    def calc(self, input):
        try:
            weight = float(input["weight"])
            height = float(input["height"])
        except ValueError:
            self._headers = [" ", " "]
            return [_("Error: We can't parse your input, please try again"), self.form_html]

        bmi = weight / (height * height)
        if bmi >= 30:
            return [_("You are obese")]
        elif bmi >= 25:
            return [_("You are overweight")]
        elif bmi >= 18.5:
            return [_("You are normal weight")]
        else:
            return [_("You are underweight")]

def default_nav_link(nav_report, i, report_cls):
    url = report_cls.get_url(nav_report.domain,
                             render_as=nav_report.render_next)
    if getattr(nav_report, 'preserve_url_params', False):
        url = url_and_params(url, nav_report.request_params)
    return format_html(u'{val}',
                        val=list_prompt(i, report_cls.name),
                        details=url)

def get_awcc(group):
    return group.metadata.get("awc-code") or _('no awcc')

def url_and_params(urlbase, params):
    assert "?" not in urlbase
    return "{url}?{params}".format(url=urlbase,
                                   params=urllib.urlencode(params))


text:
.. include:: replace.txt
.. highlight:: bash

Troubleshooting
---------------

This chapter posts some information about possibly common errors in building
or running |ns3| programs.

Please note that the wiki
(`<http://www.nsnam.org/wiki/Troubleshooting>`_) may have contributed
items.

Build errors
************

Run-time errors
***************

Sometimes, errors can occur with a program after a successful build. These are
run-time errors, and can commonly occur when memory is corrupted or pointer
values are unexpectedly null.

Here is an example of what might occur::

    $ ./waf --run tcp-point-to-point
    Entering directory '/home/tomh/ns-3-nsc/build'
    Compilation finished successfully
    Command ['/home/tomh/ns-3-nsc/build/debug/examples/tcp-point-to-point'] exited with code -11

The error message says that the program terminated unsuccessfully, but it is
not clear from this information what might be wrong. To examine more
closely, try running it under the `gdb debugger
<http://sources.redhat.com/gdb/>`_:

.. sourcecode:: bash

    $ ./waf --run tcp-point-to-point --command-template="gdb %s"
    Entering directory '/home/tomh/ns-3-nsc/build'
    Compilation finished successfully
    GNU gdb Red Hat Linux (6.3.0.0-1.134.fc5rh)
    Copyright 2004 Free Software Foundation, Inc.
    GDB is free software, covered by the GNU General Public License, and you are
    welcome to change it and/or distribute copies of it under certain conditions.
    Type "show copying" to see the conditions.
    There is absolutely no warranty for GDB.  Type "show warranty" for details.
    This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db
    library "/lib/libthread_db.so.1".

    (gdb) run
    Starting program: /home/tomh/ns-3-nsc/build/debug/examples/tcp-point-to-point
    Reading symbols from shared object read from target memory...done.
    Loaded system supplied DSO at 0xf5c000

    Program received signal SIGSEGV, Segmentation fault.
    0x0804aa12 in main (argc=1, argv=0xbfdfefa4)
        at ../examples/tcp-point-to-point.cc:136
    136       Ptr<Socket> localSocket = socketFactory->CreateSocket ();
    (gdb) p localSocket
    $1 = {m_ptr = 0x3c5d65}
    (gdb) p socketFactory
    $2 = {m_ptr = 0x0}
    (gdb) quit
    The program is running.  Exit anyway? (y or n) y

Note first the way the program was invoked-- pass the command to run as an
argument to the command template "gdb %s".

This tells us that there was an attempt to dereference a null pointer
socketFactory.

Let's look around line 136 of tcp-point-to-point, as gdb suggests:

.. sourcecode:: cpp

  Ptr<SocketFactory> socketFactory = n2->GetObject<SocketFactory> (Tcp::iid);
  Ptr<Socket> localSocket = socketFactory->CreateSocket ();
  localSocket->Bind ();

The culprit here is that the return value of GetObject is not being checked and
may be null.

Sometimes you may need to use the `valgrind memory checker
<http://valgrind.org>`_ for more subtle errors. Again, you invoke the use of
valgrind similarly::

    $ ./waf --run tcp-point-to-point --command-template="valgrind %s"


text:
class AddLocationToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :location, :string
    add_column :users, :relationship_status, :string
    add_column :connections, :user_id, :integer
    add_column :interests, :user_id, :integer
    add_index :connections, :user_id
    add_index :interests, :user_id
  end

  def self.down
    remove_column :users, :location
  end
end


text:
import { Injectable } from '@angular/core';
import { Http }       from '@angular/http';

import { Observable }     from 'rxjs/Observable';
import 'rxjs/add/operator/map';

import { Details }           from '../../types/details/details';

@Injectable()
export class HeroSearchService {
  constructor(private http: Http) {}
  search(term: string): Observable<Details[]> {
    return this.http
               .get(`app/heroes/?name=${term}`)
               .map(response => response.json().data as Details[]);
  }
}