text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jfsoft.mapper.CallingRuleMapper" >

	<resultMap id="BaseResultMap" type="com.jfsoft.model.CallingRule" >
		<id column="id" property="id" jdbcType="INTEGER" />
		<result column="code" property="code" jdbcType="INTEGER" />
		<result column="sexPriority" property="sexpriority" jdbcType="CHAR" />
		<result column="isVip" property="isvip" jdbcType="CHAR" />
		<result column="createTime" property="createtime" jdbcType="TIMESTAMP" />
		<result column="createrId" property="createrid" jdbcType="INTEGER" />
		<result column="memo" property="memo" jdbcType="NVARCHAR" />
	</resultMap>

	<sql id="Base_Column_List" >
		id, code, sexPriority, isVip, createTime, createrId, memo
	</sql>

	<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
		select
		<include refid="Base_Column_List" />
		from calling_rule
		where id = #{id,jdbcType=INTEGER}
	</select>

	<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
		delete from calling_rule
		where id = #{id,jdbcType=INTEGER}
	</delete>

	<insert id="insert" parameterType="com.jfsoft.model.CallingRule" >
		insert into calling_rule (id, code, sexPriority,
			isVip, createTime, createrId,
			memo)
		values (#{id,jdbcType=INTEGER}, #{code,jdbcType=INTEGER}, #{sexpriority,jdbcType=CHAR},
			#{isvip,jdbcType=CHAR}, #{createtime,jdbcType=TIMESTAMP}, #{createrid,jdbcType=INTEGER},
			#{memo,jdbcType=NVARCHAR})
	</insert>

	<insert id="insertSelective" parameterType="com.jfsoft.model.CallingRule" >
		insert into calling_rule
		<trim prefix="(" suffix=")" suffixOverrides="," >
			<if test="id != null" >
				id,
			</if>
			<if test="code != null" >
				code,
			</if>
			<if test="sexpriority != null" >
				sexPriority,
			</if>
			<if test="isvip != null" >
				isVip,
			</if>
			<if test="createtime != null" >
				createTime,
			</if>
			<if test="createrid != null" >
				createrId,
			</if>
			<if test="memo != null" >
				memo,
			</if>
		</trim>
		<trim prefix="values (" suffix=")" suffixOverrides="," >
			<if test="id != null" >
				#{id,jdbcType=INTEGER},
			</if>
			<if test="code != null" >
				#{code,jdbcType=INTEGER},
			</if>
			<if test="sexpriority != null" >
				#{sexpriority,jdbcType=CHAR},
			</if>
			<if test="isvip != null" >
				#{isvip,jdbcType=CHAR},
			</if>
			<if test="createtime != null" >
				#{createtime,jdbcType=TIMESTAMP},
			</if>
			<if test="createrid != null" >
				#{createrid,jdbcType=INTEGER},
			</if>
			<if test="memo != null" >
				#{memo,jdbcType=NVARCHAR},
			</if>
		</trim>
	</insert>

	<update id="updateByPrimaryKeySelective" parameterType="com.jfsoft.model.CallingRule" >
		update calling_rule
		<set >
			<if test="code != null" >
				code = #{code,jdbcType=INTEGER},
			</if>
			<if test="sexpriority != null" >
				sexPriority = #{sexpriority,jdbcType=CHAR},
			</if>
			<if test="isvip != null" >
				isVip = #{isvip,jdbcType=CHAR},
			</if>
			<if test="createtime != null" >
				createTime = #{createtime,jdbcType=TIMESTAMP},
			</if>
			<if test="createrid != null" >
				createrId = #{createrid,jdbcType=INTEGER},
			</if>
			<if test="memo != null" >
				memo = #{memo,jdbcType=NVARCHAR},
			</if>
		</set>
		where id = #{id,jdbcType=INTEGER}
	</update>

	<update id="updateByPrimaryKey" parameterType="com.jfsoft.model.CallingRule" >
		update calling_rule
		set code = #{code,jdbcType=INTEGER},
			sexPriority = #{sexpriority,jdbcType=CHAR},
			isVip = #{isvip,jdbcType=CHAR},
			createTime = #{createtime,jdbcType=TIMESTAMP},
			createrId = #{createrid,jdbcType=INTEGER},
			memo = #{memo,jdbcType=NVARCHAR}
		where id = #{id,jdbcType=INTEGER}
	</update>

	<select id="findPage" parameterType="java.util.Map" resultMap="BaseResultMap">
		select
			top ${pageSize}
			crs.id,crs.code,crs.sexPriority,crs.isVip,crs.createtime
		from
			(
				SELECT
					ROW_NUMBER() OVER (ORDER BY cr.id) AS rownumber,*
				FROM
					calling_rule cr
					<where>
						<if test="isVip != null" >
							and cr.isVip = #{isVip,jdbcType=CHAR}
						</if>
					</where>
			) crs
		where
			crs.rownumber > ${pageStart}
	</select>
	<select id="findPageCount" parameterType="java.util.Map" resultType="java.lang.Integer">
		select
		    count(cr.id)
		from
            calling_rule cr
            <where>
                <if test="isVip != null" >
                    and cr.isVip = #{isVip,jdbcType=CHAR}
                </if>
            </where>
	</select>

</mapper>


text:
package com.wci.umls.server.helpers;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * A message class for use with web sockets.
 */
@XmlRootElement
public class Message {

  /** The author. */
  public String author = "";

  /** The message. */
  public String message = "";

  /**
   * Instantiates an empty {@link Message}.
   */
  public Message() {
    // n/a
  }

  /**
   * Instantiates a {@link Message} from the specified parameters.
   *
   * @param author the author
   * @param message the message
   */
  public Message(String author, String message) {
    this.author = author;
    this.message = message;
  }

}

redpajama_set_name: RedPajamaGithub


text:
package com.ibm.datapower.er.Analytics.Structure;

import java.util.ArrayList;
import java.util.concurrent.Callable;

import org.w3c.dom.Element;

import com.ibm.datapower.er.FirmwareInputStream;
import com.ibm.datapower.er.Analytics.AnalyticsProcessor;
import com.ibm.datapower.er.Analytics.ConditionField;
import com.ibm.datapower.er.Analytics.ConditionsNode;
import com.ibm.datapower.er.Analytics.DocumentSection;
import com.ibm.datapower.er.Analytics.AnalyticsFunctions;

public class RunFormula implements Callable {

	public DocumentSection documentSet = null;
	public ArrayList<ConditionsNode> condNodes;
	public Formula formula;
	public int cidSectionID;
	public Element expElement;
	public boolean expressionsMatched = false;
	public boolean nextExpressionAnd = false;
	public int formulaPos;
	public AnalyticsProcessor mProc = null;
	public int docID = 0;
	public boolean anyExpressionsMatched = false;
	public ArrayList<ConditionField> cFields = null;
	public String xPathQuery = "";
	public String isSectionVariable = "";
	public boolean bIsSectionVariable = true;
	public String regExp = "";
	public String idxSearch = ""; // narrow down document by indexOf instead of regexp
	public String requiredFile = ""; // narrow down document by indexOf instead of regexp

	public RunFormula(AnalyticsProcessor proc, DocumentSection docSet,
			int docPos, ArrayList<ConditionsNode> nodes, Formula formulaData,
			int sectionID, Element ele, boolean expressionAnd, ArrayList<ConditionField> fields, String reqFile) {
		docID = docPos;
		mProc = proc;
		documentSet = docSet;
		condNodes = nodes;
		formula = formulaData;
		cidSectionID = sectionID;
		expElement = ele;
		nextExpressionAnd = expressionAnd;
		formulaPos = (int) formula.getItem("ID").getObject();

		requiredFile = reqFile;

		loadVars();

		cFields = fields;
	}

	public RunFormula(AnalyticsProcessor proc, DocumentSection docSet,
			int docPos, ArrayList<ConditionsNode> nodes, Formula formulaData,
			int sectionID, Element ele, boolean expressionAnd,
			ArrayList<ConditionField> fields, boolean multicore) {
		docID = docPos;
		mProc = proc;
		documentSet = docSet;
		condNodes = nodes;
		formula = formulaData;
		cidSectionID = sectionID;
		expElement = ele;
		nextExpressionAnd = expressionAnd;
		formulaPos = (int) formula.getItem("ID").getObject();
		cFields = fields;

		loadVars();

		if (!multicore)
			run();

	}

	private void loadVars()
	{
		// this is the XPath expression of the value we are trying to extract to
		// compare against our condition
		xPathQuery = AnalyticsFunctions.getAttributeByTag("Section", "XPath", expElement,
				cidSectionID);

		// if set to false then we don't use it for the Condition:SectionName
		// variable in parsing the message
		isSectionVariable = AnalyticsFunctions.getAttributeByTag("Section", "SectionName",
				expElement, 0);

		// this is kind of a reverse operand, if its false then we don't want to
		// use it, otherwise we leave the old functionality/design of always
		// true
		if (isSectionVariable.toLowerCase().equals("false"))
			bIsSectionVariable = false;

		// This is the regular expression we use to break apart the value in
		// the error report (from xPath)
		regExp = FirmwareInputStream.getValueByTag("RegExp",
				expElement);

		// This is the regular expression we use to break apart the value in
		// the error report (from xPath)
		idxSearch = FirmwareInputStream.getValueByTag("IndexSearch",
				expElement);
	}

	public Object call() {
		run();
		return (Object) this;
	}

	public void run() {
		anyExpressionsMatched = mProc.handleRunFormula(this);
	}

	public Formula getFormula() {
	return formula;
	}
}


text:
package ui

import (
	"context"
	"fmt"
	"strings"
	"sync"
	"time"

	"go.chromium.org/luci/common/clock"
	"go.chromium.org/luci/common/logging"
)

const progressReportInterval = 500 * time.Millisecond

// primitiveActivity just logs its progress into the default logger.
//
// Always logs 0% and 100% progress reports and jumps back. For normal forward
// progress throttles messages per progressReportInterval.
//
// TODO(vadimsh): Only UnitBytes are supported currently.
type primitiveActivity struct {
	logger logging.Factory // wrapped logger

	group *ActivityGroup // may be nil if not inside a group
	kind  string
	id    int

	m          sync.Mutex
	lastReport time.Time
	lastTitle  string
	lastUnits  Units
	lastCur    int64
	lastTotal  int64
	speed      speedGauge
}

func (a *primitiveActivity) Progress(ctx context.Context, title string, units Units, cur, total int64) {
	now := clock.Now(ctx)

	a.m.Lock()

	// True if made any progress since the last call.
	advanced := a.lastCur != cur
	// We log every title change for progress 0% and 100%, they are important.
	titleChange := title != a.lastTitle

	// Reset the speed gauge when the progress is restarted.
	reset := a.lastCur > cur || a.lastTotal != total || a.lastUnits != units
	if reset {
		a.speed.reset(now, cur)
	} else {
		a.speed.advance(now, cur)
	}
	speed := a.speed.speed

	a.lastTitle = title
	a.lastUnits = units
	a.lastCur = cur
	a.lastTotal = total

	// Report to log on "interesting" events and also periodically.
	reportNow := (cur == 0 && titleChange) ||
		(cur == total && (advanced || titleChange)) ||
		reset ||
		now.Sub(a.lastReport) > progressReportInterval
	if reportNow {
		a.lastReport = now
	}

	a.m.Unlock()

	if !reportNow {
		return
	}

	totalStr := fmt.Sprintf("%.1f", float64(total)/1000000.0)
	curStr := fmt.Sprintf("%.1f", float64(cur)/1000000.0)
	if len(curStr) < len(totalStr) {
		curStr = strings.Repeat(" ", len(totalStr)-len(curStr)) + curStr
	}

	var details []string
	if total != 0 {
		details = append(details, fmt.Sprintf("%3.f%%", float64(cur)/float64(total)*100.0))
	}
	if speed >= 0 {
		details = append(details, fmt.Sprintf("%.2f MB/s", speed/1000000.0))
	}
	detailsStr := strings.Join(details, ", ")
	if detailsStr != "" {
		detailsStr = " (" + detailsStr + ")"
	}

	// Use LogCall to pass non-default calldepth. Otherwise all logs appear as
	// coming from Progress function, which is not very useful.
	logging.Get(ctx).LogCall(logging.Info, 1, "%s: %s/%s MB%s",
		[]interface{}{title, curStr, totalStr, detailsStr},
	)
}

func (a *primitiveActivity) Log(ctx context.Context, level logging.Level, calldepth int, f string, args []interface{}) {
	if a.logger != nil {
		prefix := ""
		if a.group != nil && a.kind != "" {
			prefix = "[" + a.group.activityTitle(a.kind, a.id) + "] "
		}
		a.logger(ctx).LogCall(level, calldepth+1, prefix+f, args)
	}
}

func (a *primitiveActivity) Done(ctx context.Context) {
}


text:
Sistema para agregar e organizar os cuidadores de praças

## Requisitos funcionais ##
- Login social
- Envio de mensagens (notificações) sobre a praça adotada
  - "o cuidador fulano marcou uma ação na praça X dia tal. Venha também!"
- Mapa com a localização das praças
- Entrar para o time de cuidadores de uma determinada praça
- Ver os cuidadores de uma praça
- Um cuidador pode subir fotos de uma ação naquela praça
- Cadastrar as praças
  - Fotografar as praças
  - História da praça
  - Data da última ação feita na praça

## Requisitos não-funcionais ##
- Publicar no heroku ou outro serviço free com suporte a node
- NodeJS + ExpressJS
- O esquema de pesos pra usar ao mensurar prazos é:
  - 1 dia para a atividade mais simples
  - 6 dias para a atividade mais complexa
  - A escala é de 1 a 6


text:
{% extends "flood_mapper/base.html" %}
{% block header %}
    <title>Add Campus</title>
{%  endblock %}

{% load bootstrap_tags %}

{% block navigation-bar %}
    {% include "feti/navigation_bar.html" %}
{%  endblock %}

{% block content %}

            {{ form }}

{%  endblock %}


text:
from eventlet import Timeout
from httplib import urlsplit, HTTPConnection, HTTPSConnection
from json import loads, dumps
import re
from uuid import uuid4

import qork.queue.base as base

MAX_GRACE = 43200

def make_http_request(
        method, url, headers, body, timeout, acceptable_statuses, attempts):
    scheme, netloc, path, query, fragment = urlsplit(url)
    if scheme == 'https':
        Connection = HTTPSConnection
    else:
        Connection = HTTPConnection

    for attempt in xrange(attempts):
        try:
            with Timeout(timeout):
                conn = Connection(netloc)
                conn.request(method, '%s?%s' % (path, query), body, headers)
                resp = conn.getresponse()
                if resp.status in acceptable_statuses or \
                        resp.status // 100 in acceptable_statuses:
                    return resp
        except Exception as e:
            if attempt >= attempts - 1:
                raise e
        except Timeout:
            if attempt >= attempts - 1:
                raise RuntimeError('Request to %s timed out.' % (url))

    raise RuntimeError('HTTP request failed: %s %s' % (method, url))

class RAXConnection(object):
    _auth_token = list()

    def __init__(self, conf):
        self._conf = conf
        self.identity_end_point = conf['identity_end_point'].rstrip('/')
        self.username = conf['username']
        self.api_key = conf['api_key']
        self.end_point = conf['end_point'].rstrip('/')
        self.timeout = int(conf.get('timeout', 10))
        self.attempts = int(conf.get('attempts', 5))

    @property
    def auth_token(self):
        if not self._auth_token:
            self.get_auth_token()
        return self._auth_token[0]

    def create_queue(self, name):
        path = 'queues/%s' % (name)
        self.make_request('PUT', path, {}, '', (2,))
        return RAXQueue(self, name)

    def get_all_queues(self, prefix=None):
        path = 'queues'
        marker = None
        limit = 100

        queues = set()

        while True:
            params = 'limit=%d' % (limit)
            if marker:
                params += '&marker=%s' % (marker)
            this_request = '%s?%s' % (path, params)

            resp = self.make_request('GET', this_request, {}, '', (2,))
            if resp.status == 204:
                break
            data = loads(resp.read())

            if prefix:
                queues.update(
                    [str(x['name']) for x in data['queues'] if
                    x['name'].startswith(prefix)])
            else:
                queues.update([str(x['name']) for x in data['queues']])

            if len(data['queues']) < limit:
                break

            marker = data['queues'][-1]['name']

        return queues

    def get_auth_token(self):
        headers = {
            'Content-Type': 'application/json',
        }
        data = {
            'auth': {
                'RAX-KSKEY:apiKeyCredentials': {
                    'username': self.username,
                    'apiKey': self.api_key,
                }
            }
        }

        body = dumps(data)
        resp = make_http_request(
            'POST', self.identity_end_point, headers, body, self.timeout,
            (2,), 3)

        data = loads(resp.read())
        while self._auth_token:
            self._auth_token.pop()
        self._auth_token.append(data['access']['token']['id'])

    def get_queue_stats(self, name):
        path = 'queues/%s/stats' % (name)
        resp = self.make_request('GET', path, {}, '', (2,))
        return loads(resp.read())

    def make_request( self, method, path, headers, body, acceptable_statuses):
        url = '%s/%s' % (self.end_point, path)
        headers = dict(headers)
        acceptable_statuses = list(acceptable_statuses) + [401,]

        for attempt in xrange(2):
            # TODO: what is a good value for client id?  maybe specify it in
            # the config?
            headers['Client-ID'] = 'e58668fc-26eb-11e3-8270-5b3128d43830'
            headers['X-Auth-Token'] = self.auth_token
            resp = make_http_request(method, url, headers, body, self.timeout,
                acceptable_statuses, self.attempts)

            if resp.status == 401:
                self.get_auth_token()
                continue
            return resp

        raise RuntimeError('Request failed: %s %s' % (method, path))

class RAXMessage(object):
    def __init__(self, data):
        match = re.search('messages/(\w+)', data['href'])
        if not match:
            raise RuntimeError('url does not match expected pattern')
        self.id = match.group(1)
        match = re.search('claim_id=(\w+)', data['href'])
        if match:
            self.claim_id = match.group(1)
        else:
            self.claim_id = None
        self.body = data['body']

    def get_body(self):
        return self.body

class RAXQueue(object):
    def __init__(self, conn, name):
        self._conn = conn
        self.name = name

    # number of unclaimed messages in queue
    def count(self):
        stats = self._conn.get_queue_stats(self.name)
        return stats['messages']['free']

    def delete(self):
        path = 'queues/%s' % (self.name)
        self._conn.make_request('DELETE', path, {}, '', (2,))

    def delete_message(self, message):
        path = 'queues/%s/messages/%s' % (
            self.name, message.id)
        if message.claim_id:
            path += '?claim_id=%s' % (message.claim_id)
        self._conn.make_request('DELETE', path, {}, '', (2,))

    # get/claim next message
    def read(self, vtime):
        path = 'queues/%s/claims?limit=1' % (self.name)
        # TODO: is this value ok for grace?
        # 60 is the minimum value for ttl, grace
        vtime = max(vtime, 60)
        data = {
            'ttl': vtime,
            'grace': MAX_GRACE,
        }
        resp = self._conn.make_request('POST', path, {}, dumps(data), (2,))
        if resp.status == 204:
            return None
        messages = loads(resp.read())
        return RAXMessage(messages[0])

    # get/read all unclaimed messages in queue without claiming them
    def read_messages(self):
        path = 'queues/%s/messages' % (self.name)
        marker = None
        limit = 10

        while True:
            params = 'echo=true&limit=%d' % (limit)
            if marker:
                params += '&marker=%s' % (marker)
            this_request = '%s?%s' % (path, params)

            resp = self._conn.make_request('GET', this_request, {}, '', (2,))
            if resp.status == 204:
                break

            data = loads(resp.read())

            for message in data['messages']:
                yield RAXMessage(message)

            next_link = None
            for link in data['links']:
                if link['rel'] == 'next':
                    next_link = link['href']
            if not next_link:
                break

            match = re.search('marker=(\w+)', next_link)
            if not match:
                raise RuntimeError('url does not match expected pattern')
            marker = match.group(1)

    def write(self, message):
        url = 'queues/%s/messages' % (self.name)
        data = [
            {
                'ttl': base.FOURTEEN_DAYS,
                'body': message,
            }
        ]
        self._conn.make_request('POST', url, {}, dumps(data), (2,))

class QueueReader(base.QueueReader):
    """Reads messages from work queues, respecting priority"""

    def __init__(self, conf):
        super(QueueReader, self).__init__(conf)
        self._conn = RAXConnection(conf)

    def get_all_queues(self):
        """Returns all queues"""
        for queue in sorted(self._conn.get_all_queues(self._global_prefix)):
            yield MessageQueue(self._conf, queue)

    def get_global_queues(self):
        """Returns global queues"""
        for queue in self._conn.get_all_queues():
            yield MessageQueue(self._conf, queue)

    def get_queues(self):
        """Returns read queues in priority order"""
        for prefix in self._read_queues:
            for queue in sorted(self._conn.get_all_queues(prefix)):
                if queue.endswith('_failure'):
                    continue
                yield MessageQueue(self._conf, queue)

class QueueWriter(base.QueueWriter):
    """Writes messages to multiple queues"""

    def send_message(self, queue_name, message):
        if not queue_name in self._queues:
            raise ValueError('Unexpected queue name')

        queue_name = '%s_%s' % (self._global_prefix, queue_name)
        queue = MessageQueue(self._conf, queue_name)
        queue.send_message(message)

class MessageQueue(base.MessageQueue):
    """Work queue, a RAX queue wrapper"""

    # name convention is [queue_name]_[timestamp] or [queue_name]

    def __init__(self, conf, name):
        super(MessageQueue, self).__init__(conf, name)

        conn = RAXConnection(conf)
        self._queue = conn.create_queue(self.name)
        self._vtime = base.get_vtime(conf)

    def delete(self):
        self._queue.delete()

    def delete_message(self, message):
        """Delete RAX message"""
        self._queue.delete_message(message)

    def get_message(self):
        """Returns a message"""
        message = self._queue.read(self._vtime)
        if message:
            return Message(self._conf, self, message)
        return None

    def message_count(self):
        """Returns number of messages in queue"""
        return self._queue.count()

    def read_messages(self):
        """Yields each message in queue once"""
        for message in self._queue.read_messages():
            yield Message(self._conf, self, message)

    def send_failure(self, msg):
        """Puts message in queue's failure queue"""
        queue = MessageQueue(self._conf, self._failure_queue_name)
        queue.send_message(msg)

    def send_restore(self, msg):
        """Puts message from failure queue back in work queue"""
        queue = MessageQueue(self._conf, msg['meta']['queue_name'])
        queue.send_message(msg)

    def send_message(self, msg):
        """Sends message to queue"""
        if type(msg) != dict:
            raise ValueError("Message must be a dict()")

        if not('body' in msg and 'meta' in msg):
            msg = {'meta': {}, 'body': msg}
            msg['meta']['message_id'] = str(uuid4())
            msg['meta']['queue_name'] = self.name
            msg['meta']['timestamp'] = base.timestamp()

        self._queue.write(msg)

class Message(base.Message):
    """Work message, a RAX message wrapper"""

    def delete(self):
        """Deletes message from queue"""
        self._queue.delete_message(self._message)

    def get_body(self):
        return self._message.get_body()


text:
"""Tests for base_task."""

import contextlib

from absl.testing import absltest
from dm_control import composer
from dm_control.composer.observation import observable
from dm_control.composer.observation import updater
from dm_control.rl import control
from dm_robotics.moma import base_task
from dm_robotics.moma import entity_initializer
from dm_robotics.moma import robot
from dm_robotics.moma import scene_initializer
from dm_robotics.moma.effectors import arm_effector as arm_effector_module
from dm_robotics.moma.models.arenas import empty
from dm_robotics.moma.models.end_effectors.robot_hands import robotiq_2f85
from dm_robotics.moma.models.robots.robot_arms import sawyer
from dm_robotics.moma.sensors import robot_arm_sensor
from dm_robotics.moma.sensors import robot_tcp_sensor
import numpy as np

class BaseTaskTest(absltest.TestCase):

  def _build_sample_base_task(self):
    arena = empty.Arena('test_arena')

    arm = sawyer.Sawyer(with_pedestal=False)

    gripper = robotiq_2f85.Robotiq2F85()

    robot.standard_compose(
        arm=arm, gripper=gripper, wrist_ft=None, wrist_cameras=[])

    robot_sensors = [
        robot_arm_sensor.RobotArmSensor(
            arm=arm, name='robot0', have_torque_sensors=True),
        robot_tcp_sensor.RobotTCPSensor(gripper=gripper, name='robot0'),
    ]

    arm_effector = arm_effector_module.ArmEffector(
        arm=arm, action_range_override=None, robot_name='robot0')

    rbt = robot.StandardRobot(
        arm=arm,
        arm_base_site_name='pedestal_attachment',
        gripper=gripper,
        wrist_ft=None,
        wrist_cameras=[],
        robot_sensors=robot_sensors,
        arm_effector=arm_effector,
        gripper_effector=None,
        name='robot0')

    arena.attach(arm)

    task = base_task.BaseTask(
        task_name='test',
        arena=arena,
        robots=[rbt],
        props=[],
        extra_sensors=[],
        extra_effectors=[],
        scene_initializer=scene_initializer.CompositeSceneInitializer([]),
        episode_initializer=entity_initializer.TaskEntitiesInitializer([]),
        control_timestep=0.1)

    return task

  def test_observables(self):
    """Test that the task observables includes only sensor observables."""

    task = self._build_sample_base_task()
    task_obs = set(task.observables)

    robot_sensor_obs = []
    for s in task.robots[0].sensors:
      robot_sensor_obs.extend(list(s.observables))
    robot_sensor_obs = set(robot_sensor_obs)

    self.assertEmpty(task_obs ^ robot_sensor_obs)

  def test_observable_types(self):
    """Test that the task observables includes only sensor observables."""

    task = self._build_sample_base_task()
    env = composer.Environment(task, strip_singleton_obs_buffer_dim=True)
    obs_spec = env.observation_spec()

    acceptable_types = set(
        [np.dtype(np.uint8),
         np.dtype(np.int64),
         np.dtype(np.float32)])

    for spec in obs_spec.values():
      self.assertIn(np.dtype(spec.dtype), acceptable_types)

class FakePhysics(control.Physics):
  """A fake Physics class for unit testing observations."""

  def __init__(self):
    self._step_counter = 0
    self._observables = {}

  def step(self, sub_steps=1):
    self._step_counter += 1

  @property
  def observables(self):
    return self._observables

  def time(self):
    return self._step_counter

  def timestep(self):
    return 1.0

  def set_control(self, ctrl):
    pass

  def reset(self):
    self._step_counter = 0

  def after_reset(self):
    pass

  @contextlib.contextmanager
  def suppress_physics_errors(self):
    yield

class CastObservationsTest(absltest.TestCase):

  def testCastAggregatedObservable(self):
    physics = FakePhysics()
    physics.observables['raw_value'] = observable.Generic(
        raw_observation_callable=lambda unused: np.float64(physics.time()),
        update_interval=1,
        buffer_size=2,
        aggregator=lambda arr: np.asarray([arr[0], arr[1], arr[0] + arr[1]]),
        corruptor=lambda value, random_state: value * 10.0)
    physics.observables['cast_value'] = base_task.CastObservable(
        physics.observables['raw_value'])

    for obs in physics.observables.values():
      obs.enabled = True
    physics.reset()

    physics_steps_per_control_step = 2
    observation_updater = updater.Updater(
        physics.observables,
        physics_steps_per_control_step,
        strip_singleton_buffer_dim=True)
    observation_updater.reset(physics=physics, random_state=None)

    raw_values, cast_values = [], []
    for unused_step in range(0, 3):
      observation_updater.prepare_for_next_control_step()
      for _ in range(physics_steps_per_control_step):
        physics.step()
        observation_updater.update()

      observation = observation_updater.get_observation()
      print(observation)

      raw_values.append(observation['raw_value'])
      cast_values.append(observation['cast_value'])

    np.testing.assert_equal(raw_values[0], np.asarray([10.0, 20.0, 30.0]))
    np.testing.assert_equal(cast_values[0], np.asarray([10.0, 20.0, 30.0]))
    np.testing.assert_equal(raw_values[1], np.asarray([30.0, 40.0, 70.0]))
    np.testing.assert_equal(cast_values[1], np.asarray([30.0, 40.0, 70.0]))
    np.testing.assert_equal(raw_values[2], np.asarray([50.0, 60.0, 110.0]))
    np.testing.assert_equal(cast_values[2], np.asarray([50.0, 60.0, 110.0]))
    self.assertEqual(raw_values[0].dtype, np.float64)
    self.assertEqual(cast_values[0].dtype, np.float32)

if __name__ == '__main__':
  absltest.main()


text:
        <ng-container *ngIf="plagiarismComparison">
            <jhi-modeling-submission-viewer *ngIf="isModelingExercise" [exercise]="exercise" [plagiarismSubmission]="getModelingSubmissionA()"></jhi-modeling-submission-viewer>

            <jhi-text-submission-viewer
                *ngIf="isProgrammingOrTextExercise"
                [exercise]="exercise"
                [matches]="matchesA"
                [plagiarismSubmission]="getTextSubmissionA()"
            ></jhi-text-submission-viewer>
        </ng-container>

        <ng-container *ngIf="plagiarismComparison">
            <jhi-modeling-submission-viewer *ngIf="isModelingExercise" [exercise]="exercise" [plagiarismSubmission]="getModelingSubmissionB()"></jhi-modeling-submission-viewer>

            <jhi-text-submission-viewer
                *ngIf="isProgrammingOrTextExercise"
                [exercise]="exercise"
                [matches]="matchesB"
                [plagiarismSubmission]="getTextSubmissionB()"
            ></jhi-text-submission-viewer>
        </ng-container>


text:
using System;
using System.Threading.Tasks;
using work.bacome.async;
using work.bacome.imapclient.support;
using work.bacome.trace;

namespace work.bacome.imapclient
{
    public partial class cIMAPClient
    {
        private partial class cSession
        {
            private static readonly cCommandPart kStoreCommandPartStoreSpace = new cTextCommandPart("STORE ");

            private async Task ZStoreAsync(cMethodControl pMC, cStoreFeedback pFeedback, eStoreOperation pOperation, cStorableFlags pFlags, ulong? pIfUnchangedSinceModSeq, cTrace.cContext pParentContext)
            {
                var lContext = pParentContext.NewMethod(nameof(cSession), nameof(ZStoreAsync), pMC, pFeedback, pOperation, pFlags, pIfUnchangedSinceModSeq);

                // no validation ... all the parameters have been validated already by the cSession by the time we get here

                using (var lBuilder = new cCommandDetailsBuilder())
                {
                    lBuilder.Add(await mSelectExclusiveAccess.GetBlockAsync(pMC, lContext).ConfigureAwait(false)); // block select

                    cSelectedMailbox lSelectedMailbox = mMailboxCache.CheckInSelectedMailbox(pFeedback);
                    if (!lSelectedMailbox.SelectedForUpdate) throw new InvalidOperationException(kInvalidOperationExceptionMessage.NotSelectedForUpdate);

                    lBuilder.Add(await mPipeline.GetIdleBlockTokenAsync(pMC, lContext).ConfigureAwait(false)); // stop the pipeline from iding (idle is msnunsafe)
                    lBuilder.Add(await mMSNUnsafeBlock.GetTokenAsync(pMC, lContext).ConfigureAwait(false)); // wait until all commands that are msnunsafe complete, block all commands that are msnunsafe

                    // uidvalidity must be captured before the handles are resolved
                    lBuilder.AddUIDValidity(lSelectedMailbox.MessageCache.UIDValidity);

                    // collector
                    cStoreFeedbackCollector lFeedbackCollector = new cStoreFeedbackCollector();

                    // resolve the handles to MSNs
                    foreach (var lItem in pFeedback)
                    {
                        var lMSN = lSelectedMailbox.GetMSN(lItem.MessageHandle);
                        if (lMSN != 0) lFeedbackCollector.Add(lMSN, lItem);
                    }

                    // if no handles were resolved, we are done
                    if (lFeedbackCollector.Count == 0) return;

                    // build the command
                    lBuilder.Add(kStoreCommandPartStoreSpace, new cTextCommandPart(cSequenceSet.FromUInts(lFeedbackCollector.UInts)), cCommandPart.Space);
                    if (pIfUnchangedSinceModSeq != null) lBuilder.Add(kStoreCommandPartLParenUnchangedSinceSpace, new cTextCommandPart(pIfUnchangedSinceModSeq.Value), kStoreCommandPartRParenSpace);
                    lBuilder.Add(pOperation, pFlags);

                    // add the hook
                    var lHook = new cCommandHookStore(lFeedbackCollector, null, lSelectedMailbox);
                    lBuilder.Add(lHook);

                    // submit the command
                    var lResult = await mPipeline.ExecuteAsync(pMC, lBuilder.EmitCommandDetails(), lContext).ConfigureAwait(false);
                    // NOTE: updates may have been done on both OK and NO responses (see rfc 2180/ 7162) so we can't throw on a NO for this command ... NO indicates that some (or all) of the messages have pending deletes

                    // throw on a bad
                    if (lResult.ResultType == eCommandResultType.bad)
                    {
                        fCapabilities lTryIgnoring;
                        if (pIfUnchangedSinceModSeq == null) lTryIgnoring = 0;
                        else lTryIgnoring = fCapabilities.condstore;
                        throw new cProtocolErrorException(lResult, lTryIgnoring, lContext);
                    }

                    if (lResult.ResultType == eCommandResultType.ok) lContext.TraceInformation("store success");
                    else lContext.TraceInformation("store possible partial success");
                }
            }
        }
    }
}


text:
import { act, renderHook } from "@testing-library/react-hooks";

import { useVerticalDividerHeight } from "../useVerticalDividerHeight";

describe("useVerticalDivider", () => {
  it("should update the height value after the ref is called with an element", () => {
    const div = document.createElement("div");
    const parentDiv = document.createElement("div");
    parentDiv.appendChild(div);
    Object.defineProperty(parentDiv, "offsetHeight", { value: 100 });

    const { result } = renderHook(() =>
      useVerticalDividerHeight({ maxHeight: 1 })
    );
    expect(result.current.style?.height).toBeUndefined();

    act(() => result.current.ref(div));
    expect(result.current.style?.height).toBe(100);
  });

  it("should use the maxHeight as a multiplier if it is less than 1", () => {
    const div = document.createElement("div");
    const parentDiv = document.createElement("div");
    parentDiv.appendChild(div);
    Object.defineProperty(parentDiv, "offsetHeight", { value: 100 });

    const { result } = renderHook(() =>
      useVerticalDividerHeight({ maxHeight: 0.6 })
    );
    expect(result.current.style?.height).toBeUndefined();

    act(() => result.current.ref(div));
    expect(result.current.style?.height).toBe(60);
  });

  it("should use the maxHeight as a pixel value if it is greater than 1", () => {
    const div = document.createElement("div");
    const parentDiv = document.createElement("div");
    parentDiv.appendChild(div);
    Object.defineProperty(parentDiv, "offsetHeight", {
      value: 100,
      writable: true,
    });

    const { result } = renderHook(() =>
      useVerticalDividerHeight({ maxHeight: 80 })
    );
    expect(result.current.style?.height).toBeUndefined();

    act(() => result.current.ref(div));
    expect(result.current.style?.height).toBe(80);

    Object.defineProperty(parentDiv, "offsetHeight", {
      value: 40,
      writable: true,
    });
    act(() => result.current.ref(div));
    expect(result.current.style?.height).toBe(40);
  });
});


text:
struct FaviconURL;
class RenderViewHost;

namespace IPC {
class Message;
}

namespace prerender {

class PrerenderContents;

// Observer for RenderViewHost messages.
class PrerenderRenderViewHostObserver : public content::RenderViewHostObserver {
 public:
  PrerenderRenderViewHostObserver(PrerenderContents* prerender_contents,
                                  RenderViewHost* render_view_host);

  virtual void RenderViewHostDestroyed(RenderViewHost* rvh) OVERRIDE;

  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
  virtual bool Send(IPC::Message* message) OVERRIDE;

  void set_prerender_contents(PrerenderContents* prerender_contents) {
    prerender_contents_ = prerender_contents;
  }

 private:
  // Message handlers.
  void OnUpdateFaviconURL(int32 page_id, const std::vector<FaviconURL>& urls);
  void OnMaybeCancelPrerenderForHTML5Media();
  void OnCancelPrerenderForPrinting();

  // The associated prerender contents.
  PrerenderContents* prerender_contents_;
};

}  // namespace prerender

#endif  // CHROME_BROWSER_PRERENDER_PRERENDER_RENDER_VIEW_HOST_OBSERVER_H_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Karstenia 24(1): 26 (1984)

#### Original name
Phellinus pilatii Cerný

### Remarks
null


text:
(function() {
    'use strict';

    /**
     * app.config
     *
     * The module provides application configuration settings to the application.
     */
    angular.module('app.config', []);

})();


text:
package org.eclipse.cft.server.tests.core;

import org.eclipse.cft.server.core.internal.CloudFoundryServer;
import org.eclipse.cft.server.core.internal.ServerCredentialsStore;
import org.eclipse.cft.server.ui.internal.ServerDescriptor;
import org.eclipse.cft.server.ui.internal.ServerHandler;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.IServerWorkingCopy;
import org.eclipse.wst.server.core.internal.ServerWorkingCopy;

import junit.framework.TestCase;

/**
 * @author Steffen Pingel
 */
public class CloudFoundryServerTest extends TestCase {

	private CloudFoundryServer cloudFoundryServer;

	private IServer server;

	private IServerWorkingCopy serverWC;

	// there is no longer just one default url for a server type
	// public void testGetServerIdDefaultUrl() throws CoreException {
	// assertEquals(null, CloudFoundryServer.getServerId());
	//
	// CloudFoundryServer.setUrl(null);
	// assertEquals("null@http://api.cloudfoundry.com",
	// CloudFoundryServer.getServerId());
	// }

	public void testGetServerId() throws CoreException {
		// assertEquals(null, CloudFoundryServer.getServerId());

		cloudFoundryServer.setUsername("user");
		assertEquals("user@http://api.cloudfoundry.com", cloudFoundryServer.getServerId());

		cloudFoundryServer.setPassword("pass");
		assertEquals("user@http://api.cloudfoundry.com", cloudFoundryServer.getServerId());

		cloudFoundryServer.setUrl("http://url");
		assertEquals("user@http://url", cloudFoundryServer.getServerId());
	}

	public void testGetPasswordLegacy() throws CoreException {
		// create legacy password attribute
		((ServerWorkingCopy) serverWC).setAttribute("org.eclipse.cft.password", "pwd");
		serverWC.save(true, null);

		// assertEquals(null, CloudFoundryServer.getServerId());

		// create new server instance
		serverWC = server.createWorkingCopy();
		cloudFoundryServer = (CloudFoundryServer) serverWC.loadAdapter(CloudFoundryServer.class, null);

		assertEquals("pwd", cloudFoundryServer.getPassword());

		ServerCredentialsStore store = cloudFoundryServer.getCredentialsStore();
		assertEquals(null, store.getPassword());

		serverWC.save(true, null);
		assertEquals("Unexpected migration of password to secure store although it was not changed", null,
				store.getPassword());
	}

	public void testSetPasswordMigrateLegacy() throws CoreException {
		// create legacy password attribute
		((ServerWorkingCopy) serverWC).setAttribute("org.eclipse.cft.password", "pwd");
		serverWC.save(true, null);

		// create new server instance
		serverWC = server.createWorkingCopy();
		cloudFoundryServer = (CloudFoundryServer) serverWC.loadAdapter(CloudFoundryServer.class, null);

		cloudFoundryServer.setPassword("newpwd");
		assertEquals("newpwd", cloudFoundryServer.getPassword());

		serverWC.save(true, null);
		ServerCredentialsStore store = cloudFoundryServer.getCredentialsStore();
		assertEquals("newpwd", store.getPassword());
	}

	public void testSetPasswordMigrateChangePasswordOnly() throws CoreException {
		// create legacy password attribute
		((ServerWorkingCopy) serverWC).setAttribute("org.eclipse.cft.url", "http://url");
		((ServerWorkingCopy) serverWC).setAttribute("org.eclipse.cft.username", "user");
		((ServerWorkingCopy) serverWC).setAttribute("org.eclipse.cft.password", "pwd");
		serverWC.save(true, null);

		// create new server instance
		serverWC = server.createWorkingCopy();
		cloudFoundryServer = (CloudFoundryServer) serverWC.loadAdapter(CloudFoundryServer.class, null);
		cloudFoundryServer.setPassword("newpwd");
		assertEquals("newpwd", cloudFoundryServer.getPassword());
		assertEquals("user@http://url", cloudFoundryServer.getServerId());

		serverWC.save(true, null);
		cloudFoundryServer = (CloudFoundryServer) server.loadAdapter(CloudFoundryServer.class, null);
		assertEquals("user@http://url", cloudFoundryServer.getServerId());
		assertEquals("newpwd", cloudFoundryServer.getPassword());
	}

	// FIXNS: Commented out for now due to STS-3280 which is an issue in Eclipse
	// 3.7 and higher. However, CF plugin has been installed in 3.7 and 4.2
	// without
	// issues
	// and passing functional verification tests, so this unit test case is not
	// a show stopper.

	// public void testSetPasswordMigrateUpdatesClient() throws CoreException {
	// // create legacy password attribute
	// ((ServerWorkingCopy)
	// serverWC).setAttribute("org.eclipse.cft.password", "pwd");
	// ((ServerWorkingCopy)
	// serverWC).setAttribute("org.eclipse.cft.username", "user");
	// // ((ServerWorkingCopy)
	// // serverWC).setAttribute("org.eclipse.cft.url", "url");
	// serverWC.save(true, null);
	//
	// assertEquals("user", cloudFoundryServer.getUsername());
	// assertEquals("pwd", cloudFoundryServer.getPassword());
	// CloudFoundryServerBehaviour serverBehaviour =
	// (CloudFoundryServerBehaviour) serverWC.loadAdapter(
	// CloudFoundryServerBehaviour.class, null);
	// CloudFoundryOperations client = serverBehaviour.getClient(null);
	//
	// // create new server instance
	// serverWC = server.createWorkingCopy();
	// cloudFoundryServer.setPassword("newpwd");
	// cloudFoundryServer.setUsername("newuser");
	// cloudFoundryServer.setUrl("http://api.cloudfoundry.com");
	// serverWC.save(true, null);
	//
	// // verify that old instance is updated
	// assertEquals("newuser", cloudFoundryServer.getUsername());
	// assertEquals("newpwd", cloudFoundryServer.getPassword());
	// assertNotSame("Expected new client instance due to password change",
	// client, serverBehaviour.getClient(null));
	// }

	public void testSaveCredentials() throws CoreException {
		cloudFoundryServer.setUsername("user");
		cloudFoundryServer.setPassword("pass");
		assertEquals("user", cloudFoundryServer.getUsername());
		assertEquals("pass", cloudFoundryServer.getPassword());

		serverWC.save(true, null);
		assertEquals("user", cloudFoundryServer.getUsername());
		assertEquals("pass", cloudFoundryServer.getPassword());

		cloudFoundryServer = (CloudFoundryServer) server.loadAdapter(CloudFoundryServer.class, null);
		assertEquals("user", cloudFoundryServer.getUsername());
		assertEquals("pass", cloudFoundryServer.getPassword());
	}

	@Override
	protected void setUp() throws Exception {
		ServerDescriptor descriptor = new ServerDescriptor("server") {
			{
				setRuntimeTypeId("org.cloudfoundry.cloudfoundryserver.test.runtime.10");
				setServerTypeId("org.cloudfoundry.cloudfoundryserver.test.10");
				setRuntimeName("Cloud Foundry Test Runtime");
				setServerName("Cloud Foundry Test Server");
				setForceCreateRuntime(true);
			}
		};

		ServerHandler handler = new ServerHandler(descriptor);
		server = handler.createServer(new NullProgressMonitor(), ServerHandler.ALWAYS_OVERWRITE);
		serverWC = server.createWorkingCopy();
		cloudFoundryServer = (CloudFoundryServer) serverWC.loadAdapter(CloudFoundryServer.class, null);

		// there is no longer a singer default URL for a server type
		cloudFoundryServer.setUrl("http://api.cloudfoundry.com");
	}

}


text:
<?php

namespace Omnipay\Klarna\Message;

use Omnipay\Tests\TestCase;
use Omnipay\Klarna\Message\InvoiceAuthorizeRequest;
use Subscribo\Omnipay\Shared\CreditCard;

class InvoiceAuthorizeRequestTest extends TestCase
{
    public function setUp()
    {
        $this->merchantId = uniqid();
        $this->sharedSecret = uniqid();
        $this->card = [
            'gender' => CreditCard::GENDER_MALE,
            'birthday' => '1960-04-14',
            'firstName' => 'Testperson-at',
            'lastName' => 'Approved',
            'address1' => 'Klarna-Straße 1/2/3',
            'address2' => null,
            'postCode' => '8071',
            'city'     => 'Hausmannstätten',
            'country'  => 'at',
            'phone'    => '0676 2600000',
            'email'    => 'youremail@email.com',
        ];
        $this->deniedCard = [
            'gender' => 'Female',
            'birthday' => '1980-04-14',
            'firstName' => 'Testperson-at',
            'lastName' => 'Denied',
            'address1' => 'Klarna-Straße 1/2/3',
            'address2' => null,
            'postCode' => '8070',
            'city'     => 'Hausmannstätten',
            'country'  => 'at',
            'phone'    => '0676 2800000',
            'email'    => 'youremail@email.com',
        ];
        $this->shoppingCart = [
            [
                'name' => 'Some Article',
                'identifier' => 'A001',
                'price' => '2.00',
                'description' => 'Just article for testing',
                'quantity' => 9,
                'taxPercent' => '20',
            ],
            [
                'name' => 'Another Article',
                'identifier' => 'A002',
                'price' => '10.00',
                'quantity' => 1,
                'taxPercent' => '20',
                'description' => 'An article with different VAT set up',
                'flags' => 0,
            ],
            [
                'name' => 'Discounted Article',
                'identifier' => 'A003',
                'price' => '10.00',
                'description' => 'Some discounted article for testing',
                'quantity' => 1,
                'discountPercent' => '10',
                'taxPercent' => '20',
            ],
            [
                'name' => 'Shipping Fee',
                'identifier' => 'SHIPPING',
                'price' => '5.00',
                'quantity' => 3,
                'description' => 'Testing shipping fee',
                'flags' => 8,
            ]
        ];
    }

    public function testGetData()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $this->assertSame($request, $request->setMerchantId($this->merchantId));
        $this->assertSame($request, $request->setSharedSecret($this->sharedSecret));
        $this->assertSame($request, $request->setLocale('de_at'));
        $this->assertSame($request, $request->setTestMode(true));
        $this->assertSame($request, $request->setClientIp('192.0.2.1'));
        $this->assertSame($request, $request->setCard($this->card));
        $this->assertSame($request, $request->setItems($this->shoppingCart));

        $data = $request->getData();

        $this->assertSame('de', $request->getLanguage());
        $this->assertSame('AT', $request->getCountry());
        $this->assertSame('EUR', $request->getCurrency());
        $this->assertSame('192.0.2.1', $request->getClientIp());
        $this->assertTrue($request->getTestMode());
        $this->assertEmpty($request->getAmount());
        $this->assertSame(0, $request->getAmountInteger());
        $this->assertSame('54.00', $request->calculateAmount());
        $this->assertNotEmpty($request->getItems());
        $this->assertInstanceOf('Subscribo\\Omnipay\\Shared\\CreditCard', $request->getCard());
        $this->assertSame($this->merchantId, $request->getMerchantId());
        $this->assertSame($this->sharedSecret, $request->getSharedSecret());

        $this->assertTrue($data['testMode']);
        $this->assertNotEmpty($data['articles']);
        $this->assertInstanceOf('Subscribo\\Omnipay\\Shared\\CreditCard', $data['card']);
        $this->assertSame('m', $data['gender']);
        $this->assertSame(-1, $data['amount']);
        $this->assertSame('de', $data['language']);
        $this->assertSame('AT', $data['country']);
        $this->assertSame('EUR', $data['currency']);
        $this->assertSame('192.0.2.1', $data['clientIp']);
        $this->assertSame('14041960', $data['pno']);
        $this->assertSame($this->merchantId, $data['merchantId']);
        $this->assertSame($this->sharedSecret, $data['sharedSecret']);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSendWrongData()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $request->setTestMode(true);
        $request->sendData(null);
    }

    public function testGetWidget()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $request->setMerchantId($this->merchantId);
        $request->setSharedSecret($this->sharedSecret);
        $request->setLocale('de_at');
        $request->setTestMode(true);
        $request->setItems($this->shoppingCart);

        $widget = $request->getWidget();

        $this->assertInstanceOf('Omnipay\\Klarna\\Widget\\InvoiceWidget', $widget);
        $this->assertSame('54.00', $widget->getPrice());
        $this->assertSame($this->merchantId, $widget->getMerchantId());
        $this->assertSame('de', $widget->getLanguage());
        $this->assertSame('AT', $widget->getCountry());
    }

    /**
     * @expectedException \Omnipay\Common\Exception\InvalidRequestException
     */
    public function testMissingNationalIdentificationNumber()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $request->setMerchantId($this->merchantId);
        $request->setSharedSecret($this->sharedSecret);
        $request->setLocale('fi_fi');
        $request->setTestMode(true);
        $request->setClientIp('192.0.2.1');
        $request->setCard($this->card);
        $data = $request->getData();
    }

    /**
     * @expectedException \Omnipay\Common\Exception\InvalidRequestException
     * @expectedExceptionMessage Gender
     */
    public function testMissingGender()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $request->setMerchantId($this->merchantId);
        $request->setSharedSecret($this->sharedSecret);
        $request->setLocale('de_at');
        $request->setTestMode(true);
        $request->setClientIp('192.0.2.1');
        $card = $this->card;
        unset($card['gender']);
        $request->setCard($card);
        $data = $request->getData();
    }

    /**
     * @expectedException \Omnipay\Common\Exception\InvalidRequestException
     * @expectedExceptionMessage Birthday
     */
    public function testMissingBirthDate()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $request->setMerchantId($this->merchantId);
        $request->setSharedSecret($this->sharedSecret);
        $request->setLocale('de_at');
        $request->setTestMode(true);
        $request->setClientIp('192.0.2.1');
        $card = $this->card;
        unset($card['birthday']);
        $request->setCard($card);
        $data = $request->getData();
    }

    public function testPno()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $request->setMerchantId($this->merchantId);
        $request->setSharedSecret($this->sharedSecret);
        $request->setLocale('sv_se');
        $request->setTestMode(true);
        $request->setClientIp('192.0.2.1');
        $card = [
            'gender' => 'Male',
            'birthday' => '1960-04-14',
            'firstName' => 'Testperson-se',
            'lastName' => 'Approved',
            'address1' => 'Stårgatan 1',
            'address2' => null,
            'postCode' => '12345',
            'city'     => 'Ankeborg',
            'country'  => 'se',
            'phone'    => '0765260000',
            'email'    => 'youremail@email.com',
            'nationalIdentificationNumber' => '410321-9202'
        ];
        $request->setCard($card);
        $data = $request->getData();
        $this->assertSame('410321-9202', $data['pno']);
        $this->assertNull($data['gender']);
    }

    public function testSetters()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $this->assertNull($request->getOrderId1());
        $this->assertNull($request->getOrderId2());
        $this->assertNull($request->getTransactionId());
        $this->assertNull($request->getLanguage());
        $this->assertNull($request->getCountry());
        $this->assertNull($request->getCurrency());
        $this->assertNull($request->getClientIp());
        $this->assertNull($request->getAmount());
        $this->assertSame(0, $request->getAmountInteger());
        $this->assertNull($request->getCard());
        $this->assertNull($request->getItems());
        $this->assertNull($request->getMerchantId());
        $this->assertNull($request->getSharedSecret());

        $this->assertNull($request->getDescription());
        $this->assertNull($request->getReturnUrl());
        $this->assertNull($request->getCancelUrl());
        $this->assertNull($request->getCardReference());
        $this->assertNull($request->getTransactionReference());
        $this->assertNull($request->getToken());

        $this->assertNull($request->getTestMode());
        $this->assertSame($request, $request->setTestMode(false));
        $this->assertFalse($request->getTestMode());
        $this->assertSame($request, $request->setTestMode(true));
        $this->assertTrue($request->getTestMode());

        $orderId1 = uniqid();
        $orderId2 = uniqid().'second';

        $this->assertSame($request, $request->setOrderId1($orderId1));
        $this->assertSame($request, $request->setOrderId2($orderId2));
        $this->assertSame($request, $request->setLanguage('de'));
        $this->assertSame($request, $request->setCountry('AT'));
        $this->assertSame($request, $request->setCurrency('EUR'));
        $this->assertSame($orderId1, $request->getOrderId1());
        $this->assertSame($orderId2, $request->getOrderId2());
        $this->assertSame($orderId1, $request->getTransactionId());
        $this->assertSame('de', $request->getLanguage());
        $this->assertSame('AT', $request->getCountry());
        $this->assertSame('EUR', $request->getCurrency());

        $transactionId = uniqid().'transaction';

        $this->assertSame($request, $request->setTransactionId($transactionId));
        $this->assertSame($transactionId, $request->getOrderId1());
        $this->assertSame($orderId2, $request->getOrderId2());
        $this->assertSame($transactionId, $request->getTransactionId());
    }

    public function testInitialize()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $orderId1 = uniqid();
        $orderId2 = uniqid();
        $data = [
            'testMode' => true,
            'merchantId' => $this->merchantId,
            'sharedSecret' => $this->sharedSecret,
            'locale' => 'sv_se',
            'orderId1' => $orderId1,
            'orderId2' => $orderId2,
            'clientIp' => '192.0.2.1',
            'card' => [
                'nationalIdentificationNumber' => '410321-9202'
            ]
        ];
        $this->assertSame($request, $request->initialize($data));

        $this->assertSame('sv', $request->getLanguage());
        $this->assertSame('SE', $request->getCountry());
        $this->assertSame('SEK', $request->getCurrency());
        $this->assertSame('192.0.2.1', $request->getClientIp());
        $this->assertTrue($request->getTestMode());
        $this->assertEmpty($request->getAmount());
        $this->assertSame(0, $request->getAmountInteger());
        $this->assertSame('0.00', $request->calculateAmount());
        $this->assertInstanceOf('Subscribo\\Omnipay\\Shared\\CreditCard', $request->getCard());
        $this->assertSame($this->merchantId, $request->getMerchantId());
        $this->assertSame($this->sharedSecret, $request->getSharedSecret());

        $data = $request->getData();

        $this->assertTrue($data['testMode']);
        $this->assertSame($this->merchantId, $data['merchantId']);
        $this->assertSame($this->sharedSecret, $data['sharedSecret']);
        $this->assertNull($data['gender']);
        $this->assertSame(-1, $data['amount']);
        $this->assertSame('sv', $data['language']);
        $this->assertSame('SE', $data['country']);
        $this->assertSame('SEK', $data['currency']);
        $this->assertSame('192.0.2.1', $data['clientIp']);
        $this->assertSame('410321-9202', $data['pno']);
        $this->assertSame('0.00', $request->calculateAmount());
    }

    /**
     * @expectedException \Omnipay\Common\Exception\InvalidRequestException
     * @expectedExceptionMessage The merchantId parameter is required
     */
    public function testGetDataEmpty()
    {
        $request = new InvoiceAuthorizeRequest($this->getHttpClient(), $this->getHttpRequest());
        $request->setTestMode(true);
        $data = $request->getData();
    }
}


text:
void Config(){
    // 7-DEC-2000 09:00
    // Switch on Transition Radiation simulation. 6/12/00 18:00
    // iZDC=1  7/12/00 09:00
    // ThetaRange is (0., 180.). It was (0.28,179.72) 7/12/00 09:00
    // Theta range given through pseudorapidity limits 22/6/2001

    // Set Random Number seed
    // gRandom->SetSeed(12345);

    // libraries required by geant321
    gSystem->Load("libgeant321");

    new     TGeant3("C++ Interface to Geant3");

    if (!gSystem->Getenv("CONFIG_FILE"))
    {
        TFile  *rootfile = new TFile("galice.root", "recreate");

        rootfile->SetCompressionLevel(2);
    }

    TGeant3 *geant3 = (TGeant3 *) gMC;

    //
    // Set External decayer
    AliDecayer *decayer = new AliDecayerPythia();

    decayer->SetForceDecay(kAll);
    decayer->Init();
    gMC->SetExternalDecayer(decayer);
    //
    //
    //=======================================================================
    // ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
    geant3->SetTRIG(1);         //Number of events to be processed
    geant3->SetSWIT(4, 10);
    geant3->SetDEBU(0, 0, 1);
    //geant3->SetSWIT(2,2);
    geant3->SetDCAY(1);
    geant3->SetPAIR(1);
    geant3->SetCOMP(1);
    geant3->SetPHOT(1);
    geant3->SetPFIS(0);
    geant3->SetDRAY(0);
    geant3->SetANNI(1);
    geant3->SetBREM(1);
    geant3->SetMUNU(1);
    geant3->SetCKOV(1);
    geant3->SetHADR(1);         //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3)
    geant3->SetLOSS(2);
    geant3->SetMULS(1);
    geant3->SetRAYL(1);
    geant3->SetAUTO(1);         //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0)
    geant3->SetABAN(0);         //Restore 3.16 behaviour for abandoned tracks
    geant3->SetOPTI(2);         //Select optimisation level for GEANT geometry searches (0,1,2)
    geant3->SetERAN(5.e-7);

    Float_t cut = 1.e-3;        // 1MeV cut by default
    Float_t tofmax = 1.e10;

    //             GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX
    geant3->SetCUTS(cut, cut, cut, cut, cut, cut, cut, cut, cut, cut,
                    tofmax);
    //
    //=======================================================================
    // ************* STEERING parameters FOR ALICE SIMULATION **************
    // --- Specify event type to be tracked through the ALICE setup
    // --- All positions are in cm, angles in degrees, and P and E in GeV
    if (gSystem->Getenv("CONFIG_NPARTICLES")){
        int     nParticles = atoi(gSystem->Getenv("CONFIG_NPARTICLES"));
    }else{
        int     nParticles = 2;
    } // end if
//*********************************************
// Example for Fixed Particle Gun
//*********************************************
     AliGenFixed *gener = new AliGenFixed(nParticles);
     gener->SetMomentum(50);
     gener->SetPhi(180.);
     gener->SetTheta(95.);
     gener->SetOrigin(0,0,0);          //vertex position
     gener->SetPart(kMuonMinus);
    gener->Init();
    //
    // Activate this line if you want the vertex smearing to happen
    // track by track
    //
    //gener->SetVertexSmear(perTrack);

    gAlice->SetField(-999, 2);  //Specify maximum magnetic field in Tesla (neg. ==> default field)

    Int_t   iABSO  = 1;
    Int_t   iDIPO  = 1;
    Int_t   iFMD   = 1;
    Int_t   iFRAME = 1;
    Int_t   iHALL  = 1;
    Int_t   iITS   = 1;
    Int_t   iMAG   = 1;
    Int_t   iMUON  = 1;
    Int_t   iPHOS  = 1;
    Int_t   iPIPE  = 1;
    Int_t   iPMD   = 1;
    Int_t   iRICH  = 1;
    Int_t   iSHIL  = 1;
    Int_t   iT0 = 1;
    Int_t   iTOF   = 1;
    Int_t   iTPC   = 1;
    Int_t   iTRD   = 1;
    Int_t   iZDC   = 1;
    Int_t   iEMCAL = 1;

    //=================== Alice BODY parameters =============================
    AliBODY *BODY = new AliBODY("BODY", "Alice envelop");

    if (iMAG){
        //=================== MAG parameters ============================
        // --- Start with Magnet since detector layouts may be depending ---
        // --- on the selected Magnet dimensions ---
        AliMAG *MAG = new AliMAG("MAG", "Magnet");
    }
    if (iABSO){
        //=================== ABSO parameters ============================
        AliABSO *ABSO = new AliABSOv0("ABSO", "Muon Absorber");
    }
    if (iDIPO){
        //=================== DIPO parameters ============================
        AliDIPO *DIPO = new AliDIPOv2("DIPO", "Dipole version 2");
    }
    if (iHALL){
        //=================== HALL parameters ============================
        AliHALL *HALL = new AliHALL("HALL", "Alice Hall");
    }
    if (iFRAME){
        //=================== FRAME parameters ============================
        AliFRAME *FRAME = new AliFRAMEv2("FRAME", "Space Frame");
    }
    if (iSHIL){
        //=================== SHIL parameters ============================
        AliSHIL *SHIL = new AliSHILvF("SHIL", "Shielding");
    }
    if (iPIPE){
        //=================== PIPE parameters ============================
        AliPIPE *PIPE = new AliPIPEv0("PIPE", "Beam Pipe");
    }
    if(iITS) {
	//=================== ITS parameters ============================
	//
	// As the innermost detector in ALICE, the Inner Tracking System
	// "impacts" on almost all other detectors. This involves the fact
	// that the ITS geometry still has several options to be followed
	//in parallel in order to determine the best set-up which minimizes
	// the induced background. All the geometries available to date are
	// described in the following. Read carefully the comments and use
	// the default version (the only one uncommented) unless you are making
	// comparisons and you know what you are doing. In this case just
	// uncomment the ITS geometry you want to use and run Aliroot.
	// Detailed geometries:
	AliITSvPPRasymm *ITS  = new AliITSvPPRasymm("ITS","New ITS PPR detailed version with asymmetric services");
	ITS->SetMinorVersion(2); // don't touch this parameter if you're not an ITS developer
	ITS->SetReadDet(kFALSE); // don't touch this parameter if you're not an ITS developer
	ITS->SetThicknessDet1(200.); // detector thickness on layer 1 must be in the range [100,300]
	ITS->SetThicknessDet2(200.); // detector thickness on layer 2 must be in the range [100,300]
	ITS->SetThicknessChip1(200.); // chip thickness on layer 1 must be in the range [150,300]
	ITS->SetThicknessChip2(200.);// chip thickness on layer 2 must be in the range [150,300]
	ITS->SetRails(1);	     // 1 --> rails in ; 0 --> rails out
	ITS->SetCoolingFluid(1);   // 1 --> water ; 0 --> freon
	// Geant3 <-> EUCLID conversion
	// ============================
	// SetEUCLID is a flag to output (=1) or not to output (=0) both
	// geometry and media to two ASCII files (called by default
	// ITSgeometry.euc and ITSgeometry.tme) in a format understandable
	// to the CAD system EUCLID.  The default (=0) means that you dont
	// want to use this facility.
	ITS->SetEUCLID(0);
    }
    if (iTPC){
        //============================ TPC parameters =========================
        // This allows the user to specify sectors for the SLOW (TPC geometry
	// 2) Simulator. SecAL (SecAU) <0 means that ALL lower (upper)
        // sectors are specified, any value other than that requires at least
	// one sector (lower or upper)to be specified!
        // Reminder: sectors  1-24 are lower sectors  ( 1-12->z>0,13-24->z<0)
        //           sectors 25-72 are the upper ones (25-48->z>0,49-72->z<0)
        // SecLows - number of lower sectors specified (up to 6)
        // SecUps - number of upper sectors specified (up to 12)
        // Sens - sensitive strips for the Slow Simulator !!!
        // This does NOT work if all S or L-sectors are specified, i.e.
        // if SecAL or SecAU < 0
        //---------------------------------------------------------------------
        //  gROOT->LoadMacro("SetTPCParam.C");
        //  AliTPCParam *param = SetTPCParam();
        AliTPC *TPC = new AliTPCv2("TPC", "Default");
        // All sectors included
        TPC->SetSecAL(-1);
        TPC->SetSecAU(-1);
    }
    if (iTOF){
        //=================== TOF parameters ============================
        AliTOF *TOF = new AliTOFv2("TOF", "normal TOF");
    }
    if (iRICH){
        //=================== RICH parameters ===========================
        AliRICH *RICH = new AliRICHv3("RICH", "normal RICH");
    }
    if (iZDC){
        //=================== ZDC parameters ============================
        AliZDC *ZDC = new AliZDCv2("ZDC", "normal ZDC");
    }
    if (iTRD){
        //=================== TRD parameters ============================
        AliTRD *TRD = new AliTRDv1("TRD", "TRD slow simulator");
        // Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe +
	// 10% CO2)
        TRD->SetGasMix(1);
        // With hole in front of PHOS
        TRD->SetPHOShole();
        // With hole in front of RICH
        TRD->SetRICHhole();
        // Switch on TR
        AliTRDsim *TRDsim = TRD->CreateTR();
    }
    if (iFMD){
        //=================== FMD parameters ============================
        AliFMD *FMD = new AliFMDv1("FMD", "normal FMD");
        FMD->SetRingsSi1(256);
        FMD->SetRingsSi2(64);
        FMD->SetSectorsSi1(20);
        FMD->SetSectorsSi2(24);
    }
    if (iMUON){
        //=================== MUON parameters ===========================
        AliMUON *MUON = new AliMUONv1("MUON", "default");
    }
    if (iPHOS){
	//=================== PHOS parameters ===========================
        AliPHOS *PHOS = new AliPHOSv1("PHOS", "GPS2");
    }
    if (iPMD){
        //=================== PMD parameters ============================
        AliPMD *PMD = new AliPMDv1("PMD", "normal PMD");
        PMD->SetPAR(1., 1., 0.8, 0.02);
        PMD->SetIN(6., 18., -580., 27., 27.);
        PMD->SetGEO(0.0, 0.2, 4.);
        PMD->SetPadSize(0.8, 1.0, 1.0, 1.5);
    }
    if (iEMCAL){
        //=================== EMCAL parameters ============================
        AliEMCAL *EMCAL = new AliEMCALv1("EMCAL", "G56_2_55_19_104_14");
    }
    if (iT0){
        //=================== T0 parameters ============================
        AliT0 *T0 = new AliT0v1("T0", "T0 Detector");
    }
}
//----------------------------------------------------------------------
Float_t EtaToTheta(Float_t arg){
  return (180./TMath::Pi())*2.*atan(exp(-arg));
}


text:
package org.mockitousage.testng;

import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.Map;

import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.when;

@Listeners(MockitoTestNGListener.class)
public class ConfigurationMethodTest {
    @Mock private Map map;

    @BeforeMethod
    public void some_behavior() {
        when(map.get("the answer to ...")).thenReturn(42);
    }

    @Test
    public void mocks_should_stay_configured_with_behavior() throws IOException {
        assertThat(map.get("the answer to ...")).isEqualTo(42);
    }
}


text:
> Executes CoffeeScript scripts or compiles them into JavaScript.

- Run a script:

`coffee {{path/to/file.coffee}}`

- Compile to JavaScript and save to a file with the same name:

`coffee --compile {{path/to/file.coffee}}`

- Compile to JavaScript and save to a given output file:

`coffee --compile {{path/to/file.coffee}} --output {{path/to/file.js}}`

- Run interactive REPL:

`coffee --interactive`

- Watch script for changes and re-run script:

`coffee --watch {{path/to/file.coffee}}`


text:
use 5.022;

{
    package Bridge1;
    use Moose;
    with 'AbstractBridgeRole';
    use namespace::autoclean;

    sub Function1 {
        my $self = shift;
        say "Not implemented exception thrown by Bridge1."
    }

    sub Function2 {
        my $self = shift;
        say "Not implemented exception thrown by Bridge1."
    }

    __PACKAGE__->meta->make_immutable;
}

{
    package Bridge2;
    use Moose;
    with 'AbstractBridgeRole';
    use namespace::autoclean;

    sub Function1 {
       my $self = shift;
        say "Not implemented exception thrown by Bridge2."
    }

    sub Function2 {
        my $self = shift;
        say "Not implemented exception thrown by Bridge2."
    }

    __PACKAGE__->meta->make_immutable;
}

{
    package AbstractBridgeRole;
    use Moose::Role;

    requires qw(Function1 Function2);
}

{
   package AbstractBridge;
   use Moose;

    has 'bridge' => (
        is => 'rw',
        isa => 'AbstractBridgeRole',
        handles => [qw(Function1 Function2)],
    );
}

my $ab1 = AbstractBridge->new(bridge => Bridge1->new());
$ab1->bridge->Function1();
$ab1->bridge->Function2();

my $ab2 = AbstractBridge->new(bridge => Bridge2->new());
$ab2->bridge->Function1();
$ab2->bridge->Function2();


text:
=========================
Salt 0.15.0 Release Notes
=========================

:release: 2013-05-03

The many new features of Salt 0.15.0 have arrived! Salt 0.15.0 comes with many
smaller features and a few larger ones.

These features range from better debugging tools to the new Salt Mine system.

Major Features
==============

The Salt Mine
-------------

First there was the peer system, allowing for commands to be executed from a
minion to other minions to gather data live. Then there was the external job
cache for storing and accessing long term data. Now the middle ground is being
filled in with the Salt Mine. The Salt Mine is a system used to execute
functions on a regular basis on minions and then store only the most recent
data from the functions on the master, then the data is looked up via targets.

The mine caches data that is public to all minions, so when a minion posts
data to the mine all other minions can see it.

IPV6 Support
------------

0.13.0 saw the addition of initial IPV6 support but errors were encountered and
it needed to be stripped out. This time the code covers more cases and must be
explicitly enabled. But the support is much more extensive than before.

Copy Files From Minions to the Master
-------------------------------------

Minions have long been able to copy files down from the master file server, but
until now files could not be easily copied from the minion up to the master.

A new function called ``cp.push`` can push files from the minions up to the
master server. The uploaded files are then cached on the master in the master
cachedir for each minion.

Better Template Debugging
-------------------------

Template errors have long been a burden when writing states and pillar. 0.15.0
will now send the compiled template data to the debug log, this makes tracking
down the intermittent stage templates much easier. So running state.sls or
state.highstate with `-l debug` will now print out the rendered templates in
the debug information.

State Event Firing
------------------

The state system is now more closely tied to the master's event bus. Now when
a state fails the failure will be fired on the master event bus so that the
reactor can respond to it.

Major Syndic Updates
--------------------

The Syndic system has been basically re-written. Now it runs in a completely
asynchronous way and functions primarily as an event broker. This means that
the events fired on the syndic are now pushed up to the higher level master
instead of the old method used which waited for the client libraries to
return.

This makes the syndic much more accurate and powerful, it also means that
all events fired on the syndic master make it up the pipe as well making a
reactor on the higher level master able to react to minions further
downstream.

Peer System Updates
-------------------

The Peer System has been updated to run using the client libraries instead
of firing directly over the publish bus. This makes the peer system much more
consistent and reliable.

Minion Key Revocation
---------------------

In the past when a minion was decommissioned the key needed to be manually
deleted on the master, but now a function on the minion can be used to revoke
the calling minion's key:

.. code-block:: bash

    $ salt-call saltutil.revoke_auth

Function Return Codes
---------------------

Functions can now be assigned numeric return codes to determine if the function
executed successfully. While not all functions have been given return codes,
many have and it is an ongoing effort to fill out all functions that might
return a non-zero return code.

Functions in Overstate
----------------------

The overstate system was originally created to just manage the execution of
states, but with the addition of return codes to functions, requisite logic can
now be used with respect to the overstate. This means that an overstate stage
can now run single functions instead of just state executions.

Pillar Error Reporting
----------------------

Previously if errors surfaced in pillar, then the pillar would consist of only
an empty dict. Now all data that was successfully rendered stays in pillar and
the render error is also made available. If errors are found in the pillar,
states will refuse to run.

Using Cached State Data
-----------------------

Sometimes states are executed purely to maintain a specific state rather than
to update states with new configs. This is grounds for the new cached state
system. By adding `cache=True` to a state call the state will not be generated
fresh from the master but the last state data to be generated will be used.
If no previous state data is available then fresh data will be generated.

Monitoring States
-----------------

The new monitoring states system has been started. This is very young but
allows for states to be used to configure monitoring routines. So far only one
monitoring state is available, the ``disk.status`` state. As more capabilities
are added to Salt UI the monitoring capabilities of Salt will continue to be
expanded.


text:
import {ddescribe, describe, xdescribe, it, iit, xit, expect, beforeEach, afterEach, AsyncTestCompleter, inject, beforeEachProviders} from 'angular2/testing_internal';

import {Component, provide} from 'angular2/core';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {SpyTemplateCompiler} from './spies';
import {TemplateCompiler} from 'angular2/src/compiler/compiler';
import {RuntimeCompiler, RuntimeCompiler_} from 'angular2/src/compiler/runtime_compiler';
import {HostViewFactory} from 'angular2/src/core/linker/view';

export function main() {
  describe('RuntimeCompiler', () => {
    var compiler: RuntimeCompiler_;
    var templateCompilerSpy;
    var someHostViewFactory;

    beforeEachProviders(() => {
      templateCompilerSpy = new SpyTemplateCompiler();
      someHostViewFactory = new HostViewFactory(null, null);
      templateCompilerSpy.spy('compileHostComponentRuntime')
          .andReturn(PromiseWrapper.resolve(someHostViewFactory));
      return [provide(TemplateCompiler, {useValue: templateCompilerSpy})];
    });

    beforeEach(inject([RuntimeCompiler], (_compiler) => { compiler = _compiler; }));

    it('compileInHost should compile the template via TemplateCompiler',
       inject([AsyncTestCompleter], (async) => {
         compiler.compileInHost(SomeComponent).then((hostViewFactoryRef) => {
           expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory);
           async.done();
         });
       }));

    it('should clear the cache', () => {
      compiler.clearCache();
      expect(templateCompilerSpy.spy('clearCache')).toHaveBeenCalled();
    });
  });
}

@Component({selector: 'some-comp', template: ''})
class SomeComponent {
}


text: var data = {balance-block: {}}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache>
    <cache name = "ehcache" maxElementsInMemory = "1000"/>
</ehcache>


text:
package com.github.rvesse.airline.io.writers;

import java.io.Writer;

import com.github.rvesse.airline.io.colors.Color256;
import com.github.rvesse.airline.io.colors.sources.AnsiBackgroundColorSource;
import com.github.rvesse.airline.io.colors.sources.AnsiForegroundColorSource;

/**
 * A colorized writer supporting the ANSI 256 colour palette
 * @author rvesse
 *
 */
public class Ansi256ColorizedWriter extends ColorizedWriter<Color256> {

    public Ansi256ColorizedWriter(Writer writer) {
        super(writer, new AnsiForegroundColorSource<Color256>(), new AnsiBackgroundColorSource<Color256>());
    }

}


text:
package codes.thischwa.bacoma.exception;

import java.util.UUID;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

import codes.thischwa.bacoma.model.pojo.site.Site;

@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends AbstractBacomaException {

	private static final long serialVersionUID = 1L;

	private String name;
	private UUID id;

	public ResourceNotFoundException(Site site) {
		super(site);
	}

	public ResourceNotFoundException(Site site, String name) {
		this(site);
		this.name = name;
	}

	public ResourceNotFoundException(Site site, UUID id) {
		this(site);
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public UUID getId() {
		return id;
	}
}


text:
template< bool C > int assertion_failed( int);
template< class >
struct N
{
  static bool const okay = true;
  enum {
    t = sizeof( assertion_failed<okay>( 0))
  };
};
int main()
{
  N<int> n;
}


text:
package me.zsj.interessant.binder.related;

import android.support.annotation.NonNull;

import me.zsj.interessant.model.Header;

/**
 * @author zsj
 */

public class RelatedHeader {

    public Header header;
    public boolean related;

    public RelatedHeader(@NonNull Header header, boolean related) {
        this.header = header;
        this.related = related;
    }

}


text:
from setuptools import setup, find_packages
import re

for line in open('costcla/__init__.py'):
    match = re.match("__version__ *= *'(.*)'", line)
    if match:
        __version__, = match.groups()

setup(name='costcla',
      version=__version__,
      description='costcla is a Python module for cost-sensitive machine learning (classification) ',
      long_description=open('README.rst').read(),
      author='Alejandro CORREA BAHNSEN',
      author_email='al.bahnsen@gmail.com',
      url='https://github.com/albahnsen/CostSensitiveClassification',
      license='new BSD',
      packages=find_packages(),
      include_package_data = True,
      keywords=['machine learning', 'classification', 'cost-sensitive'],
      install_requires=['scikit-learn>=0.15.0b2','pandas>=0.14.0','numpy>=1.8.0', 'pyea>=0.2'],
      classifiers=['Intended Audience :: Science/Research',
                   'Intended Audience :: Developers',
                   'Programming Language :: Python',
                   'Topic :: Software Development',
                   'Topic :: Scientific/Engineering',
                   'Programming Language :: Python :: 2.7',
                   'Programming Language :: Python :: 3',
                   'Programming Language :: Python :: 3.3',
                   'Programming Language :: Python :: 3.4',
                   'Programming Language :: Python :: 3.5',
                   'Topic :: Scientific/Engineering :: Artificial Intelligence',
                   'License :: OSI Approved :: BSD License',
                   'Operating System :: OS Independent',],
      )


text:
A simple wrapper to enable parallel processing using [Symfony Process](http://symfony.com/doc/current/components/process.html) component.

##Installation

`composer require jagandecapri/symfony-parallel-process`

##Example

```php
<?php

use Symfony\Component\Process\Process;
use Jack\Symfony\ProcessManager;

$proc1 = new Process('ls -l');
$proc2 = new Process('ls -l');

$proc_mgr = new ProcessManager();

$processes = array();
array_push($processes, $proc1, $proc2);

$max_parallel_processes = 5;
$polling_interval = 1000; // microseconds
$proc_mgr->runParallel($processes, $max_parallel_processes, $polling_interval);
```


text:
import $$ from '../utilities/dom-query';
import setup from '../utilities/dom-setup';
import trigger from '../utilities/trigger';

/**
 * Events
 * Events.on: Test click-like events
 *
 * A good reference about the events, and their expected behaviour:
 * https://developer.mozilla.org/en-US/docs/Web/Events
 */

import Events from 'index.js';

QUnit.module('Events', {
    beforeEach: function() {
        const fakeDOM = '\

\

Click the following button:
\
                <button id="child">Child button</button>\
                Child link\

';

        setup(fakeDOM);

        this.box = $$('#parent')[0];
        this.btn = $$('#child')[0];
    }
});

['mouseup', 'mousedown', 'dblclick'].forEach(function(eventName, i) {
    QUnit.test('[CK0'+(i+1)+'] '+eventName, function(assert) {
        const spy = sinon.spy();

        Events.on(this.btn, eventName, spy);
        trigger(this.btn, eventName);

        sinon.assert.calledOnce(spy);
        sinon.assert.calledOn(spy, this.btn);
        assert.expect(0);
    });

    QUnit.test('[CK0'+(i+2)+'] delegate '+eventName, function(assert) {
        const spy = sinon.spy();

        Events.on(this.box, eventName, '#child', spy);
        trigger(this.btn, eventName);

        sinon.assert.calledOnce(spy);
        sinon.assert.calledOn(spy, this.btn);
        assert.expect(0);
    });
});


text:
(function() {
  'use strict';

  var gulp = require('gulp'),
    gutil = require('gulp-util'),
    rev = require('gulp-rev'),
    revReplace = require('gulp-rev-replace'),
    cfg = require('../config.json');

  gulp.task('rev', ['clean', 'scripts', 'less'], function() {
    if(gutil.env.env != 'qa' && gutil.env.env != 'prod') {
      return false;
    }
    return gulp.src(['client/dist/**/*.css', 'client/dist/**/*.js'])
      .pipe(rev())
      .pipe(gulp.dest('client/dist'))
      .pipe(rev.manifest())
      .pipe(gulp.dest('client/dist'));
  });

  gulp.task('revreplace', ['rev'], function () {
    // if(gutil.env.env != 'qa' && gutil.env.env != 'prod') {
    //   return false;
    // }
    var manifest = gulp.src('client/dist/rev-manifest.json');
    return gulp.src("server/views/index.html")
      .pipe(revReplace({manifest: manifest}))
      .pipe(gulp.dest("server/views/dist"));
  });
}());


text:
package org.elasticsearch.rest.action.admin.indices;

import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;

import static org.elasticsearch.rest.RestRequest.Method.GET;

public class RestIndicesStatsAction extends BaseRestHandler {
    public RestIndicesStatsAction(Settings settings, RestController controller) {
        super(settings);
        controller.registerHandler(GET, "/_stats", this);
        controller.registerHandler(GET, "/_stats/{metric}", this);
        controller.registerHandler(GET, "/{index}/_stats", this);
        controller.registerHandler(GET, "/{index}/_stats/{metric}", this);
    }

    @Override
    public String getName() {
        return "indices_stats_action";
    }

    static final Map<String, Consumer<IndicesStatsRequest>> METRICS;

    static {
        final Map<String, Consumer<IndicesStatsRequest>> metrics = new HashMap<>();
        metrics.put("docs", r -> r.docs(true));
        metrics.put("store", r -> r.store(true));
        metrics.put("indexing", r -> r.indexing(true));
        metrics.put("search", r -> r.search(true));
        metrics.put("suggest", r -> r.search(true));
        metrics.put("get", r -> r.get(true));
        metrics.put("merge", r -> r.merge(true));
        metrics.put("refresh", r -> r.refresh(true));
        metrics.put("flush", r -> r.flush(true));
        metrics.put("warmer", r -> r.warmer(true));
        metrics.put("query_cache", r -> r.queryCache(true));
        metrics.put("segments", r -> r.segments(true));
        metrics.put("fielddata", r -> r.fieldData(true));
        metrics.put("completion", r -> r.completion(true));
        metrics.put("request_cache", r -> r.requestCache(true));
        metrics.put("recovery", r -> r.recovery(true));
        metrics.put("translog", r -> r.translog(true));
        METRICS = Collections.unmodifiableMap(metrics);
    }

    @Override
    public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
        IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest();
        indicesStatsRequest.indicesOptions(IndicesOptions.fromRequest(request, indicesStatsRequest.indicesOptions()));
        indicesStatsRequest.indices(Strings.splitStringByCommaToArray(request.param("index")));
        indicesStatsRequest.types(Strings.splitStringByCommaToArray(request.param("types")));

        Set<String> metrics = Strings.tokenizeByCommaToSet(request.param("metric", "_all"));
        // short cut, if no metrics have been specified in URI
        if (metrics.size() == 1 && metrics.contains("_all")) {
            indicesStatsRequest.all();
        } else if (metrics.contains("_all")) {
            throw new IllegalArgumentException(
                String.format(Locale.ROOT,
                    "request [%s] contains _all and individual metrics [%s]",
                    request.path(),
                    request.param("metric")));
        } else {
            indicesStatsRequest.clear();
            // use a sorted set so the unrecognized parameters appear in a reliable sorted order
            final Set<String> invalidMetrics = new TreeSet<>();
            for (final String metric : metrics) {
                final Consumer<IndicesStatsRequest> consumer = METRICS.get(metric);
                if (consumer != null) {
                    consumer.accept(indicesStatsRequest);
                } else {
                    invalidMetrics.add(metric);
                }
            }

            if (!invalidMetrics.isEmpty()) {
                throw new IllegalArgumentException(unrecognized(request, invalidMetrics, METRICS.keySet(), "metric"));
            }
        }

        if (request.hasParam("groups")) {
            indicesStatsRequest.groups(Strings.splitStringByCommaToArray(request.param("groups")));
        }

        if (request.hasParam("types")) {
            indicesStatsRequest.types(Strings.splitStringByCommaToArray(request.param("types")));
        }

        if (indicesStatsRequest.completion() && (request.hasParam("fields") || request.hasParam("completion_fields"))) {
            indicesStatsRequest.completionFields(
                    request.paramAsStringArray("completion_fields", request.paramAsStringArray("fields", Strings.EMPTY_ARRAY)));
        }

        if (indicesStatsRequest.fieldData() && (request.hasParam("fields") || request.hasParam("fielddata_fields"))) {
            indicesStatsRequest.fieldDataFields(
                    request.paramAsStringArray("fielddata_fields", request.paramAsStringArray("fields", Strings.EMPTY_ARRAY)));
        }

        if (indicesStatsRequest.segments()) {
            indicesStatsRequest.includeSegmentFileSizes(request.paramAsBoolean("include_segment_file_sizes", false));
        }

        return channel -> client.admin().indices().stats(indicesStatsRequest, new RestToXContentListener<>(channel));
    }

    @Override
    public boolean canTripCircuitBreaker() {
        return false;
    }

    private static final Set<String> RESPONSE_PARAMS = Collections.singleton("level");

    @Override
    protected Set<String> responseParams() {
        return RESPONSE_PARAMS;
    }

}