text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Bird (v1) - Responsive admin dashboard theme by Followtechnique</title>
	<link href="assets/images/favicon.ico" rel="apple-touch-icon" type="image/png" sizes="144x144">
	<link href="assets/images/favicon.ico" rel="apple-touch-icon" type="image/png" sizes="114x114">
	<link href="assets/images/favicon.ico" rel="apple-touch-icon" type="image/png" sizes="72x72">
	<link href="assets/images/favicon.ico" rel="apple-touch-icon" type="image/png">
	<link href="assets/images/favicon.ico" rel="icon" type="image/png">
	<link href="assets/images/favicon.ico" rel="shortcut icon">

	<link href="fonts/fonts.css" rel="stylesheet" type="text/css">
    <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
	<link href="css/animate.min.css" rel="stylesheet" type="text/css">
	<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
	<link href="css/main.css" rel="stylesheet" type="text/css">
	<link href="css/bootstrap-extended.css" rel="stylesheet" type="text/css">
	<link href="css/plugins.css" rel="stylesheet" type="text/css">
	<link href="css/color-system.css" rel="stylesheet" type="text/css">
	<link href="css/media.css" rel="stylesheet" type="text/css">
	<link type="text/css" rel="stylesheet" href="appearance_typography.html" id="style">
	<link type="text/css" rel="stylesheet" href="appearance_typography.html" id="theme">

Styles

Themes

				5

								Jane Elliott
								04:58

							Suspendisse vel dolor dui. Cras bibendum elit ac...

								Florence Douglas
								12:16

							Aenean aliquam tempor odio nec tincidunt...

								Eugine Turner
								22:48

							Aliquam erat volutpat. Integer ut molestie elit...

								Ann Porter
								Tue

							Maecenas varius bibendum sagittis. Donec porttitor...

								Jacqueline Howell
								Mon

							Cras eleifend gravida ullamcorper. Mauris id congue nunc...

					 Read all notifications

						Andrew Brewer

							Network engineer

						 Dashboard

Content

						 Bootstrap Components

Modals

Dropdown menus

Tabs component

Accordions

Buttons

Tooltips and popovers

Alerts

Pagination

Labels and badges

Loaders and bars

Media objects

						 Appearance

Content panels

Draggable panels

Typography

Helper classes

						 Icons

Glyphicons

Font awesome

Icomoon

 CSS3 Animations

 Color system

 Grid system

Forms

						 Form components

Basic inputs

Input groups

Checkboxes & radios

Select2 selects

Tag inputs

NoUI sliders

Form Wizard

						 Text Editors

CKEditor

TinyMCE editor

						 Pickers

Date & Time pickers

Color pickers

Charts & Graphs

 C3 library

Lines & areas

Bars & pies

Advanced examples

Chart axis

Grid options

 Google charts

Line charts

Bar charts

Pie charts

Bubble & scatter charts

Extensions

 PNotify notifications

						 File uploaders

Bootstrap file uploader

Dropzone

 Event calendars

						 Maps integration

Vector maps

								Google maps

Basics

Markers

Layers

Tables

						 Basic tables

Basic examples

Table borders

Table sizing

Table styling

						 Data tables

Basic datatable

Advanced datatables

						 Data tables extensions

Row reorder

Columns reorder

State Saving

Fixed columns

Fixed header

Auto fill

Key table

Export options

Columns selection

 Responsive tables

Pages

 Email

						 Invoice

Invoice list

Invoice template

 Timeline

 Tasks

 Media Gallery

 Search

						 User pages

Users cards

Users list

Simple user profile

						 Login & registration

User login

Simple registration

Detailed registration

Unlock user

Reset password

Tabbed form

						 Support

FAQ page

Knowledgebase

Support Center

						 Error pages

Error 403

Error 404

Error 405

Error 500

Error 503

Offline page

 Contact Page

Extras

 Starter Page

						 Menu levels

Second level

								Second level with child

Third level

										Third level with child

Fourth level

Fourth level

Third level

Second level

 Typography

Home

Appearance

Typography

Paragraph styles

						Default paragraph

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

						Light paragraph

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

						Semibold paragraph

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

						Bold paragraph

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

Heading styles

						Light headings

H1 Heading (25px)

H2 Heading (23px)

H3 Heading (21px)

H4 Heading  (19px)

h4 Heading (17px)

H6 Heading (15px)

						Regular headings

H1 Heading (25px)

H2 Heading (23px)

H3 Heading (21px)

H4 Heading  (19px)

h4 Heading (17px)

H6 Heading (15px)

						Semibold headings

H1 Heading (25px)

H2 Heading (23px)

H3 Heading (21px)

H4 Heading  (19px)

h4 Heading (17px)

H6 Heading (15px)

						Bold headings

H1 Heading (25px)

H2 Heading (23px)

H3 Heading (21px)

H4 Heading  (19px)

h4 Heading (17px)

H6 Heading (15px)

Heading elements

							 Left icon
							Left positioned heading icon

							Right inline icon
							Right inline icon position

							Right floating icon
							Right floating icon

							New Left label
							Left positioned heading label

							Right inline label New
							Right inline heading label

							Right floating label New
							Right floating heading label

							18 Left badge
							Left positioned heading badge

							Right inline badge 18
							Right inline heading badge

							Right floating badge 18
							Right floating heading badge

List options

						Default unordered list

Lorem ipsum dolor sit amet

Nulla volutpat aliquam velit

Phasellus iaculis neque

Purus sodales ultricies

Faucibus porta lacus fringilla

Aenean sit amet erat nunc

						Square list type

Lorem ipsum dolor sit amet

Nulla volutpat aliquam velit

Phasellus iaculis neque

Purus sodales ultricies

Faucibus porta lacus fringilla

Aenean sit amet erat nunc

						Default ordered list

Lorem ipsum dolor sit amet

Nulla volutpat aliquam velit

Phasellus iaculis neque

Purus sodales ultricies

Faucibus porta lacus fringilla

Aenean sit amet erat nunc

						List with icons

Lorem ipsum dolor sit amet

Nulla volutpat aliquam velit

Phasellus iaculis neque

Purus sodales ultricies

Faucibus porta lacus fringilla

Aenean sit amet erat nunc

Inline list options

						Default inline list

1. First item

2. Second item

3. Third item

						Condensed inline list

1. First item

2. Second item

3. Third item

						Separated inline list

First item

Second item

Third item

Description lists

						Vertical description list

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.

Aenean massa

Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Donec quam felis

Ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

						Horizontal description list

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.

Aenean massa

Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Donec quam felis

Ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

Felis euismod semper eget lacinia

Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.

Blockquote options

						Left blockquote

							Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
							Aenean massa Cum sociis natoque

						Right blockquote

							Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
							Aenean massa Cum sociis natoque

						Left blockquote with image

							Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
							Aenean massa Cum sociis natoque

						Right blockquote with image

							Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
							Aenean massa Cum sociis natoque

Well blocks

						Large well block

							Look, I'm in a large well block!

						Default well block

							Look, I'm in a well block!

						Small well block

							Look, I'm in a small well block!

						White well block

							Look, I'm in a white well block!

						Optional border

							Look, I'm in a bordered well block!

						Solid color wells

							Look, I'm in a .bg-info well block!

						© 2016 Bird - Admin theme by FollowTechnique   •   Version - 1.0.0


text:
This example shows how to use the [Logz.io Log4j 1.2 Appender](https://github.com/logzio/logzio-log4j-appender) to centralize your Java logs.

While this example prints logs both to the console & remotely to Logz.io, the end goal should just be to send remote logs to Logz.io and not to the console or a file.  This will have the best performance of minimizing I/O, as well as the benefit of not having to manage log rotations or disk space.

### High level steps
At a high level, here are the steps (review [Dockerfile](Dockerfile) for more specifics):
- Create/update your Maven *pom.xml* file to include the needed dependencies (review [pom.xml](pom.xml))
- Create/update your *log4j.properties* file to include the *LogzioAppender* and desired properties (review [log4j.properties](log4j.properties))
- Package the necessary dependencies into your application & run

### Requirements
To run this example, you must:
- have the ability to clone this Docker repo (https://github.com/rentacenter/logzio.git)
- have installed [Docker](https://www.docker.com/)
- have the ability for Docker to pull images from [Docker Hub](https://hub.docker.com/)
- have a [logz.io](http://logz.io) account
- have the ability to communicate to *listener.logz.io* over secure *port 8071*

### Build the example
```shell
$ docker build -t logz/log4j-example:1 .
```

### Run the example
```shell
$ docker run -e 'LOGZIO_TOKEN=<put your logz.io token here>' -e 'ENVIRONMENT=dev' logz/log4j-example:1
```

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Deutschl. Krypt. -Fl. (Leipzig) 1: (1844)

#### Original name
Schinzia penicillata Nägeli

### Remarks
null


text: I am the root of a document composite.


text:
import arrow
import datetime
from sqlalchemy import (
    Column, Integer, String, DateTime, ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine

Base = declarative_base()

class DeploymentStatus(object):
    SCHEDULED = 0
    STARTED = 1
    SUCCESS = 2
    FAILED = 3

class Commit(Base):
    __tablename__ = 'commits'

    id = Column(Integer, primary_key=True)
    hash = Column(String)
    time = Column(DateTime)
    message = Column(String)
    url = Column(String)
    author_name = Column(String)
    author_email = Column(String)
    author_username = Column(String)
    committer_name = Column(String)
    committer_email = Column(String)
    committer_username = Column(String)

    def __repr__(self):
        return "<Commit(id='%s', hash='%s', 'author'='%s')>" % (self.id,
                                                                self.hash,
                                                                self.author_name)

class Deployment(Base):
    __tablename__ = 'deployments'

    id = Column(Integer, primary_key=True)
    spec_id = Column(Integer)
    branch = Column(String)
    status = Column(Integer)
    triggered_time = Column(DateTime)
    start_time = Column(DateTime)
    end_time = Column(DateTime)
    triggered_commit_id = Column(Integer, ForeignKey('commits.id'))
    pusher_name = Column(String)
    pusher_email = Column(String)

    triggered_commit = relationship("Commit", backref="Deployment", lazy="joined")

    def __repr__(self):
        return "<Deployment(id='%s', spec_id='%s', branch='%s')>" % (self.id,
                                                                     self.spec_id,
                                                                     self.branch)

    def mark_status(self, st):
        self.status = st

    def is_successful(self):
        return self.status == DeploymentStatus.SUCCESS

    def get_status_description(self):
        if self.status == DeploymentStatus.SCHEDULED:
            return 'scheduled'
        elif self.status == DeploymentStatus.STARTED:
            return 'started'
        elif self.status == DeploymentStatus.FAILED:
            return 'failed'
        elif self.status == DeploymentStatus.SUCCESS:
            return 'success'

    @staticmethod
    def parse_from_github(payload, store):
        print store

        assert isinstance(payload, dict)

        ref = payload['ref']
        branch = ref.split('/')[-1]

        d = Deployment(status=DeploymentStatus.SCHEDULED,
                       triggered_time=datetime.datetime.now())
        d.branch = branch
        d.pusher_name = payload['pusher']['name']
        d.pusher_email = payload['pusher']['email']

        phc = payload['head_commit']
        head_commit = Commit()
        head_commit.hash = phc['id']
        head_commit.time = phc['timestamp']
        head_commit.message = phc['message']
        head_commit.url = phc['url']
        head_commit.author_name = phc['author']['name']
        head_commit.author_email = phc['author']['email']
        head_commit.author_username = phc['author']['username']
        head_commit.committer_name = phc['committer']['name']
        head_commit.committer_email = phc['committer']['email']
        head_commit.committer_username = phc['committer']['username']
        head_commit.time = arrow.get(head_commit.time).datetime
        store.insert_commit(head_commit)

        d.triggered_commit_id = head_commit.id
        d.triggered_commit = head_commit
        return d


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-8-b-iii-1-5.js
 * @description Array.prototype.reduceRight - element to be retrieved is own data property that overrides an inherited accessor property on an Array-like object
 */

function testcase() {

        var testResult = false;
        function callbackfn(prevVal, curVal, idx, obj) {
            if (idx === 1) {
                testResult = (prevVal === "20");
            }
        }

        var proto = {};

        Object.defineProperty(proto, "2", {
            get: function () {
                return 11;
            },
            configurable: true
        });

        var Con = function () { };
        Con.prototype = proto;

        var child = new Con();
        child.length = 3;
        child[0] = "0";
        child[1] = "1";
        Object.defineProperty(proto, "2", {
            value: "20",
            configurable: true
        });

        Array.prototype.reduceRight.call(child, callbackfn);
        return testResult;
    }
runTestCase(testcase);


text:
layout: documentation
title: Annotations
id: annotations
section: documentation
---

## Annotations

Annotations provide information on how a particular field or model class
should behave. The most commonly used annotations are `@Indexed` and
`@Embedded`.

### Field Annotations

`@InternalNamePrefix(String)`

> Specifies the prefix for the internal names of all fields in the target type.

`@CollectionMaximum(int)`

> Specifies the maximum number of items in the target field.

`@CollectionMinimum(int)`

> Specifies the minimum number of items in the target field.

`@DisplayName(String)`

> Specifies the target field's display name.

`@Embedded`

> Specifies whether the target field value is embedded.

`@Ignored`

> Specifies whether the target field is ignored.

`@Indexed`

> Specifies whether the target field value is indexed.

`@InternalName(String)`

> Specifies the target field's internal name.

`@Maximum(double)`

> Specifies either the maximum numeric value or string length of the target field. Our example uses a 5 Star review option.

`@Minimum(double)`

> Specifies either the minimum numeric value or string length of the target field. The user can input 0 out of 5 for the review.

`@Step(double)`

> Specifies the margin between entries in the target field, in the example below every 0.5 is allowed. 0.5, 1.0, 1.5 etc.

`@Regex(String)`

> Specifies the regular expression pattern that the target field value must match.

`@Required`

> Specifies whether the target field value is required.

`@FieldTypes(Class<Recordable>[])`

> Specifies the valid types for the target field value.

`@FieldUnique`

> Deprecated. Use `Recordable.FieldIndexed` with isUnique instead.

`@Values`

> Specifies the valid values for the target field value.

### Class Annotations

`@Abstract`

> Specifies whether the target type is abstract and can't be used to create a concrete instance.

`@DisplayName(String)`

> Specifies the target type's display name.

`@Embedded`

> Specifies whether the target type data is always embedded within another type data.

`@InternalName(String)`

> Specifies the target type's internal name.

`@LabelFields(String[])`

> Specifies the field names that are used to retrieve the labels of the objects represented by the target type.

`@PreviewField`

> Specifies the field name used to retrieve the previews of the objects represented by the target type.


text:
package org.apache.camel.component.kafka;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;

import org.apache.camel.Endpoint;
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * The Producer IT tests require a Kafka broker running on 9092 and a zookeeper instance running on 2181.
 * The broker must have a topic called test created.
 */
public class KafkaProducerIT extends CamelTestSupport {

    public static final String TOPIC = "test";

    @EndpointInject(uri = "kafka:localhost:9092?topic=" + TOPIC + "&partitioner=org.apache.camel.component.kafka.SimplePartitioner")
    private Endpoint to;

    @Produce(uri = "direct:start")
    private ProducerTemplate template;

    private ConsumerConnector kafkaConsumer;

    @Before
    public void before() {
        Properties props = new Properties();
        props.put("zookeeper.connect", "localhost:2181");
        props.put("group.id", KafkaConstants.DEFAULT_GROUP);
        props.put("zookeeper.session.timeout.ms", "400");
        props.put("zookeeper.sync.time.ms", "200");
        props.put("auto.commit.interval.ms", "1000");

        kafkaConsumer = kafka.consumer.Consumer.createJavaConsumerConnector(new ConsumerConfig(props));
    }

    @After
    public void after() {
        kafkaConsumer.shutdown();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {

            @Override
            public void configure() throws Exception {
                from("direct:start").to(to);
            }
        };
    }

    @Test
    public void producedMessageIsReceivedByKafka() throws InterruptedException, IOException {

        final List<String> messages = new ArrayList<String>();

        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
        topicCountMap.put(TOPIC, 5);
        Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = kafkaConsumer.createMessageStreams(topicCountMap);
        List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(TOPIC);

        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (final KafkaStream stream : streams) {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    ConsumerIterator<byte[], byte[]> it = stream.iterator();
                    while (it.hasNext()) {
                        String msg = new String(it.next().message());
                        messages.add(msg);
                    }
                }
            });
        }

        for (int k = 0; k < 10; k++) {
            template.sendBodyAndHeader("IT test message", KafkaConstants.PARTITION_KEY, "1");
        }

        for (int k = 0; k < 20; k++) {
            if (messages.size() == 10) {
                return;
            }
            Thread.sleep(200);
        }

        fail();
    }
}


text:
module Main where

import System.Win32.HPPath (winPath, unWinPath, clearPath, addHPPath,
  isVersionOpt)
import System.Environment (getArgs, lookupEnv, setEnv)
import System.Exit (exitWith, ExitCode(ExitFailure))
import System.Process (callProcess)
import Data.Maybe (fromMaybe)
import Data.Version (showVersion)
import Paths_win_hp_path (version)

usage :: IO ()
usage = putStrLn (unlines msg) >> exitWith (ExitFailure 1)
  where
    msg =
      [ "use-hppath version " ++ showVersion version
      , "Usage:"
      , "  use-hppath <path-to-hp>"
      , "Example:"
      , "  use-hppath " ++
        "\"C:\\Program Files (x86)\\Haskell Platform\\2014.2.0.0\""
      ]

main = fmap parseCmd getArgs >>= maybe usage useHPPath

useHPPath :: FilePath -> IO ()
useHPPath hp = do
  oldPath <- fmap (winPath . fromMaybe []) $ lookupEnv "PATH"
  let newPath = addHPPath hp . clearPath $ oldPath
  setEnv "PATH" $ unWinPath newPath
  putStrLn $ "Using Haskell Platform at " ++ hp
  putStrLn $ "Enter 'exit' when done."
  callProcess "cmd.exe" []

parseCmd :: [String] -> Maybe FilePath
parseCmd [v]
 | isVersionOpt v = Nothing
 | otherwise      = Just v
parseCmd _        = Nothing


text:
package gitoscope.exception;

public class GitoscopeException extends RuntimeException {
    public GitoscopeException() {
        super();
    }

    public GitoscopeException(Throwable t) {
        super(t);
    }
}


text:
var JsonViewer = require('../viewer/json/index.js');

function Response(ctx) {
    this._ctx = ctx;
    this._data = [];

    this._headers = {};

    this.setStatus(200);
    this.setContentType("application/json; charset=utf-8;");
}

Response.prototype.getData = function (mid) {
    var data = this.getDataArray(mid);
    return data ? data[0] : null;
}

Response.prototype.getDataArray = function (mid) {
    var data = [];
    for(var i in this._data) {
        if(!mid || this._data[i].module.getMid() == mid) {
            data.push(this._data[i]);
        }
    }
    return data;
}

Response.prototype.send = function (data, viewer) {
    if(!viewer)
        viewer = JsonViewer;

    this._data.push({module:this._ctx.current.module, viewer:viewer, data:data});
}

Response.prototype.error = function (data) {
    var error = typeof data == "string" ? data : {error:{mid:data.mid, code:data.code, message:data.message, stack:data.stack}};
    this.setStatus(500);
    this._data.push({module:this._ctx.getSaram().getCoreModule(), viewer:JsonViewer, data:error});
    this.sendResponse();
}

Response.prototype.getStatus = function () {
    return this.status;
}

Response.prototype.setStatus = function (code) {
    this.status = code;
}

Response.prototype.getContentType = function () {
    return this.contentType;
}

Response.prototype.setContentType = function (contentType) {
    this.contentType = contentType;
}

Response.prototype.getHeader = function (name) {
    return this._headers[name]
}

Response.prototype.setHeader = function (name, value) {
    this._headers[name] = value;
}

Response.prototype.sendResponse = function () {
    if(this.getStatus()>=400) {
        var root = this._data.pop();
        root._stack = this._data;
        throw root.data.error;
    }
}

module.exports = Response;


text:
layout: page
title: Moon Squad Corporation Conference
date: 2016-05-24
author: Deborah Malone
tags: weekly links, java
status: published
summary: Nullam et lacinia orci. Cras a sem augue.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 07/21/2019
  endDate: 07/24/2019
  ctyhocn: MKEBLHX
  groupCode: MSCC
published: true
---
Nam id massa sem. Aenean velit arcu, malesuada non erat eu, commodo ultricies neque. In quis ex vitae ligula consequat tincidunt. Aenean gravida iaculis tellus, ut posuere nibh laoreet at. Sed lobortis diam eu sagittis fermentum. Etiam tincidunt lobortis velit, nec egestas erat. Suspendisse dolor nunc, placerat vitae vulputate et, congue vitae purus. Nullam eget ligula a neque varius tempus. Morbi sagittis non ex sit amet tincidunt. Donec odio velit, tempus at ullamcorper non, fermentum nec nibh. Suspendisse iaculis et neque id luctus. In hac habitasse platea dictumst. Donec finibus sollicitudin orci, ac hendrerit velit congue non. Etiam scelerisque placerat nulla, at cursus massa. Aliquam risus eros, auctor sed diam nec, ornare fringilla neque.

* Nulla in erat et tortor ullamcorper facilisis eget sit amet nulla
* Pellentesque eu orci vehicula, faucibus elit ut, fringilla ipsum
* Phasellus vestibulum nulla et luctus elementum
* Sed et sapien id ligula rutrum luctus
* Cras quis lorem ut erat rhoncus faucibus sed nec diam
* Mauris facilisis elit in porttitor elementum.

In hac habitasse platea dictumst. Ut iaculis a justo ac rhoncus. Donec vitae rutrum orci. Nullam ornare suscipit malesuada. Etiam bibendum tortor vitae interdum scelerisque. Ut venenatis molestie finibus. Nunc sit amet elit at dolor fringilla ultrices.
Vivamus feugiat ut ligula non aliquet. Suspendisse velit eros, convallis in urna sit amet, rhoncus semper dui. Aliquam rutrum ex at semper volutpat. Fusce sed libero ac sem facilisis volutpat vitae eu nibh. Fusce commodo placerat ante, ac vulputate libero imperdiet in. Cras porttitor ante eu mattis semper. Phasellus elementum ut nibh et dignissim. Aliquam dignissim ligula quis ullamcorper eleifend. Sed molestie eget ante in ultrices. Donec enim mi, laoreet sed bibendum eu, lobortis porttitor turpis. Pellentesque pharetra scelerisque nisl, eget iaculis leo finibus id. Integer aliquam ipsum eu malesuada porttitor.


text:
/* globals describe, it */
/* eslint-disable no-new-wrappers */

'use strict';

var assert = require('assert');
var pick = require('../');
var es5It = typeof Object.create === 'function' ? it : xit;

describe('pick', function() {
  it('should be a function', function() {
    assert.equal(typeof pick, 'function');
  });

  it('should have an arity of 2', function() {
    assert.equal(pick.length, 2);
  });

  it('should return a new object', function() {
    var source = { name: 'tim' };
    var result = pick('name', source);

    assert.equal(typeof result, 'object');
    assert.notEqual(result, source);
  });

  it('should return an object including only the specified `keep` property', function() {
    var source = { name: 'tim', occupation: 'enchanter' };
    var expected = { name: 'tim' };

    assert.deepEqual(pick('name', source), expected);
  });

  it('should return an object including only the specified `keep` properties', function() {
    var source = { name: 'tim', occupation: 'enchanter', scaredOf: 'rabbits' };
    var expected = { name: 'tim', scaredOf: 'rabbits' };

    assert.deepEqual(pick(['name', 'scaredOf'], source), expected);
  });

  it('should handle properties that don\'t exist on the target `object`', function() {
    var source = { name: 'tim', occupation: 'enchanter', scaredOf: 'rabbits' };

    assert.deepEqual(pick('nonexistent', source), {});
    assert.deepEqual(pick(['name', 'keys'], source), { name: 'tim' });
  });

  it('should handle an empty list of `props`', function() {
    var source = { name: 'tim', occupation: 'enchanter', scaredOf: 'rabbits' };

    assert.deepEqual(pick([], source), {});
  });

  it('should ignore non-string omissions', function() {
    var source = { name: 'tim', 'null': 'enchanter', 'undefined': 'rabbits' };

    assert.deepEqual(pick(null, source), {});
    assert.deepEqual(pick([null, undefined], source), {});
    assert.deepEqual(pick([null, 'name', undefined], source), { name: 'tim' });
  });

  it('should handle non-array/string `omissions` arguments', function() {
    var source = { name: 'tim', occupation: 'enchanter', scaredOf: 'rabbits' };

    assert.deepEqual(pick(null, source), {});
    assert.deepEqual(pick(undefined, source), {});
    assert.deepEqual(pick(/name/, source), {});
    assert.deepEqual(pick(Error, source), {});
  });

  it('should handle objects with a `.length` property', function() {
    var source = { name: 'tim', occupation: 'enchanter', scaredOf: 'rabbits', length: 100 };
    var expected = { name: 'tim', scaredOf: 'rabbits', length: 100 };

    assert.deepEqual(pick(['name', 'scaredOf', 'length'], source), expected);
  });

  it('should handle `null` and `undefined` as the `object` parameter', function() {
    assert.deepEqual(pick('whatever', null), {});
    assert.deepEqual(pick('whatever', undefined), {});
  });

  it('should return an empty object when passed a primitive value', function() {
    assert.deepEqual(pick('whatever', 'test'), {});
    assert.deepEqual(pick('whatever', 12), {});
    assert.deepEqual(pick('whatever', /regex/), {});
  });

  es5It('should not ignore non-enumerable properties', function() {
    var source = Object.create(null, {
      name: { value: 'tim', enumerable: true },
      occupation: { value: 'enchanter', enumerable: true },
      scaredOf: { value: 'rabbits', enumerable: false }
    });

    assert('scaredOf' in pick('scaredOf', source));
  });

  es5It('should not ignore inherited properties', function() {
    var parent = { parent: 'parent' };
    var child = Object.create(parent);
    child.child = 'child';
    child.color = 'green';

    assert('parent' in pick('parent', child));
  });
});


text:
"""The product Matern32 kernel embeddings."""

from typing import Union

import numpy as np

from ...quadrature.interfaces.standard_kernels import IProductMatern32
from ..measures import IntegrationMeasure, LebesgueMeasure
from .quadrature_kernels import LebesgueEmbedding, QuadratureProductKernel

class QuadratureProductMatern32(QuadratureProductKernel):
    r"""Base class for a product Matern32 kernel augmented with integrability.

    The kernel is of the form :math:`k(x, x') = \sigma^2 \prod_{i=1}^d k_i(x, x')` where

    .. math::
        k_i(x, x') = (1 + \sqrt{3}r_i ) e^{-\sqrt{3} r_i}.

    Above, :math:`d` is the input dimensionality, :math:`r_i =\frac{|x_i - x'_i|}{\lambda_i}`,
    is the scaled distance, :math:`\sigma^2` is the ``variance`` property and :math:`\lambda_i`
    is the :math:`i` th element of the ``lengthscales`` property.

    .. note::
        This class is compatible with the standard kernel :class:`IProductMatern32`.
        Each subclass of this class implements an embedding w.r.t. a specific integration measure.

    .. seealso::
       * :class:`emukit.quadrature.interfaces.IProductMatern32`
       * :class:`emukit.quadrature.kernels.QuadratureProductKernel`

    :param matern_kernel: The standard EmuKit product Matern32 kernel.
    :param measure: The integration measure.
    :param variable_names: The (variable) name(s) of the integral.

    """

    def __init__(
        self,
        matern_kernel: IProductMatern32,
        measure: IntegrationMeasure,
        variable_names: str,
    ) -> None:
        super().__init__(kern=matern_kernel, measure=measure, variable_names=variable_names)

    @property
    def nu(self) -> float:
        """The smoothness parameter of the kernel."""
        return self.kern.nu

    @property
    def lengthscales(self) -> np.ndarray:
        r"""The lengthscales :math:`\lambda` of the kernel."""
        return self.kern.lengthscales

    @property
    def variance(self) -> float:
        r"""The scale :math:`\sigma^2` of the kernel."""
        return self.kern.variance

class QuadratureProductMatern32LebesgueMeasure(QuadratureProductMatern32, LebesgueEmbedding):
    """A product Matern32 kernel augmented with integrability w.r.t. the standard Lebesgue measure.

    .. seealso::
       * :class:`emukit.quadrature.interfaces.IProductMatern32`
       * :class:`emukit.quadrature.kernels.QuadratureProductMatern32`
       * :class:`emukit.quadrature.measures.LebesgueMeasure`

    :param matern_kernel: The standard EmuKit product Matern32 kernel.
    :param measure: The Lebesgue measure.
    :param variable_names: The (variable) name(s) of the integral.

    """

    def __init__(self, matern_kernel: IProductMatern32, measure: LebesgueMeasure, variable_names: str = "") -> None:
        super().__init__(matern_kernel=matern_kernel, measure=measure, variable_names=variable_names)

    def _scale(self, z: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
        return self.variance * z

    def _get_univariate_parameters(self, dim: int) -> dict:
        return {
            "domain": self.measure.domain.bounds[dim],
            "lengthscale": self.lengthscales[dim],
            "normalize": self.measure.is_normalized,
        }

    def _qK_1d(self, x: np.ndarray, **parameters) -> np.ndarray:
        a, b = parameters["domain"]
        lengthscale = parameters["lengthscale"]
        normalization = 1 / (b - a) if parameters["normalize"] else 1.0
        s3 = np.sqrt(3.0)
        first_term = 4.0 * lengthscale / s3
        second_term = -np.exp(s3 * (x - b) / lengthscale) * (b + 2.0 * lengthscale / s3 - x)
        third_term = -np.exp(s3 * (a - x) / lengthscale) * (x + 2.0 * lengthscale / s3 - a)
        return (first_term + second_term + third_term) * normalization

    def _qKq_1d(self, **parameters) -> float:
        a, b = parameters["domain"]
        lengthscale = parameters["lengthscale"]
        normalization = 1 / (b - a) if parameters["normalize"] else 1.0
        c = np.sqrt(3.0) * (b - a)
        qKq = (
            2.0 * lengthscale / 3.0 * (2.0 * c - 3.0 * lengthscale + np.exp(-c / lengthscale) * (c + 3.0 * lengthscale))
        )
        return float(qKq) * normalization**2

    def _dqK_dx_1d(self, x: np.ndarray, **parameters) -> np.ndarray:
        a, b = parameters["domain"]
        lengthscale = parameters["lengthscale"]
        normalization = 1 / (b - a) if parameters["normalize"] else 1.0
        s3 = np.sqrt(3)
        exp_term_b = np.exp(s3 * (x - b) / lengthscale)
        exp_term_a = np.exp(s3 * (a - x) / lengthscale)
        first_term = exp_term_b * (-1 + (s3 / lengthscale) * (x - b))
        second_term = exp_term_a * (+1 - (s3 / lengthscale) * (a - x))
        return (first_term + second_term) * normalization


text:
parentheses_expr(_,char,char_literal(A)) -->
	char_literal(A).

parentheses_expr(_,string,string_literal(A)) -->
	string_literal(A).

parentheses_expr(Data,Type1,anonymous_function(Type1,Params1,Body1)) -->
        anonymous_function_(Data,[
			type(Data,Type1),
			parameters(Data,Params1),
			statements(Data,Type1,Body1)
        ]).

parentheses_expr(Data,bool,"true") -->
	true_(Data).
parentheses_expr(Data,bool,"false") -->
	false_(Data).

parentheses_expr(Data,[array,Type],initializer_list(A)) -->
	initializer_list_(Data,[
		initializer_list_(Data,Type,A),
		type(Data,Type)
	]).

parentheses_expr(Data,[dict,Type1],dict(A)) -->
	dict_(Data,[
		dict_(Data,Type1,A),
		type(Data,Type1)
	]).

parentheses_expr(Data,Type,var_name(A)) -->
	var_name_(Data,Type,A).

parentheses_expr(_,int,an_int(A)) -->
	an_int(A).
parentheses_expr(_,double,a_double(A)) -->
	a_double(A).

parentheses_expr(Data,Type,parentheses(A)) -->
	"(",ws,expr(Data,Type,A),ws,")".

parentheses_expr(Data,Type, function_call(Name,Params1,Params2)) -->
    function_call_(Data,[
		function_name(Data,Type,Name,Params2),
		function_call_parameters(Data,Params1,Params2)
	]),
	{reserved_words(Name)}.


text:
package com.joshcough.minecraft.db;

import com.avaje.ebean.EbeanServer;
import com.joshcough.minecraft.fp.*;
import static com.joshcough.minecraft.fp.JavaParsers.*;
import org.bukkit.entity.Player;

import java.util.List;

public class WarpPluginJava extends BetterJavaPlugin {

  private static Parser<String> warpToken = anyString;

  public WarpPluginJava(){
    addDependency("WarpPluginDB");
    Commands(
      Command("warps", "List all warps.", p -> warpsFor(p).forEach(w -> p.sendMessage(w.toString()))),
      Command("warp", "Warp to the given warp location.", warpToken,
        (p, wt) -> p.teleport(getWarp(p, wt).location(p.getWorld()))
      ),
      Command("set-warp", "Create a new warp location.", warpToken,
        (p, warpName) -> {
          getDatabase().save(createWarp(warpName, p));
          p.sendMessage("created warp: " + warpName);
        }
       )
    );
  }

  public EbeanServer getDatabase(){
    return getServer().getPluginManager().getPlugin("WarpPluginDB").getDatabase();
  }

  // go to the database to find all the warps for the given player
  List<Warp> warpsFor(Player p){
    return getDatabase().find(Warp.class).where().eq("player", p.getName()).findList();
  }

  Warp getWarp(Player p, String name){
    return getDatabase().find(Warp.class).where().
        eq("player", p.getName()).eq("name", name).findUnique();
  }

  Warp createWarp(String n, Player p) {
    Warp w = new Warp();
    w.name = n;
    w.player = p.getName();
    w.x = p.getLocation().getX();
    w.y = p.getLocation().getY();
    w.z = p.getLocation().getZ();
    return w;
  }

  /*
    Command("delete-warp", "Delete a warp location.", warpToken){ case (p, wt) =>
      withWarp(p, wt){w => db.delete(w); p ! s"deleted warp: ${w.name}" }
    },

    Command("delete-all", "Delete all your warps.")(p =>
    warpsFor(p).foreach{ w => p ! s"deleting: $w"; db.delete(w); }
    ),

    OpOnly(Command("purge-warps-database", "Delete all warps in the database.")(p =>
    db.foreach { w => p ! s"deleting: $w"; db.delete(w) })
        )
        )
   */

}


text:
<?php

/** @var \Magento\Framework\Registry $registry */
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\Framework\Registry');

$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);

/** @var $product \Magento\Catalog\Model\Product */
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Catalog\Model\Product');
$product->loadByAttribute('sku', 'simple');
if ($product->getId()) {
    $product->delete();
}

/** @var $product \Magento\Catalog\Model\Product */
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Catalog\Model\Product');
$product->loadByAttribute('sku', '12345');
if ($product->getId()) {
    $product->delete();
}

/** @var $category \Magento\Catalog\Model\Category */
$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Catalog\Model\Category');
$category->load(9);
if ($category->getId()) {
    $category->delete();
}

$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);


text:
<?php

namespace Oro\Bundle\LocaleBundle\DoctrineExtensions\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

class UTCDateTimeType extends DateTimeType
{
    /** @var null| \DateTimeZone  */
    static private $utc = null;

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
        }

        /** @var \DateTime $value */
        $timezone = (self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'));
        if ($value->getTimezone() !== $timezone) {
            $value->setTimezone($timezone);
        }

        return parent::convertToDatabaseValue($value, $platform);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
        }

        $val = \DateTime::createFromFormat(
            $platform->getDateTimeFormatString(),
            $value,
            (self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'))
        );

        if (!$val) {
            throw ConversionException::conversionFailed($value, $this->getName());
        }

        $errors = $val->getLastErrors();
        // date was parsed to completely not valid value
        if ($errors['warning_count'] > 0 && (int)$val->format('Y') < 0) {
            return null;
        }

        return $val;
    }
}


text:
owner_slack: "#govuk-2ndline-tech"
title: Deploy an emergency banner
parent: "/manual.html"
layout: manual_layout
section: Publishing
important: true
---

There are three types of events that would lead GOV.UK to add an emergency
banner to the top of each page on the web site; a notable death, a national
emergency or a local emergency.

> **Note**
>
> There is also [a non-emergency sitewide banner](/manual/global-banner.html), used to convey important information on GOV.UK which is not deemed emergency level information.

The GOV.UK on-call escalations contact will tell you when you need to publish
an emergency banner. They will ensure that the event is legitimate and provide
you with the text for the emergency banner. They will also tell you what type
of event it is; you do not need to determine the type of event yourself.

If you need to publish the emergency banner out of hours, you will be
instructed to do so either by the GOV.UK on-call escalations contact or the
Head of GOV.UK.

Contact numbers for those people are in the [legacy Ops manual](https://docs.google.com/document/d/17XUuPaZ5FufyXH00S9qukl6Kf3JbJtAqwHR3eOBVBpI/edit).

## Adding an emergency banner

### 1. Get the content you will need

The GOV.UK on-call escalations contact will supply you with:

- The emergency banner type or campaign class (one of `notable-death`,
  `national-emergency` or `local-emergency`)
- Text for the heading.
- (Optional) Text for the 'short description', which is a sentence displayed under the heading. This is optional.
- (Optional) A URL for users to find more information (it might not be provided at first).
- (Optional) Link text that will be displayed for the more information URL (this will default to "More information" if you do not supply it).

### 2. Deploy the banner using Jenkins

The data for the emergency banner is stored in Redis. Jenkins is used to set the variables.

1. Go to the Jenkins task:
   - [Deploy the emergency banner on Integration](https://deploy.integration.publishing.service.gov.uk/job/deploy-emergency-banner/)
   - [Deploy the emergency banner on Staging](https://deploy.blue.staging.govuk.digital/job/deploy-emergency-banner/)
   - [⚠ Deploy the emergency banner on Production ⚠](https://deploy.blue.production.govuk.digital/job/deploy-emergency-banner/)

1. Click `Build with Parameters`.

1. Fill in the appropriate variables using the form presented by Jenkins. Use a relative URL (i.e. without the www.gov.uk prefix) if a link is required.

1. Click `Build`.

![Jenkins Deploy Emergency Banner](images/emergency_publishing/deploy_emergency_banner_job.png)

> **Note**
>
> The Jenkins job will also clear the Varnish caches and the CDN cache for [a predefined list of 10 URLs](https://github.com/alphagov/govuk-puppet/blob/8cca9aad2b68d6cb396a135f47524fafeca1c947/modules/govuk_jenkins/templates/jobs/clear_cdn_cache.yaml.erb#L22-L34) (including the website root).

### 3. Test with cache bust strings

Most GOV.UK pages have a cache TTL of 5 minutes. After deploying the emergency
banner you should expect to see the banner appear on all GOV.UK pages within
10 minutes.

Once the banner deployment completes, wait a minute to allow frontend
application caches to clear, and then do a test to see if the deployment has
succeeded.

Test the changes by visiting pages and adding a cache-bust string. Remember to change the URL based on the environment you are testing in (integration, staging, production).

For each page:

- Check the banner displays as expected
- Double-check the information for the header, short description and link are as they should be
- Test the link, if it is present
- Make sure the banner colour is appropriate - black for a notable death, red for a national emergency, green for a local emergency

#### Some example pages to check

- [https://www.gov.uk/?ae00e491](https://www.gov.uk/?ae00e491) ([Integration](https://www-origin.integration.publishing.service.gov.uk/?ae00e491), [Staging](https://www-origin.staging.publishing.service.gov.uk/?ae00e491))
- [https://www.gov.uk/financial-help-disabled?7f7992eb](https://www.gov.uk/financial-help-disabled?7f7992eb) ([Integration](https://www-origin.integration.publishing.service.gov.uk/financial-help-disabled?7f7992eb), [Staging](https://www-origin.staging.publishing.service.gov.uk/financial-help-disabled?7f7992eb))
- [https://www.gov.uk/government/organisations/hm-revenue-customs?49854527](https://www.gov.uk/government/organisations/hm-revenue-customs?49854527) ([Integration](https://www-origin.integration.publishing.service.gov.uk/government/organisations/hm-revenue-customs?49854527), [Staging](https://www-origin.staging.publishing.service.gov.uk/government/organisations/hm-revenue-customs?49854527))
- [https://www.gov.uk/search?q=69b197b8](https://www.gov.uk/search?q=69b197b8) ([Integration](https://www-origin.integration.publishing.service.gov.uk/search?q=69b197b8), [Staging](https://www-origin.staging.publishing.service.gov.uk/search?q=69b197b8))

If the banner doesn't show, [look at the troubleshooting section](#the-banner-is-not-showing--not-clearing).

Once all caches have had time to clear, check that the emergency banner is visible when accessing the same pages as before but without a cache-bust string.

- [https://www.gov.uk/](https://www.gov.uk/) ([Integration](https://www-origin.integration.publishing.service.gov.uk/), [Staging](https://www-origin.staging.publishing.service.gov.uk/))
- [https://www.gov.uk/financial-help-disabled](https://www.gov.uk/financial-help-disabled) ([Integration](https://www-origin.integration.publishing.service.gov.uk/financial-help-disabled), [Staging](https://www-origin.staging.publishing.service.gov.uk/financial-help-disabled))
- [https://www.gov.uk/government/organisations/hm-revenue-customs](https://www.gov.uk/government/organisations/hm-revenue-customs) ([Integration](https://www-origin.integration.publishing.service.gov.uk/government/organisations/hm-revenue-customs), [Staging](https://www-origin.staging.publishing.service.gov.uk/government/organisations/hm-revenue-customs))
- [https://www.gov.uk/search](https://www.gov.uk/search) ([Integration](https://www-origin.integration.publishing.service.gov.uk/search), [Staging](https://www-origin.staging.publishing.service.gov.uk/search))

---

## Removing an emergency banner

### Remove the banner using Jenkins

1. Navigate to the appropriate deploy Jenkins environment (integration, staging or production):
   - [Remove the emergency banner from Integration](https://deploy.integration.publishing.service.gov.uk/job/remove-emergency-banner/)
   - [Remove the emergency banner from Staging](https://deploy.blue.staging.govuk.digital/job/remove-emergency-banner/)
   - [⚠ Remove the emergency banner from Production ⚠](https://deploy.blue.production.govuk.digital/job/remove-emergency-banner/)

1. Click `Build now` in the left hand menu.

![Jenkins Remove Emergency Banner](images/emergency_publishing/remove_emergency_banner_job.png)

Caches will clear automatically.

---

## Troubleshooting

### Background

The information for the emergency banner is stored in Redis. [Static](https://github.com/alphagov/static) is responsible for displaying the data and we use Jenkins to run [rake tasks in static](https://github.com/alphagov/static/blob/main/lib/tasks/emergency_banner.rake) to set or delete the appropriate hash in Redis.

### The banner is not showing / not clearing

Usually this is because a cache has not expired or cleared properly. This can be
at various points in our stack as well as locally in your browser. Things to try:

- Make sure you are actually looking at a page on the environment you released
  the banner. All the links in this document go to the production version of
  GOV.UK. Remember to use the equivalent page for the environment (often staging)
  on which you are testing/releasing the banner.
- Test the page with `curl` to circumvent any browser-based caching.
  Chrome seems to aggressively cache on occasion. You can also test in an
  private browser instance.
- It is possible that the caching layers for the GOV.UK stack have evolved and
  we need to tweak the scripts to clear new caches that have been set up.
- You can also try manually purging the Varnish and CDN caches:
  1. Wait for 2 minutes after the Deploy Emergency Banner job has completed.
    This will allow the frontend application caches to [clear automatically after 60s][slimmer-cache].
  2. Run the "Clear varnish cache" Jenkins job
     - [Clear varnish on Integration](https://deploy.blue.integration.govuk.digital/job/clear-varnish-cache/)
     - [Clear varnish on  Staging](https://deploy.blue.staging.govuk.digital/job/clear-varnish-cache/)
     - [⚠ Clear varnish on Production ⚠](https://deploy.blue.production.govuk.digital/job/clear-varnish-cache/)
  3. Run the "Clear CDN cache" Jenkins job
     - [Clear CDN on Integration](https://deploy.blue.integration.govuk.digital/job/clear-cdn-cache/)
     - [Clear CDN on  Staging](https://deploy.blue.staging.govuk.digital/job/clear-cdn-cache/)
     - [⚠ Clear CDN on Production ⚠](https://deploy.blue.production.govuk.digital/job/clear-cdn-cache/)

[slimmer-cache]: https://github.com/alphagov/slimmer/blob/5b8428704f143547bdae2c7cb9a585ab77d3181b/lib/slimmer.rb#L10

### Manually testing the Redis key

You can manually check whether the data has been stored in Redis by the Jenkins job on one of the frontend machines.

1. Load a Rails console for the static application on the frontend machine in the relevant environment.

   ```bash
   $ gds govuk connect -e staging app-console frontend/static
   ```

1. Check the Redis key exists:

   ```rb
   irb(main):001:0> Redis.new.hgetall("emergency_banner")
   #> {}
   ```

In the above example, the key has not been set. A successfully set key would return a result similar to the following:

```rb
irb(main):001:0> Redis.new.hgetall("emergency_banner")
=> {"campaign_class"=>"notable-death", "heading"=>"The heading", "short_description"=>"The short description", "link"=>"https://www.gov.uk", "link_text"=>"More information about the emergency"}
```

### Manually running the rake task to deploy the emergency banner

If you need to manually run the rake tasks to set the Redis keys, you can do so (remember to follow the instructions above to clear application template caches, restart Whitehall and purge origin caches afterwards):

1. SSH into a `frontend` machine appropriate to the environment you are
   deploying the banner on. For example:

   ```bash
   $ gds govuk connect -e staging ssh frontend
   ```

1. Change into the directory for `static`:

   ```bash
   $ cd /var/apps/static
   ```

1. Run the rake task to create the emergency banner hash in Redis, substituting
   the quoted data for the parameters:

   ```bash
   $ sudo -u deploy govuk_setenv static bundle exec rake emergency_banner:deploy[campaign_class,heading,short_description,link,link_text]
   ```

The `campaign_class` is directly injected into the HTML as a `class` and must be one of

- notable-death
- national-emergency
- local-emergency

For example, if you are deploying an emergency banner for which you have the
following information:

- Type: Death
- Heading: Alas poor Yorick
- Short description: I knew him Horatio
- URL: <https://www.gov.uk>
- Link text: Click for more information

You would enter the following command:

```bash
$ sudo -u deploy govuk_setenv static bundle exec rake emergency_banner:deploy["notable-death","Alas poor Yorick","I knew him Horatio","https://www.gov.uk","Click for more information"]
```

Note there are no spaces after the commas between parameters to the rake task.

Quit your SSH session:

```bash
$ exit
```

### Manually running the rake task to remove an emergency banner

1. SSH into a frontend machine:

   ```bash
   $ gds govuk connect -e staging ssh frontend
   ```

1. Change into the directory for `static`:

   ```bash
   $ cd /var/apps/static
   ```

1. Run the rake task to remove the emergency banner hash from Redis:

   ```bash
   $ sudo -u deploy govuk_setenv static bundle exec rake emergency_banner:remove
   ```

1. Quit your SSH session

   ```bash
   $ exit
   ```

---

## Types of emergency banners

### Death of a notable person

A large **black** banner is displayed on all GOV.UK pages, including the homepage.

The wording to use in the template will be the official title of the
deceased and the years of their life, for example 'His Royal Highness Henry VIII
1491 to 1547'. The text should link to their official biography.

#### GOV.UK Homepage

![GOV.UK Homepage](images/emergency_publishing/notable-death-homepage.png)

#### Other pages

![](images/emergency_publishing/notable-death.png)

### National emergency (level 1 or category 2)

A large **red** banner is displayed on all GOV.UK pages, including the homepage.

#### GOV.UK Homepage

![GOV.UK Homepage](images/emergency_publishing/national-emergency-homepage.png)

#### Other pages

![](images/emergency_publishing/national-emergency.png)

### Localised large-scale emergency (level 2 or category 1)

A large **green** banner is displayed on all GOV.UK pages, including the homepage.

These incidents will not be processed outside of business hours.

#### GOV.UK Homepage

![GOV.UK Homepage](images/emergency_publishing/local-emergency_homepage.png)

#### Other pages

![](images/emergency_publishing/local-emergency.png)


text:
package net.sourceforge.ganttproject.chart;

import net.sourceforge.ganttproject.chart.GraphicPrimitiveContainer.GraphicPrimitive;
import net.sourceforge.ganttproject.chart.GraphicPrimitiveContainer.Rectangle;
import net.sourceforge.ganttproject.time.TimeFrame;
import net.sourceforge.ganttproject.time.TimeUnit;
import net.sourceforge.ganttproject.task.algorithm.SortTasksAlgorithm;
import net.sourceforge.ganttproject.task.dependency.TaskDependency;
import net.sourceforge.ganttproject.task.ResourceAssignment;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskActivity;
import net.sourceforge.ganttproject.task.TaskLength;

import java.awt.Dimension;
import java.awt.Point;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: bard
 */
public class TaskRendererImpl extends ChartRendererBase implements TimeUnitVisitor{
    private List/*<TaskActivity>*/ myVisibleActivities;
    private static final SortTasksAlgorithm ourAlgorithm = new SortTasksAlgorithm();
    private List/*<TaskActivity>*/ myCurrentlyProcessed = new ArrayList();
    private Map/*<TaskActivity,Integer>*/ myActivity2ordinalNumber = new HashMap();
    private Map/*<Task, Integer>*/ myTask_WorkingRectanglesLength = new HashMap();
    private int myPosX;
    private TimeFrame myCurrentTimeFrame;
    private TimeUnit myCurrentUnit;
	private Date myUnitStart;
	private boolean myProgressRenderingEnabled = true;
	private boolean myDependenciesRenderingEnabled = true;
	private GraphicPrimitiveContainer myRegularTaskContainer = new GraphicPrimitiveContainer();

    public TaskRendererImpl(ChartModelImpl model) {
        super(model);
        getPrimitiveContainer().newLayer();
        getPrimitiveContainer().newLayer();
    }

    public void beforeProcessingTimeFrames() {
        getPrimitiveContainer().clear();
        getPrimitiveContainer().getLayer(1).clear();
        getPrimitiveContainer().getLayer(2).clear();
        myActivity2ordinalNumber.clear();
        myTask_WorkingRectanglesLength.clear();
        myVisibleActivities = getSortedTaskActivities();
        myCurrentlyProcessed.clear();
        myPosX = 0;
    }

	public void afterProcessingTimeFrames() {
		if (myDependenciesRenderingEnabled) {
			createDependencyLines();
		}
	}

	private List/*<Task>*/ getSortedTaskActivities() {
        List visibleTasks = ((ChartModelImpl)getChartModel()).getVisibleTasks();
        List visibleActivities = new ArrayList();
        myActivity2ordinalNumber.clear();
        for (int i=0; i<visibleTasks.size(); i++) {
        	Task nextTask = (Task) visibleTasks.get(i);
        	Integer nextOrdinal = new Integer(i);
        	TaskActivity[] activities = nextTask.getActivities();
        	//System.err.println("[TaskRendererImpl] task="+nextTask+"\nactivities="+Arrays.asList(activities));
        	for (int j=0; j<activities.length; j++) {
                myActivity2ordinalNumber.put(activities[j], nextOrdinal);
                visibleActivities.add(activities[j]);
        	}
        	float totalTaskLength = nextTask.getDuration().getLength(getChartModel().getBottomUnit())*getChartModel().getBottomUnitWidth();
        	myTask_WorkingRectanglesLength.put(nextTask, new Long((long)(totalTaskLength*nextTask.getCompletionPercentage()/100)));
        }
        ourAlgorithm.sortByStartDate(visibleActivities);
        return visibleActivities;
    }

    public void startTimeFrame(TimeFrame timeFrame) {
        myCurrentTimeFrame = timeFrame;
    }

    public void endTimeFrame(TimeFrame timeFrame) {
        myCurrentTimeFrame = null;
    }

    public void startUnitLine(TimeUnit timeUnit) {
        if (myCurrentTimeFrame.getBottomUnit()==timeUnit) {
            myCurrentUnit = timeUnit;
        }
    }

    public void endUnitLine(TimeUnit timeUnit) {
        myCurrentUnit = null;
    }

    public void nextTimeUnit(int unitIndex) {
        if (myCurrentUnit!=null) {
            Date unitStart = myCurrentTimeFrame.getUnitStart(myCurrentUnit, unitIndex);
            Date unitFinish = myCurrentTimeFrame.getUnitFinish(myCurrentUnit, unitIndex);
            myUnitStart = unitStart;
            pullQueue(unitStart, unitFinish);
            //System.err.println("[TaskRendererImpl] nextTimeUnit(): unitStart="+unitStart+" posX="+myPosX);
            //if (!myCurrentlyProcessed.isEmpty()) {
            //    System.err.println("[TaskRendererImpl] nextTimeUnit(): processing:"+myCurrentlyProcessed);
            //}
            for (Iterator startedActivities = myCurrentlyProcessed.iterator(); startedActivities.hasNext();startedActivities.remove())  {
                TaskActivity nextStarted = (TaskActivity) startedActivities.next();
                processActivity(nextStarted);
            }
            myPosX+=getChartModel().getBottomUnitWidth();
        }
    }

    private void processActivity(TaskActivity nextStarted) {
        if (nextStarted.isLast()) {
        	processLastActivity(nextStarted);
        }
        else if (nextStarted.isFirst()) {
        	processFirstActivity(nextStarted);
        }
        else {
        	processRegularActivity(nextStarted);
        }
    }

	private Rectangle processRegularActivity(TaskActivity nextStarted) {
        Task nextTask = nextStarted.getTask();
        boolean nextHasNested = ((ChartModelImpl)getChartModel()).getTaskContainment().getNestedTasks(nextTask).length>0;
        if (nextTask.isMilestone() && !nextStarted.isFirst()) {
            return null;
        }
        java.awt.Rectangle nextBounds = getBoundingRectangle(nextStarted);
        int nextLength = (int)nextBounds.width;
        int topy = nextBounds.y;

        int posX = myPosX;
        GraphicPrimitiveContainer.Rectangle nextRectangle;
        //if (nextStarted.getStart().compareTo(myUnitStart)>=0) {
        	TaskLength deltaLength = nextTask.getManager().createLength(getChartModel().getTimeUnitStack().getDefaultTimeUnit(), myUnitStart, nextStarted.getStart());

        	int deltaX = (int) (deltaLength.getLength(myCurrentUnit)*getChartModel().getBottomUnitWidth());
        	posX += deltaX;
        	//System.err.println("[TaskRendererImpl] myUnitStart="+myUnitStart+" nextActivity="+nextStarted+" deltaX="+deltaX+" deltaLength="+deltaLength.getLength(myCurrentUnit));
        //}
//        else {
//        	nextRectangle = getPrimitiveContainer().createRectangle(myPosX+getChartModel().getBottomUnitWidth()-nextLength, topy, nextLength, getRowHeight()*3/5);
//        }

            GraphicPrimitiveContainer container = nextHasNested ? getPrimitiveContainer().getLayer(2) : getPrimitiveContainer();
    	nextRectangle = container.createRectangle(posX, topy, (int)nextLength, getRowHeight()*3/5);
        //System.err.println("task="+nextStarted.getTask()+" nested tasks length="+nextStarted.getTask().getNestedTasks().length);
        if (nextStarted.getTask().isMilestone()) {
        	nextRectangle.setStyle("task.milestone");
        }
        else if (nextHasNested) {
       		nextRectangle.setStyle("task.supertask");
       		if (nextStarted.isFirst()) {
       			GraphicPrimitiveContainer.Rectangle supertaskStart =  container.createRectangle(nextRectangle.myLeftX, topy, (int)nextLength, getRowHeight()*3/5);
       			supertaskStart.setStyle("task.supertask.start");
       		}
       		if (nextStarted.isLast()) {
       			GraphicPrimitiveContainer.Rectangle supertaskEnd =  container.createRectangle(posX, topy, (int)nextLength, getRowHeight()*3/5); // JA (added -1)
       			supertaskEnd.setStyle("task.supertask.end");

       		}
        }
        else if (nextStarted.getIntensity()==0f) {
        	nextRectangle.setStyle("task.holiday");
        }
        else {
            nextRectangle.setStyle("task");
            if (myProgressRenderingEnabled) {
            	renderProgressBar(nextTask, nextRectangle);
            }
        }
        if (!"task.holiday".equals(nextRectangle.getStyle()) && !"task.supertask".equals(nextRectangle.getStyle())) {
        	nextRectangle.setBackgroundColor(nextStarted.getTask().getColor());
        }
        container.bind(nextRectangle, nextStarted);
        return nextRectangle;
	}

	private void renderProgressBar(Task nextTask, GraphicPrimitiveContainer.Rectangle nextActivityRectangle) {
		int nextLength = nextActivityRectangle.myWidth;
		Long workingRectanglesLength = (Long) myTask_WorkingRectanglesLength.get(nextTask);
		if (workingRectanglesLength!=null) {
			long nextProgressLength = nextLength;
			String style;
			if (workingRectanglesLength.longValue()>nextLength) {
				myTask_WorkingRectanglesLength.put(nextTask, new Long(workingRectanglesLength.longValue()-nextLength));
				style = "task.progress";
			}
			else {
				nextProgressLength = workingRectanglesLength.longValue();
				myTask_WorkingRectanglesLength.remove(nextTask);
				style = "task.progress.end";
			}
			int nextMidY = nextActivityRectangle.getMiddleY();
			GraphicPrimitive nextProgressRect = getPrimitiveContainer().getLayer(1).createRectangle(nextActivityRectangle.myLeftX, nextMidY-1, (int)nextProgressLength, 3);
			nextProgressRect.setStyle(style);
			getPrimitiveContainer().getLayer(1).bind(nextProgressRect, nextTask);
		}
	}

	private void processFirstActivity(TaskActivity taskActivity) {
        boolean stop = taskActivity.getIntensity()==0f;
		if (!stop) {
			processRegularActivity(taskActivity);
		}
	}

	private void processLastActivity(TaskActivity taskActivity) {
        java.awt.Rectangle bounds = getBoundingRectangle(taskActivity);
		if (taskActivity.getIntensity()!=0f) {
			processRegularActivity(taskActivity);
		}
        if (taskActivity.getTask().isMilestone()) {
            return;
        }
        int xText = (int)bounds.getMaxX()+9;
        int yText = (int) bounds.getCenterY()+3;
        getPrimitiveContainer().getLayer(2).createText(xText, yText, getTaskLabel(taskActivity.getTask()));
	}

	private String getTaskLabel(Task task) {
		StringBuffer result = new StringBuffer();
		if (myProgressRenderingEnabled) {
			result.append("[ ");
			result.append(task.getCompletionPercentage()+"%");
			result.append(" ] ");
		}
		ResourceAssignment[] assignments = task.getAssignments();
		if (assignments.length>0) {
			for (int i=0; i<assignments.length; i++) {
				result.append(assignments[i].getResource().getName());
				if (i<assignments.length-1) {
					result.append(",");
				}
			}
		}
		return result.toString();
	}

    private java.awt.Rectangle getBoundingRectangle(TaskActivity activity) {
    	//System.err.println("[TaskRendererImpl] activity="+activity+"\nstartDate="+myUnitStart+"\nduration="+activity.getDuration().getLength(myCurrentUnit));
    	int posX = myPosX;
        if (activity.getStart().compareTo(myUnitStart)>=0) {
        	TaskLength deltaLength = activity.getTask().getManager().createLength(getChartModel().getTimeUnitStack().getDefaultTimeUnit(), myUnitStart, activity.getStart());

        	int deltaX = (int) (deltaLength.getLength(myCurrentUnit)*getChartModel().getBottomUnitWidth());
        	posX += deltaX;
        }
        int length = (int)(activity.getDuration().getLength(myCurrentUnit)*getChartModel().getBottomUnitWidth());
        Integer nextOrdNumber = (Integer)myActivity2ordinalNumber.get(activity);
        int topy = nextOrdNumber.intValue()*getRowHeight() + 4; // JA Added 4 so that it draws in middle of row
        return new java.awt.Rectangle(posX, topy, length, getRowHeight());
    }

	private void createDependencyLines() {
		List/*<DependencyDrawData>*/ dependencyDrawData = prepareDependencyDrawData();
		drawDependencies(dependencyDrawData);
	}

    /**
	 * @param dependencyDrawData
	 */
	private void drawDependencies(List dependencyDrawData) {
        GraphicPrimitiveContainer primitiveContainer = getPrimitiveContainer().getLayer(2);
        int arrowLength = 7;
		for (int i=0; i<dependencyDrawData.size(); i++) {
			DependencyDrawData next = (DependencyDrawData)dependencyDrawData.get(i);
            if (next.myDependeeVector.reaches(next.myDependantVector.getPoint())) {
                // when dependee.end <= dependant.start && dependency.type is any
                // or dependee.end <= dependant.end && dependency.type==FF
                // or dependee.start >= dependant.end && dependency.type==SF
                int ysign = signum(next.myDependantVector.getPoint().y - next.myDependeeVector.getPoint().y);
            	Point first =new Point(next.myDependeeVector.getPoint().x, next.myDependeeVector.getPoint().y);
            	Point second= new Point(next.myDependantVector.getPoint(-3).x, next.myDependeeVector.getPoint().y);
                Point third = new Point(next.myDependantVector.getPoint(-3).x, next.myDependantVector.getPoint().y);
                java.awt.Rectangle arrowBoundary = null;
                String style;
                if (next.myDependantVector.reaches(third)){
                    second.x += arrowLength;
                    third.x += arrowLength;
                	Point forth = next.myDependantVector.getPoint();
                	primitiveContainer.createLine(third.x,third.y,forth.x,forth.y);
                    arrowBoundary = new java.awt.Rectangle(forth.x, forth.y-3, arrowLength, 6);
                    style = "dependency.arrow.left";
                }
                else {
                    third.y -= ysign*next.myDependantRectangle.myHeight/2;
                    arrowBoundary = new java.awt.Rectangle(third.x-3, third.y - (ysign>0 ? ysign*arrowLength : 0), 6, arrowLength);
                    style = ysign>0 ? "dependency.arrow.down" : "dependency.arrow.up";
                }
                primitiveContainer.createLine(first.x,first.y,second.x,second.y);
                primitiveContainer.createLine(second.x,second.y,third.x,third.y);
                if (arrowBoundary!=null) {
                    Rectangle arrow=primitiveContainer.createRectangle(arrowBoundary.x, arrowBoundary.y, arrowBoundary.width, arrowBoundary.height);
                    arrow.setStyle(style);
                }
            }
            else {
            	Point first = next.myDependeeVector.getPoint(3);
            	if (next.myDependantVector.reaches(first)) {
            		Point second = new Point(first.x, next.myDependantVector.getPoint().y);
                	primitiveContainer.createLine(next.myDependeeVector.getPoint().x, next.myDependeeVector.getPoint().y, first.x, first.y);
                	primitiveContainer.createLine(first.x, first.y, second.x, second.y);
                	primitiveContainer.createLine(second.x, second.y, next.myDependantVector.getPoint().x, next.myDependantVector.getPoint().y);
                	int xsign = signum(next.myDependantVector.getPoint().x-second.x);
                	java.awt.Rectangle  arrowBoundary = new java.awt.Rectangle(next.myDependantVector.getPoint(7).x, next.myDependantVector.getPoint().y-3, xsign*7, 6);
                	Rectangle arrow=primitiveContainer.createRectangle(arrowBoundary.x, arrowBoundary.y, arrowBoundary.width, arrowBoundary.height);
                	arrow.setStyle(xsign<0?"dependency.arrow.left":"dependency.arrow.right");
            	}
            	else {
	            	Point forth = next.myDependantVector.getPoint(3);
	            	Point second = new Point(first.x, (first.y+forth.y)/2);
	            	Point third = new Point(forth.x, (first.y+forth.y)/2);
	            	primitiveContainer.createLine(next.myDependeeVector.getPoint().x, next.myDependeeVector.getPoint().y, first.x, first.y);
	            	primitiveContainer.createLine(first.x, first.y, second.x, second.y);
	            	primitiveContainer.createLine(second.x, second.y, third.x, third.y);
	            	primitiveContainer.createLine(third.x, third.y, forth.x, forth.y);
	            	primitiveContainer.createLine(forth.x, forth.y, next.myDependantVector.getPoint().x, next.myDependantVector.getPoint().y);
            	}
            }
		}
	}

    private int signum(int value) {
        if (value==0) {
            return 0;
        }
        return value<0 ? -1 : 1;
    }

	/**
	 * @return
	 */
	private List prepareDependencyDrawData() {
		List result = new ArrayList();
		List/*<Task>*/ visibleTasks = ((ChartModelImpl)getChartModel()).getVisibleTasks();
		for (int i=0; i<visibleTasks.size(); i++) {
			Task nextTask = (Task) visibleTasks.get(i);
			prepareDependencyDrawData(nextTask, result);
		}
		return result;
	}

	private void prepareDependencyDrawData(Task task, List result) {
		TaskDependency[] deps = task.getDependencies().toArray();
		for (int i=0; i<deps.length; i++) {
			TaskDependency next = deps[i];
			TaskDependency.ActivityBinding activityBinding = next.getActivityBinding();
			TaskActivity dependant = activityBinding.getDependantActivity();
			GraphicPrimitiveContainer.Rectangle dependantRectangle = (Rectangle) getPrimitiveContainer().getPrimitive(dependant);
			if (dependantRectangle==null) {
				continue;
			}
			TaskActivity dependee = activityBinding.getDependeeActivity();
			GraphicPrimitiveContainer.Rectangle dependeeRectangle = (Rectangle) getPrimitiveContainer().getPrimitive(dependee);
			if (dependeeRectangle==null) {
				continue;
			}
            Date[] bounds = activityBinding.getAlignedBounds();
            PointVector dependantVector;
            if (bounds[0].equals(dependant.getStart())) {
                dependantVector = new WestPointVector(new Point(dependantRectangle.myLeftX, dependantRectangle.getMiddleY()));
            }
            else if (bounds[0].equals(dependant.getEnd())) {
                dependantVector = new EastPointVector(new Point(dependantRectangle.getRightX(), dependantRectangle.getMiddleY()));
            }
            else {
                throw new RuntimeException();
            }
            //
            PointVector dependeeVector;
            if (bounds[1].equals(dependee.getStart())) {
                dependeeVector = new WestPointVector(new Point(dependeeRectangle.myLeftX, dependeeRectangle.getMiddleY()));
            }
            else if (bounds[1].equals(dependee.getEnd())) {
                dependeeVector = new EastPointVector(new Point(dependeeRectangle.getRightX(), dependeeRectangle.getMiddleY()));
            }
            else {
                throw new RuntimeException();
            }
			DependencyDrawData data = new DependencyDrawData(next, dependantRectangle, dependeeRectangle, dependantVector, dependeeVector);
			result.add(data);
		}
	}

	private int getRowHeight() {
        return getConfig().getRowHeight();
    }

    private void pullQueue(Date unitStart, Date unitFinish) {
        for (Iterator activities = myVisibleActivities.iterator(); activities.hasNext();) {
            TaskActivity next = (TaskActivity) activities.next();
            if (next.getStart().after(unitFinish)) {
                break;
            }
            if (next.getStart().compareTo(unitStart)>=0 && next.getStart().compareTo(unitFinish)<0 ||
            	next.getEnd().compareTo(unitStart)>=0 && next.getEnd().compareTo(unitFinish)<0) {
                myCurrentlyProcessed.add(next);
                activities.remove();
            }
        }
    }

    private static class DependencyDrawData {
    	final GraphicPrimitiveContainer.Rectangle myDependantRectangle;
    	final GraphicPrimitiveContainer.Rectangle myDependeeRectangle;
    	final TaskDependency myDependency;
        final PointVector myDependantVector;
        final PointVector myDependeeVector;

		public DependencyDrawData(TaskDependency dependency, GraphicPrimitiveContainer.GraphicPrimitive dependantPrimitive, GraphicPrimitiveContainer.GraphicPrimitive dependeePrimitive, PointVector dependantVector, PointVector dependeeVector) {
			myDependency = dependency;
			myDependantRectangle = (GraphicPrimitiveContainer.Rectangle)dependantPrimitive;
			myDependeeRectangle = (GraphicPrimitiveContainer.Rectangle)dependeePrimitive;
			myDependantVector = dependantVector;
            myDependeeVector = dependeeVector;
		}

        public String toString() {
            return "From activity="+myDependency.getActivityBinding().getDependantActivity()+" (vector="+myDependantVector+")\n to activity="+myDependency.getActivityBinding().getDependeeActivity()+" (vector="+myDependeeVector;
        }
    }

    private static abstract class PointVector {
        private final Point myPoint;
        protected PointVector(Point point) {
            myPoint = point;
        }
		Point getPoint() {
            return myPoint;
        }
        abstract boolean reaches(Point targetPoint);
        abstract Point getPoint(int i);
    }

    private static class WestPointVector extends PointVector {
        protected WestPointVector(Point point) {
            super(point);
        }

        boolean reaches(Point targetPoint) {
            return targetPoint.x <= getPoint().x;
        }

		Point getPoint(int diff) {
			return new Point(getPoint().x-diff, getPoint().y);
		}

        public String toString() {
            return "<="+getPoint().toString();
        }

    }

    private static class EastPointVector extends PointVector {
        protected EastPointVector(Point point) {
            super(point);
        }

        boolean reaches(Point targetPoint) {
            return targetPoint.x>=getPoint().x;
        }

		Point getPoint(int diff) {
			return new Point(getPoint().x+diff, getPoint().y);
		}

        public String toString() {
            return ">="+getPoint().toString();
        }

    }

	public void setProgressRenderingEnabled(boolean renderProgress) {
		myProgressRenderingEnabled = renderProgress;
	}

	public void setDependenciesRenderingEnabled(boolean renderDependencies) {
		myDependenciesRenderingEnabled = renderDependencies;
	}

}


text:
//Adding and removing employees
$(function () {
    $('#template-row').hide();

    //Taking the last index in the table of the current teams if we are making an edit and
    //for new record index = 0
    if ($("#beginForm").attr("class") == "createForm") {
        index = 0;
    }
    else {
        var index = $('table.table tr').length;
    }

    //Таking the html template row replacing the word index with number and appending the new employee in the table
    //as new row with DropDownList
    $('#add-team-btn').on('click', function () {
        var html = $('#template-row').html();
        html = html.replace(/index/g, index);
        $('#tableTeams').append('<tr>' + html + '</tr>');
        index++;
    });

    $("#tableTeams").on("click", "#delete-team-btn", function () {
        $(this).closest('tr').remove();
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bifapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- Permissions required for GCM -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.bifapp.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.bifapp.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.bifapp.provider"
            android:exported="false"
            android:grantUriPermissions="true" >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    </application>

</manifest>


text:
<?php

namespace Okanjo\Clients\Marketplace\Constants;

class LoginAction
{
    const LOGIN_USERNAME_PASSWORD = 'loginUsernamePassword';
    const LOGIN_EMAIL_PASSWORD = 'loginEmailPassword';
    const LOGIN_FACEBOOK = 'loginFacebook';
    const LOGIN_OPENID = 'loginOpenID';

    const REGISTER_EMAIL_PASSWORD = 'registerEmailPassword';
    const REGISTER_FACEBOOK = 'registerFacebook';
    const REGISTER_OPENID = 'registerOpenID';

    const GUEST_CHECKOUT = 'checkoutAsGuest';
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Naiad.Dataflow.Channels;
using Microsoft.Research.Naiad.Serialization;
using Microsoft.Research.Naiad.DataStructures;

namespace Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.CollectionTrace
{
    internal struct Handle<T>
    {
        public readonly T[] Array;
        public readonly int Offset;
        public readonly int Length;

        public Handle(T[] array, int offset, int length) { Array = array; Offset = offset; Length = length; }
    }

    internal struct RegionHandle<R>
    {
        public Handle<R> Handle;

        public readonly int Identifier;     // a unique ID for this region
        public readonly int HeapOffset;     // offset into a fixed-length heap
        public readonly int HeapIndex;      // index of the fixed-length heap.

        public bool IsNull { get { return Identifier == 0; } }

        public RegionHandle(int i, int o, int l)
        {
            Handle = default(Handle<R>);

            Identifier = i; HeapOffset = o; HeapIndex = l;
        }

        public RegionHandle(int i)
        {
            Handle = default(Handle<R>);

            Identifier = i;

            if (Identifier != 0)
            {
                HeapIndex = 0;
                while ((Identifier >> HeapIndex) % 2 == 0)
                    HeapIndex++;

                HeapOffset = Identifier >> (HeapIndex + 1);
            }
            else
            {
                HeapIndex = 0;
                HeapOffset = 0;
            }
        }

        public RegionHandle(int o, int l)
        {
            Handle = default(Handle<R>);

            HeapOffset = o;
            HeapIndex = l;

            Identifier = (HeapOffset << (HeapIndex + 1)) + (1 << HeapIndex);
        }
    }

    internal struct FixedLengthHeap<T>
        where T : IEquatable<T>
    {
        public NaiadList<T[]> Spine;          //
        public NaiadList<int> FreeList;       // consider making this a priority queue...

        public readonly int SegmentLength;             // the length of each element in the spine
        public readonly int Length;                    // the length of each allocatable region

        public int Allocated;                 // next available offset

        public Handle<T> Dereference(int Offset)
        {
            return new Handle<T>(Spine.Array[(Offset * Length) / SegmentLength], (Offset * Length) % SegmentLength, Length);
        }

        public int Allocate()
        {
            if (FreeList.Count > 0)
            {
                return FreeList.RemoveAtAndReturn(0);
            }
            else
            {
                // make sure there are enough elements available
                while (Spine.Count * SegmentLength < (Allocated + 1) * Length)
                    Spine.Add(new T[SegmentLength]);

                return Allocated++;
            }
        }

        public void Release(int region)
        {
            // seems unlikely, but may as well try...
            if (region == Allocated - 1)
                Allocated--;
            else
                FreeList.Add(region);
        }

        public double Density()
        {
            if (Allocated > 0)
                return 1.0 - ((double)FreeList.Count) / Allocated;
            else
                return 1.0;
        }

        /* Checkpoint format:
         * int                         SpineCount
         * T[SegmentLength]*SpineCount Spine
         * NaiadList<int> FreeList
         * int            Allocated
         */

        public void Checkpoint(NaiadWriter writer)
        {
            writer.Write(this.Spine.Count);
            for (int i = 0; i < this.Spine.Count; ++i)
                for (int j = 0; j < this.SegmentLength; ++j)
                    writer.Write(this.Spine.Array[i][j]);

            this.FreeList.Checkpoint(writer);

            writer.Write(this.Allocated);
        }

        public void Restore(NaiadReader reader)
        {
            int spineCount = reader.Read<int>();
            this.Spine.Clear();
            this.Spine.EnsureCapacity(spineCount);
            this.Spine.Count = spineCount;
            for (int i = 0; i < spineCount; ++i)
            {
                this.Spine.Array[i] = new T[this.SegmentLength];
                for (int j = 0; j < this.Spine.Array[i].Length; ++j)
                    this.Spine.Array[i][j] = reader.Read<T>();
            }

            this.FreeList.Restore(reader);

            this.Allocated = reader.Read<int>();
        }

        public bool Stateful { get { return true; } }

        public FixedLengthHeap(int length, int segmentLength)
        {
            Length = length;
            FreeList = new NaiadList<int>(0);
            Spine = new NaiadList<T[]>(0);

            SegmentLength = Math.Max(segmentLength, Length);

            Allocated = 0;
        }
    }

    internal struct VariableLengthHeap<T>
        where T : IEquatable<T>
    {
        public readonly FixedLengthHeap<T>[] heaps;

        public Handle<T> Dereference(OffsetLength ol)
        {
            if (ol.IsEmpty)
            {
                return new Handle<T>(null, 0, 0);
            }
            else
            {
                var offset = 0;
                var length = 0;

                ol.GetOffsetLength(out offset, out length);

                return heaps[length].Dereference(offset);
            }
        }

        public Handle<T> Dereference(int Offset, int Length)
        {
            return heaps[Length].Dereference(Offset);
        }

        public void Release(ref OffsetLength ol)
        {
            if (!ol.IsEmpty)
            {
                var offset = 0;
                var length = 0;

                ol.GetOffsetLength(out offset, out length);

                heaps[length].Release(offset);
                ol = new OffsetLength();
            }
        }

        public Handle<T> Allocate(out OffsetLength ol, int capacity)
        {
            var offset = 0;
            var length = 0;

            var handle = Allocate(out offset, out length, capacity);

            for (int i = 0; i < handle.Length; i++)
                handle.Array[handle.Offset + i] = default(T);

            ol = new OffsetLength(offset, length);

            return handle;
        }

        public Handle<T> Allocate(out int Offset, out int Length, int capacity)
        {
            Length = 0;
            while (capacity > heaps[Length].Length)
                Length++;

            Offset = heaps[Length].Allocate();

            return heaps[Length].Dereference(Offset);
        }

        public Handle<T> EnsureAllocation(ref OffsetLength ol, int capacity)
        {
            if (ol.IsEmpty)
            {
                return Allocate(out ol, capacity);
            }
            else
            {
                var offset = 0;
                var length = 0;

                ol.GetOffsetLength(out offset, out length);

                var handle = EnsureAllocation(ref offset, ref length, capacity);

                ol = new OffsetLength(offset, length);

                return handle;
            }
        }

        Handle<T> EnsureAllocation(ref int Offset, ref int Length, int capacity)
        {
            if (capacity > heaps[Length].Length)
            {
                var oldLength = Length;
                var oldOffset = Offset;

                var newHandle = Allocate(out Offset, out Length, capacity);
                var oldHandle = heaps[oldLength].Dereference(oldOffset);

                for (int i = 0; i < heaps[oldLength].Length; i++)
                    newHandle.Array[newHandle.Offset + i] = oldHandle.Array[oldHandle.Offset + i];

                for (int i = heaps[oldLength].Length; i < heaps[Length].Length; i++)
                    newHandle.Array[newHandle.Offset + i] = default(T);

                heaps[oldLength].Release(oldOffset);

                return newHandle;
            }
            else
                return heaps[Length].Dereference(Offset);
        }

        /* Checkpoint format:
         * FixedLengthHeap<T>*this.heaps.Length heaps
         * [N.B. this.heaps.Length is provided as a parameter to the constructor
         *       and is always 32.]
         */

        public void Checkpoint(NaiadWriter writer)
        {
            for (int i = 0; i < this.heaps.Length; ++i)
            {
                this.heaps[i].Checkpoint(writer);
            }
        }

        public void Restore(NaiadReader reader)
        {
            for (int i = 0; i < this.heaps.Length; ++i)
            {
                this.heaps[i].Restore(reader);
            }
        }

        public bool Stateful { get { return true; } }

        public VariableLengthHeap(int heapCount)
        {
            heaps = Enumerable.Range(0, heapCount).Select(i => new FixedLengthHeap<T>(1 << i, 1 << 16)).ToArray();
        }
    }

    internal struct VariableLengthHeapAlt<T>
        where T : IEquatable<T>
    {
        public FixedLengthHeap<T>[] heaps;

        public RegionHandle<T> Dereference(int identifier)
        {
            var result = new RegionHandle<T>(identifier);

            if (!result.IsNull)
                result.Handle = heaps[result.HeapIndex].Dereference(result.HeapOffset);

            return result;
        }

        public void Release(ref RegionHandle<T> handle)
        {
            if (!handle.IsNull)
            {
                heaps[handle.HeapIndex].Release(handle.HeapOffset);
                handle = new RegionHandle<T>();
            }
        }

        public RegionHandle<T> Allocate(int capacity)
        {
            var index = 0;
            while (capacity > heaps[index].Length)
                index++;

            var result = new RegionHandle<T>(heaps[index].Allocate(), index);

            result.Handle = heaps[result.HeapIndex].Dereference(result.HeapOffset);

            return result;
        }

        public void EnsureAllocation(ref RegionHandle<T> handle, int capacity)
        {
            if (handle.IsNull)
                handle = Allocate(capacity);
            else
            {
                if (capacity > heaps[handle.HeapIndex].Length)
                {
                    var newHandle = Allocate(capacity);

                    for (int i = 0; i < heaps[handle.HeapIndex].Length; i++)
                        newHandle.Handle.Array[newHandle.Handle.Offset + i] = handle.Handle.Array[handle.Handle.Offset + i];

                    for (int i = heaps[handle.HeapIndex].Length; i < heaps[newHandle.HeapIndex].Length; i++)
                        newHandle.Handle.Array[newHandle.Handle.Offset + i] = default(T);

                    Release(ref handle);

                    handle = newHandle;
                }
            }
        }

        public VariableLengthHeapAlt(int heapCount, int segmentSize = 1 << 16)
        {
            heaps = Enumerable.Range(0, heapCount).Select(i => new FixedLengthHeap<T>(1 << i, segmentSize)).ToArray();
        }
    }
}


text:
{% extends widget.get_base_template %}

{% load i18n %}

{% block content %}
<object id="svg-{{ widget.fe_identifier }}" class='svg_preview' data="{{ widget.source.file.url }}" type="image/svg+xml" {% if width and height %}width="{{ width }}" height="{{ height }}"{% else %}width="640px" height="480px"{% endif %}>
    <embed src="{{ widget.source.file.url }}" type="image/svg+xml" {% if width and height %}width="{{ width }}" height="{{ height }}"{% else %}width="640px" height="480px"{% endif %}/>
</object>
<script type="text/javascript">
$('#svg-{{ widget.fe_identifier }}').width($('#svg-{{ widget.fe_identifier }}').closest('#{{ widget.fe_identifier }}').width());

</script>
{% endblock %}


text:
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}

module Unison.Test.Util.PinBoard
  ( test,
  )
where

import qualified Data.ByteString as ByteString
import EasyTest
import GHC.Exts (isTrue#, reallyUnsafePtrEquality#, touch#)
import GHC.IO (IO (IO))
import System.Mem (performGC)
import qualified Unison.Util.PinBoard as PinBoard

test :: Test ()
test =
  scope "util.pinboard" . tests $
    [ scope "pinning equal values stores only one" $ do
        let b0 = ByteString.singleton 0
        let b1 = ByteString.copy b0

        board <- PinBoard.new

        -- pinning a thing for the first time returns it
        b0' <- PinBoard.pin board b0
        expectSamePointer b0 b0'

        -- pinning an equal thing returns the first
        b1' <- PinBoard.pin board b1
        expectSamePointer b0 b1'

        -- the board should only have one value in it
        expect' . (== 1) <$> io (PinBoard.debugSize board)

        -- keep b0 alive until here
        touch b0

        -- observe that the board doesn't keep its value alive
        io performGC
        expect' . (== 0) <$> io (PinBoard.debugSize board)

        ok
    ]

expectSamePointer :: a -> a -> Test ()
expectSamePointer x y =
  expect' (isTrue# (reallyUnsafePtrEquality# x y))

touch :: a -> Test ()
touch x =
  io (IO \s -> (# touch# x s, () #))


text:
<!doctype html>
<title>Crash test: asynchronously applying image content to image input</title>
<link rel="author" href="mailto:yuzhehan@chromium.org" title="Yu Han">
<link rel="help" href="https://crbug.com/1096002">
<style>
  .content { content: url(data:text/plain,aaa); }
</style>
<input id="input" type="image" class=content>
<script>
  onload = ()=> {
    document.body.offsetTop;
    input.setAttribute('class', '');
    document.body.offsetTop;
  }
</script>


text:
package io.fabric8.openclustermanagement.examples.cluster;

import io.fabric8.openclustermanagement.api.model.cluster.v1beta1.ManagedClusterSet;
import io.fabric8.openclustermanagement.api.model.cluster.v1beta1.ManagedClusterSetBuilder;
import io.fabric8.openclustermanagement.client.DefaultOpenClusterManagementClient;
import io.fabric8.openclustermanagement.client.OpenClusterManagementClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ManagedClusterSetCreate {
  private static final Logger logger = LoggerFactory.getLogger(ManagedClusterSetCreate.class.getSimpleName());

  public static void main(String[] args) {
    try (OpenClusterManagementClient ocmClient = new DefaultOpenClusterManagementClient()) {
      ManagedClusterSet managedClusterSet = new ManagedClusterSetBuilder()
        .withNewMetadata().withName("managedclusterset1").endMetadata()
        .withNewSpec()
        .endSpec()
        .build();
      logger.info("Creating ManagedClusterSet {}", managedClusterSet.getMetadata().getName());

      ocmClient.clusters().managedClusterSets().create(managedClusterSet);
    }
  }
}


text:
puts "Loading environment..."
require_relative '../../../dashboard/config/environment'
require 'dynamic_config/loaders/dcdo_loader'

puts "Updating config..."
DCDOLoader.load(ARGV[0])
puts "Done"


text:
@implementation MPLegacyPrintLaterJob

NSString * const kHPPPPrintLaterJobId = @"kHPPPPrintLaterJobId";
NSString * const kHPPPPrintLaterJobName = @"kHPPPPrintLaterJobName";
NSString * const kHPPPPrintLaterJobDate = @"kHPPPPrintLaterJobDate";
NSString * const kHPPPPrintLaterJobImages = @"kHPPPPrintLaterJobImages";
NSString * const kHPPPPrintLaterNumCopies = @"kHPPPPrintLaterNumCopies";
NSString * const kHPPPPrintLaterPageRange = @"kHPPPPrintLaterPageRange";
NSString * const kHPPPPrintLaterBlackAndWhite = @"kHPPPPrintLaterBlackAndWhite";
NSString * const kHPPPPrintLaterJobExtra = @"kHPPPPrintLaterJobExtra";

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super init]) {
        self.id = [decoder decodeObjectForKey:kHPPPPrintLaterJobId];
        self.name = [decoder decodeObjectForKey:kHPPPPrintLaterJobName];
        self.date = [decoder decodeObjectForKey:kHPPPPrintLaterJobDate];
        self.pageRange = [decoder decodeObjectForKey:kHPPPPrintLaterPageRange];
        self.printItems = [decoder decodeObjectForKey:kHPPPPrintLaterJobImages];
        self.extra = [decoder decodeObjectForKey:kHPPPPrintLaterJobExtra];
        NSNumber *numCopies = [decoder decodeObjectForKey:kHPPPPrintLaterNumCopies];
        self.numCopies = [numCopies integerValue];
        NSNumber *blackAndWhite = [decoder decodeObjectForKey:kHPPPPrintLaterBlackAndWhite];
        self.blackAndWhite = [blackAndWhite boolValue];
    }

    return self;
}

@end


text:
package osp

// TODO(pthatcher):
// - Read messages as well, and more than one

import (
	"context"
)

func SendMessageAsClient(ctx context.Context, hostname string, port int, msg interface{}) error {
	session, err := DialAsQuicClient(ctx, hostname, port)
	if err != nil {
		return err
	}
	stream, err := session.OpenStreamSync()
	if err != nil {
		return err
	}
	return WriteMessage(msg, stream)
}


text:
% This function classifies input images into Class 2 or Class 5 based on
% provided probability vectors using Bernaulli Maximum Aposteriori Classifier
%
% Parameters
% TestData: Matrix of N X 256
% probVectorClass2: Vector(256 x 1) contains probability P(Xi=1|C=2)
% probVectorClass5: Vector(256 x 1) contains probability P(Xi=1|C=5)
% prior: Scalar(1x1) contains P(C=2)
%
% Returns
% predictedLabels: Vector(N x 1) contains Label for each image

function [predictedLabels] = predictByBernoulliMAP(TestData, probVectorClass2, probVectorClass5, prior)

    [numOfImages,numOfPixels] = size(TestData);

    predictedLabels = zeros(numOfImages, 1);
    imageProbVectorClass2 = ones(numOfImages, 1);
    imageProbVectorClass5 = ones(numOfImages, 1);

    % Loop through each image vector to find its probablity in each class
    for i = 1:numOfImages
        % Calculating Bern([pixel1 pixel2... pixeln] | C=2) and
        % Bern([pixel1 pixel2... pixeln] | C=2)
        for j = 1:numOfPixels
           if TestData(i,j) == 1
               imageProbVectorClass2(i) = imageProbVectorClass2(i) * probVectorClass2(j);
               imageProbVectorClass5(i) = imageProbVectorClass5(i) * probVectorClass5(j);
           else
               imageProbVectorClass2(i) = imageProbVectorClass2(i) * (1-probVectorClass2(j));
               imageProbVectorClass5(i) = imageProbVectorClass5(i) * (1-probVectorClass5(j));
           end

        end

        % Classsify or predict the Label based on calculated probability
        if imageProbVectorClass2(i)*prior >= imageProbVectorClass5(i)*(1-prior)
            predictedLabels(i) = 2;
        else
            predictedLabels(i) = 5;
        end
    end
end


text:
NS_ASSUME_NONNULL_BEGIN

@interface QuickSpec (QuickSpec_MethodList)

+ (NSSet<NSString*> *)allSelectors;

@end

NS_ASSUME_NONNULL_END


text:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>greensnow25</groupId>
    <artifactId>Inharitance</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>
    <parent>
        <groupId>greensnow25</groupId>
        <artifactId>chapter2</artifactId>
        <version>1.0</version>

    </parent>

</project>