text:
app.StatsView = Backbone.View.extend({
    drawChart: function (data) {
        this.$('#chart_div').highcharts({

            chart: { type: 'column', width: $('#content').width() },
            title: { text: 'General Statistics' },
            xAxis: { categories: data.categories },
            yAxis: {
                allowDecimals: false,
                min: 0,
                title: { text: 'Number of keys' },
                stackLabels: {
                    enabled: true,
                    style: {
                        fontWeight: 'bold',
                        color: '#333'
                    },
                    formatter: function() {
                        return  this.stack.substr(0,2);
                    }
                }
            },
            tooltip: {
                formatter: function() {
                    return ''+ this.x +'
'+
                        this.series.name +': '+ this.y + '
'+
                        'Total: '+ this.point.stackTotal  +' (' + this.percentage.toFixed(2) + '%)';
                }
            },
            plotOptions: {
                column: { size:'100%', stacking: 'normal' }
            },
            legend: { enabled: false },
            series: data.series
        });
    },

    render:function () {
        this.$el.html(this.template());
        var self = this;
        $.getJSON('api/stats').success(function(data) {
            self.drawChart(data);
        });
        return this;
    }

});


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using osuTK;
using osuTK.Graphics;
using osu.Game.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Screens.Ranking;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
    public class DrawableSpinner : DrawableOsuHitObject
    {
        protected readonly Spinner Spinner;

        public readonly SpinnerDisc Disc;
        public readonly SpinnerTicks Ticks;
        private readonly SpinnerSpmCounter spmCounter;

        private readonly Container mainContainer;

        public readonly SpinnerBackground Background;
        private readonly Container circleContainer;
        private readonly CirclePiece circle;
        private readonly GlowPiece glow;

        private readonly SpriteIcon symbol;

        private readonly Color4 baseColour = OsuColour.FromHex(@"002c3c");
        private readonly Color4 fillColour = OsuColour.FromHex(@"005b7c");

        private readonly IBindable<Vector2> positionBindable = new Bindable<Vector2>();

        private Color4 normalColour;
        private Color4 completeColour;

        public DrawableSpinner(Spinner s)
            : base(s)
        {
            Origin = Anchor.Centre;
            Position = s.Position;

            RelativeSizeAxes = Axes.Both;

            // we are slightly bigger than our parent, to clip the top and bottom of the circle
            Height = 1.3f;

            Spinner = s;

            InternalChildren = new Drawable[]
            {
                circleContainer = new Container
                {
                    AutoSizeAxes = Axes.Both,
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Children = new Drawable[]
                    {
                        glow = new GlowPiece(),
                        circle = new CirclePiece
                        {
                            Position = Vector2.Zero,
                            Anchor = Anchor.Centre,
                        },
                        new RingPiece(),
                        symbol = new SpriteIcon
                        {
                            Anchor = Anchor.Centre,
                            Origin = Anchor.Centre,
                            Size = new Vector2(48),
                            Icon = FontAwesome.Asterisk,
                            Shadow = false,
                        },
                    }
                },
                mainContainer = new AspectContainer
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    RelativeSizeAxes = Axes.Y,
                    Children = new[]
                    {
                        Background = new SpinnerBackground
                        {
                            Alpha = 0.6f,
                            Anchor = Anchor.Centre,
                            Origin = Anchor.Centre,
                        },
                        Disc = new SpinnerDisc(Spinner)
                        {
                            Scale = Vector2.Zero,
                            Anchor = Anchor.Centre,
                            Origin = Anchor.Centre,
                        },
                        circleContainer.CreateProxy(),
                        Ticks = new SpinnerTicks
                        {
                            Anchor = Anchor.Centre,
                            Origin = Anchor.Centre,
                        },
                    }
                },
                spmCounter = new SpinnerSpmCounter
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Y = 120,
                    Alpha = 0
                }
            };
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            normalColour = baseColour;

            Background.AccentColour = normalColour;

            completeColour = colours.YellowLight.Opacity(0.75f);

            Disc.AccentColour = fillColour;
            circle.Colour = colours.BlueDark;
            glow.Colour = colours.BlueDark;

            positionBindable.BindValueChanged(pos => Position = pos.NewValue);
            positionBindable.BindTo(HitObject.PositionBindable);
        }

        public float Progress => MathHelper.Clamp(Disc.RotationAbsolute / 360 / Spinner.SpinsRequired, 0, 1);

        protected override void CheckForResult(bool userTriggered, double timeOffset)
        {
            if (Time.Current < HitObject.StartTime) return;

            if (Progress >= 1 && !Disc.Complete)
            {
                Disc.Complete = true;

                const float duration = 200;

                Disc.FadeAccent(completeColour, duration);

                Background.FadeAccent(completeColour, duration);
                Background.FadeOut(duration);

                circle.FadeColour(completeColour, duration);
                glow.FadeColour(completeColour, duration);
            }

            if (userTriggered || Time.Current < Spinner.EndTime)
                return;

            ApplyResult(r =>
            {
                if (Progress >= 1)
                    r.Type = HitResult.Great;
                else if (Progress > .9)
                    r.Type = HitResult.Good;
                else if (Progress > .75)
                    r.Type = HitResult.Meh;
                else if (Time.Current >= Spinner.EndTime)
                    r.Type = HitResult.Miss;
            });
        }

        protected override void Update()
        {
            Disc.Tracking = OsuActionInputManager?.PressedActions.Any(x => x == OsuAction.LeftButton || x == OsuAction.RightButton) ?? false;
            if (!spmCounter.IsPresent && Disc.Tracking)
                spmCounter.FadeIn(HitObject.TimeFadeIn);

            base.Update();
        }

        protected override void UpdateAfterChildren()
        {
            base.UpdateAfterChildren();

            circle.Rotation = Disc.Rotation;
            Ticks.Rotation = Disc.Rotation;
            spmCounter.SetRotation(Disc.RotationAbsolute);

            float relativeCircleScale = Spinner.Scale * circle.DrawHeight / mainContainer.DrawHeight;
            Disc.ScaleTo(relativeCircleScale + (1 - relativeCircleScale) * Progress, 200, Easing.OutQuint);

            symbol.RotateTo(Disc.Rotation / 2, 500, Easing.OutQuint);
        }

        protected override void UpdatePreemptState()
        {
            base.UpdatePreemptState();

            circleContainer.ScaleTo(Spinner.Scale * 0.3f);
            circleContainer.ScaleTo(Spinner.Scale, HitObject.TimePreempt / 1.4f, Easing.OutQuint);

            Disc.RotateTo(-720);
            symbol.RotateTo(-720);

            mainContainer
                .ScaleTo(0)
                .ScaleTo(Spinner.Scale * circle.DrawHeight / DrawHeight * 1.4f, HitObject.TimePreempt - 150, Easing.OutQuint)
                .Then()
                .ScaleTo(1, 500, Easing.OutQuint);
        }

        protected override void UpdateCurrentState(ArmedState state)
        {
            var sequence = this.Delay(Spinner.Duration).FadeOut(160);

            switch (state)
            {
                case ArmedState.Idle:
                    Expire(true);
                    break;
                case ArmedState.Hit:
                    sequence.ScaleTo(Scale * 1.2f, 320, Easing.Out);
                    break;
                case ArmedState.Miss:
                    sequence.ScaleTo(Scale * 0.8f, 320, Easing.In);
                    break;
            }

            Expire();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.klarna.hiverunner;

import com.klarna.hiverunner.annotations.HiveSQL;
import com.klarna.hiverunner.annotations.HiveSetupScript;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.Arrays;
import java.util.List;

@RunWith(StandaloneHiveRunner.class)
public class UserDefinedFunctionTest {

    private final String hdfsSource = "${hiveconf:hadoop.tmp.dir}/udf";

    @HiveSetupScript
    String setup =
            "  CREATE TABLE udf_test (" +
                    " id int," +
                    " value string" +
                    "  )" +
                    "  ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'" +
                    "  STORED AS TEXTFILE" +
                    "  LOCATION '" + hdfsSource + "' ";

    @HiveSQL(files = {}, autoStart = false)
    public HiveShell hiveShell;

    @Test
    public void udfMax() {
        hiveShell.addResource(hdfsSource + "/data.csv",
                "123\tv1\n" +
                        "124\tv2\n" +
                        "125\tv3");
        hiveShell.start();
        Assert.assertEquals(Arrays.asList("125"), hiveShell.executeQuery("SELECT max(id) FROM udf_test"));
    }

    @Test
    public void udfMin() {
        hiveShell.addResource(hdfsSource + "/data.csv",
                "123\tv1\n" +
                        "124\tv2\n" +
                        "125\tv3");
        hiveShell.start();
        Assert.assertEquals(Arrays.asList("123"), hiveShell.executeQuery("SELECT min(id) FROM udf_test"));
    }

    @Test
    public void regexp_extract() {
        hiveShell.addResource(hdfsSource + "/data.csv", "1\t123ABC");
        hiveShell.start();
        List<String> expected = Arrays.asList("123");
        List<String> actual = hiveShell.executeQuery("SELECT regexp_extract(value, '([0-9]*)[A-Z]*', 1) FROM udf_test");
        Assert.assertEquals(expected, actual);
    }

}


text:
namespace documentapi {

PutDocumentMessage::PutDocumentMessage() :
    TestAndSetMessage(),
    _document(),
    _time(0)
{}

PutDocumentMessage::PutDocumentMessage(document::Document::SP document) :
    TestAndSetMessage(),
    _document(),
    _time(0)
{
    setDocument(std::move(document));
}

PutDocumentMessage::~PutDocumentMessage() = default;

DocumentReply::UP
PutDocumentMessage::doCreateReply() const
{
    return std::make_unique<WriteDocumentReply>(DocumentProtocol::REPLY_PUTDOCUMENT);
}

bool
PutDocumentMessage::hasSequenceId() const
{
    return true;
}

uint64_t
PutDocumentMessage::getSequenceId() const
{
    return *reinterpret_cast<const uint64_t*>(_document->getId().getGlobalId().get());
}

uint32_t
PutDocumentMessage::getType() const
{
    return DocumentProtocol::MESSAGE_PUTDOCUMENT;
}

void
PutDocumentMessage::setDocument(document::Document::SP document)
{
    if ( ! document ) {
        throw vespalib::IllegalArgumentException("Document can not be null.", VESPA_STRLOC);
    }
    _document = std::move(document);
}

}


text:
#import <BaiduMapAPI_Base/BMKTypes.h>

/// 云检索结果列表类
@interface BMKCloudPOIList : NSObject {
    NSInteger               _status;
    NSInteger               _total;
    NSInteger               _size;
    NSInteger               _pageNum;
    NSArray                 *_POIs;

}
///搜索状态
@property (nonatomic, assign) NSInteger     status;
///结果总数
@property (nonatomic, assign) NSInteger     total;
///当前页返回数量
@property (nonatomic, assign) NSInteger     size;
///页数
@property (nonatomic, assign) NSInteger     pageNum;
///POI结果列表
@property (nonatomic, strong) NSArray       *POIs;

@end

/// 云检索结果信息类
@interface BMKCloudPOIInfo : NSObject {
    int             _uid;
    int             _geotableId;
    NSString        *_title;
    NSString        *_address;
    NSString        *_province;
    NSString        *_city;
    NSString        *_district;
    float           _latitude;
    float           _longitude;
    NSString        *_tags;
    float           _distance;
    float           _weight;
    NSMutableDictionary *_customDict;
    int             _creattime;
    int             _modifytime;
    int             _type;

}
///poi数据id
@property (nonatomic, assign) int             uid;
///所属table的id
@property (nonatomic, assign) int             geotableId;
///poi名称
@property (nonatomic, strong) NSString        *title;
///poi地址
@property (nonatomic, strong) NSString        *address;
///poi所属省
@property (nonatomic, strong) NSString        *province;
///poi所属城市
@property (nonatomic, strong) NSString        *city;
///poi所属区县
@property (nonatomic, strong) NSString        *district;
///poi所处位置的纬度
@property (nonatomic, assign) float           latitude;
///poi所处位置的经度
@property (nonatomic, assign) float           longitude;
///poi标签
@property (nonatomic, strong) NSString        *tags;
///poi距离
@property (nonatomic, assign) float           distance;
///权重
@property (nonatomic, assign) float           weight;
///自定义列
@property (nonatomic, strong) NSMutableDictionary *customDict;
///创建时间
@property (nonatomic, assign) int             creattime;
///修改时间
@property (nonatomic, assign) int             modifytime;
///类型
@property (nonatomic, assign) int             type;
///处于位置点的方向
@property (nonatomic, strong) NSString        *direction;
@end

/// 云检索结果百度地图POI信息类
@interface BMKCloudMapPOIInfo : NSObject

///poi名称
@property (nonatomic, strong) NSString *name;
///poi uid
@property (nonatomic, strong) NSString *uid;
///POI坐标
@property (nonatomic, assign) CLLocationCoordinate2D pt;
///poi地址
@property (nonatomic, strong) NSString *address;
///poi标签
@property (nonatomic, strong) NSString *tags;
///poi距离
@property (nonatomic, assign) CGFloat distance;
///处于位置点的方向
@property (nonatomic, strong) NSString* direction;
@end

/// 云RGC检索结果类
@interface BMKCloudReverseGeoCodeResult : NSObject

///层次化地址信息
@property (nonatomic, strong) BMKAddressComponent* addressDetail;
///地址名称
@property (nonatomic, strong) NSString* address;
///地址坐标
@property (nonatomic) CLLocationCoordinate2D location;
///用户定义位置描述
@property (nonatomic, strong) NSString* customLocationDescription;
///推荐的位置描述(结合poiList和customPoiList计算推荐结果)
@property (nonatomic, strong) NSString* recommendedLocationDescription;
///地址周边百度地图POI信息,成员类型为BMKCloudMapPOIInfo
@property (nonatomic, strong) NSArray* poiList;
///地址周边POI信息,成员类型为BMKCloudPOIInfo
@property (nonatomic, strong) NSArray* customPoiList;

@end


text:
<?xml version='1.0' encoding='utf-8'?>
<Jobs>
  <ApplicationJob xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Guid="1e0cec11-33ea-4845-9314-49f00f363332">
    <WebsiteUrl />
    <UserAgent />
    <UserNotes />
    <LastFileSize>12530872</LastFileSize>
    <LastFileDate>2015-11-14T18:13:25+01:00</LastFileDate>
    <IgnoreFileInformation>false</IgnoreFileInformation>
    <DownloadBeta>Default</DownloadBeta>
    <DownloadDate xsi:nil="true" />
    <CheckForUpdatesOnly>false</CheckForUpdatesOnly>
    <VariableChangeIndicator />
    <CanBeShared>true</CanBeShared>
    <ShareApplication>false</ShareApplication>
    <ExclusiveDownload>false</ExclusiveDownload>
    <HttpReferer />
    <SetupInstructions />
    <Variables>
      <item>
        <key>
          <string>version</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>RegularExpression</VariableType>
            <Regex>MPC-HC_v([\d\.]+)_x64</Regex>
            <Url>https://mpc-hc.org/downloads/</Url>
            <StartText><tr title="MPC-HC_v</StartText>
            <EndText>_x86" class="folder</EndText>
            <TextualContent />
            <Name>version</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>url64</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>https://binaries.mpc-hc.org/MPC HomeCinema - x64/MPC-HC_v{version}_x64/MPC-HC.{version}.x64.exe</TextualContent>
            <Name>url64</Name>
          </UrlVariable>
        </value>
      </item>
    </Variables>
    <ExecuteCommand />
    <ExecutePreCommand />
    <ExecuteCommandType>Batch</ExecuteCommandType>
    <ExecutePreCommandType>Batch</ExecutePreCommandType>
    <Category />
    <SourceType>FixedUrl</SourceType>
    <PreviousLocation>C:\Chocolatey\_work\MPC-HC.1.7.10.x86.exe</PreviousLocation>
    <DeletePreviousFile>true</DeletePreviousFile>
    <Enabled>true</Enabled>
    <FileHippoId />
    <LastUpdated>2015-11-24T22:08:08.7470967+01:00</LastUpdated>
    <TargetPath>C:\Chocolatey\_work\</TargetPath>
    <FixedDownloadUrl>https://binaries.mpc-hc.org/MPC HomeCinema - Win32/MPC-HC_v{version}_x86/MPC-HC.{version}.x86.exe</FixedDownloadUrl>
    <Name>mpc-hc</Name>
  </ApplicationJob>
</Jobs>


text:
<?php namespace Redub\Database\PDO
{
	use Redub\Database;
	use Dotink\Flourish;

	use PDOStatement;
	use PDO;

	/**
	 * A PDO Result
	 *
	 */
	class Result implements Database\ResultInterface
	{
		/**
		 *
		 */
		protected $count = 0;

		/**
		 *
		 */
		protected $result = NULL;

		/**
		 *
		 */
		protected $rows = array();

		/**
		 *
		 */
		public function __construct(PDOStatement $result, $count = 0)
		{
			$this->result = $result;
			$this->count  = $count;

			$this->fetchRow();
		}

		/**
		 *
		 */
		public function count()
		{
			return $this->count;
		}

		/**
		 * Gets the row currently pointed to by the cursor
		 */
 		public function current()
		{
			return current($this->rows);
		}

		/**
		 * Gets the row at a given index.
		 */
		public function get($index)
		{
			if (!is_int($index) || $index < 0) {
				throw new Flourish\ProgrammerException(
					'Cannot get element at index "%s", only positive integer indexes are supported',
					$index
				);
			}

			if ($index >= $this->count) {
				return NULL;
			}

			if (!isset($this->rows[$index])) {
				while (count($this->rows) < $index + 1) {
					$this->rows[] = $this->result->fetch(PDO::FETCH_ASSOC);
				}
			}

			return $this->rows[$index];
		}

		/**
		 * Gets the index of the row currently pointed to by the cursor
		 */
		public function key()
		{
			return key($this->rows);
		}

		/**
		 * Increments the cursor position in the result set
		 */
		public function next()
		{
			if ($this->key() < ($this->count - 1)) {
				$this->fetchRow();
			}

			next($this->rows);
		}

		/**
		 *
		 */
		public function rewind()
		{
			reset($this->rows);
		}

		/**
		 *
		 */
		public function valid()
		{
			return $this->current() !== FALSE;
		}

		/**
		 *
		 */
		protected function fetchRow()
		{
			if ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
				$this->rows[] = $row;
			}
		}
	}
}


text:
package uk.ac.ox.zoo.seeg.abraid.mp.dataacquisition.acquirers.healthmap;

import org.joda.time.DateTime;
import org.junit.Test;
import uk.ac.ox.zoo.seeg.abraid.mp.dataacquisition.acquirers.healthmap.domain.HealthMapAlert;

import java.util.Arrays;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class HealthMapAlertValidatorTest {
    @Test
    public void alertWithNoDiseaseIdsIsInvalid() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseases(Arrays.asList("Disease 1", "Disease 2"));
        actAndAssertMessage(alert, "Missing disease IDs in HealthMap alert (alert ID 5)");
    }

    @Test
    public void alertWithDiseaseIdMissingInListIsInvalid() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseaseIds(Arrays.asList("123", null, "456"));
        alert.setDiseases(Arrays.asList("Disease 1", "Disease 2", "Disease 3"));
        actAndAssertMessage(alert, "Missing disease ID within list in HealthMap alert (alert ID 5)");
    }

    @Test
    public void alertWithNoDiseaseNamesIsInvalid() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseaseIds(Arrays.asList("123", "456"));
        actAndAssertMessage(alert, "Missing diseases in HealthMap alert (alert ID 5)");
    }

    @Test
    public void alertWithDiseaseIdCountNotEqualToDiseaseNameCountIsInvalid() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseaseIds(Arrays.asList("123", "456"));
        alert.setDiseases(Arrays.asList("Disease 1", "Disease 2", "Disease 3"));
        actAndAssertMessage(alert, "HealthMap alert has 2 disease ID(s) but 3 disease name(s) (alert ID 5)");
    }

    @Test
    public void alertWithAPlaceCategoryToIgnoreIsInvalid() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseaseId("123");
        alert.setDisease("Test name");
        alert.setPlaceCategories(Arrays.asList("Farm hatchery", "imported Case"));
        actAndAssertMessage(alert, "Ignoring HealthMap alert because it has place category \"imported Case\" (alert ID 5)");
    }

    @Test
    public void alertWithAPlaceCategoryToIgnoreIsInvalid2() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseaseId("123");
        alert.setDisease("Test name");
        alert.setPlaceCategories(Arrays.asList("  Vaccine-associated Paralytic Poliomyelitis   "));
        actAndAssertMessage(alert, "Ignoring HealthMap alert because it has place category \"Vaccine-associated Paralytic Poliomyelitis\" (alert ID 5)");
    }

    @Test
    public void alertWithOtherPlaceCategoriesIsValid() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseaseId("123");
        alert.setDisease("Test name");
        alert.setPlaceCategories(Arrays.asList("Farm hatchery", "Some other category"));
        actAndAssertMessage(alert, null);
    }

    @Test
    public void alertWithNoDateIsInvalid() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseaseId("123");
        alert.setDisease("Test name");
        alert.setDate(null);
        actAndAssertMessage(alert, "Missing date in HealthMap alert (alert ID 5)");
    }

    @Test
    public void alertWithNoFeedIsInvalid() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseaseId("123");
        alert.setDisease("Test name");
        alert.setFeed(null);
        actAndAssertMessage(alert, "Missing feed in HealthMap alert (alert ID 5)");
    }

    @Test
    public void alertWithNoFeedIdIsInvalid() {
        HealthMapAlert alert = createHealthMapAlert(5);
        alert.setDiseaseId("123");
        alert.setDisease("Test name");
        alert.setFeedId(null);
        actAndAssertMessage(alert, "Missing feed ID in HealthMap alert (alert ID 5)");
    }

    private HealthMapAlert createHealthMapAlert(int alertId) {
        HealthMapAlert alert = new HealthMapAlert();
        alert.setLink("http://healthmap.org/ln.php?" + alertId);
        alert.setDate(DateTime.now());
        alert.setFeed("ProMed Mail");
        alert.setFeedId("1");
        return alert;
    }

    private void actAndAssertMessage(HealthMapAlert alert, String expectedMessage) {
        List<String> placeCategoriesToIgnore = Arrays.asList("imported case", "vaccine-associated paralytic poliomyelitis");
        HealthMapAlertValidator validator = new HealthMapAlertValidator(alert, placeCategoriesToIgnore);
        String message = validator.validate();
        assertThat(message).isEqualTo(expectedMessage);
    }
}


text:
package org.onosproject.lisp.ctl.impl;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.AbstractChannel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * Bootstraps LISP netty channel, handles all setup and network listeners.
 */
public class LispControllerBootstrap {

    private static final Logger log = LoggerFactory.getLogger(LispControllerBootstrap.class);

    private static final int LISP_DATA_PORT = 4341;
    private static final int LISP_CONTROL_PORT = 4342;

    // Configuration options
    protected List<Integer> lispPorts = ImmutableList.of(LISP_DATA_PORT, LISP_CONTROL_PORT);

    private EventLoopGroup eventLoopGroup;
    private Class<? extends AbstractChannel> channelClass;
    private List<ChannelFuture> channelFutures = Lists.newArrayList();

    /**
     * Stitches all channel handlers into server bootstrap.
     */
    private void run() {

        try {
            final Bootstrap bootstrap = createServerBootstrap();

            configBootstrapOptions(bootstrap);

            lispPorts.forEach(p -> {
                InetSocketAddress sa = new InetSocketAddress(p);
                channelFutures.add(bootstrap.bind(sa));
                log.info("Listening for LISP router connections on {}", sa);
            });

            for (ChannelFuture f : channelFutures) {
                f.sync();
            }

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * Initializes server bootstrap with given LISP channel initializer.
     *
     * @return initialized server bootstrap
     */
    private Bootstrap createServerBootstrap() {
        Bootstrap bootstrap = new Bootstrap();

        initEventLoopGroup();
        bootstrap.group(eventLoopGroup)
                .channel(channelClass)
                .handler(new LispChannelInitializer());

        return bootstrap;
    }

    /**
     * Configures bootstrap options to tune the communication performance.
     *
     * @param bootstrap LISP server bootstrap
     */
    private void configBootstrapOptions(Bootstrap bootstrap) {
        bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    /**
     * Closes all open channels.
     *
     * @param channelFutures a collection of channel futures
     */
    private void closeChannels(List<ChannelFuture> channelFutures) {
        try {
            for (ChannelFuture f : channelFutures) {
                f.channel().closeFuture().sync();
            }
        } catch (InterruptedException e) {
            log.warn("Failed to close channels. Reasons: {}.", e.getMessage());
        }
    }

    /**
     * Initializes event loop group.
     */
    private void initEventLoopGroup() {

        // try to use EpollEventLoopGroup if possible,
        // if OS does not support native Epoll, fallback to use netty NIO
        try {
            eventLoopGroup = new EpollEventLoopGroup();
            channelClass = EpollDatagramChannel.class;
        } catch (NoClassDefFoundError e) {
            log.debug("Failed to initialize native (epoll) transport. "
                        + "Reason: {}. Proceeding with NIO event group.", e);
        }
        eventLoopGroup = new NioEventLoopGroup();
        channelClass = NioDatagramChannel.class;
    }

    /**
     * Launches LISP controller to listen control channel.
     */
    public void start() {
        log.info("Starting LISP control I/O");

        this.run();
    }

    /**
     * Terminates LISP controller and lease all occupied resources.
     */
    public void stop() {
        log.info("Stopping LISP control I/O");

        try {
            // try to shutdown all open event groups
            eventLoopGroup.shutdownGracefully().sync();
            closeChannels(channelFutures);
        } catch (InterruptedException e) {
            log.warn("Failed to stop LISP controller. Reasons: {}.", e.getMessage());
        }
    }
}


text:
package com.thinkbiganalytics.nifi.provenance.model.util;

import com.thinkbiganalytics.nifi.provenance.model.ProvenanceEventRecordDTO;
import com.thinkbiganalytics.nifi.provenance.model.stats.AggregatedFeedProcessorStatistics;
import com.thinkbiganalytics.nifi.provenance.model.stats.AggregatedFeedProcessorStatisticsHolder;
import com.thinkbiganalytics.nifi.provenance.model.stats.AggregatedFeedProcessorStatisticsHolderV3;
import com.thinkbiganalytics.nifi.provenance.model.stats.AggregatedFeedProcessorStatisticsV2;
import com.thinkbiganalytics.nifi.provenance.model.stats.AggregatedProcessorStatistics;
import com.thinkbiganalytics.nifi.provenance.model.stats.AggregatedProcessorStatisticsV2;
import com.thinkbiganalytics.nifi.provenance.model.stats.GroupedStats;
import com.thinkbiganalytics.nifi.provenance.model.stats.GroupedStatsIdentity;
import com.thinkbiganalytics.nifi.provenance.model.stats.GroupedStatsV2;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class GroupedStatsUtil {

    /**
     * Add stats2 to stats1 and modify stats1
     *
     * @param stats1 stats to modify
     * @param stats2 stats to add
     */
    public static void addStats1(GroupedStats stats1, GroupedStats stats2) {
        stats1.addTotalCount(stats2.getTotalCount());
        stats1.addBytesIn(stats2.getBytesIn());
        stats1.addBytesOut(stats2.getBytesOut());
        stats1.addDuration(stats2.getDuration());
        stats1.addProcessorsFailed(stats2.getProcessorsFailed());
        stats1.addJobsStarted(stats2.getJobsStarted());
        stats1.addJobsFinished(stats2.getJobsFinished());
        stats1.addJobDuration(stats2.getJobDuration());
        stats1.addJobsFailed(stats2.getJobsFailed());
        stats1.addSuccessfulJobDuration(stats2.getSuccessfulJobDuration());
        stats1.setMaxTime(stats1.getMaxTime() == null || stats1.getMaxTime() < stats2.getMaxTime() ? stats2.getMaxTime() : stats1.getMaxTime());
        stats1.setMinTime(stats1.getMinTime() == null || stats1.getMinTime() > stats2.getMinTime() ? stats2.getMinTime() : stats1.getMinTime());
        stats1.setTime(stats1.getMinTime());
        if (stats1 instanceof GroupedStatsV2 && stats2 instanceof GroupedStatsV2) {
            if (((GroupedStatsV2) stats1).getLatestFlowFileId() == null && ((GroupedStatsV2) stats2).getLatestFlowFileId() != null) {
                ((GroupedStatsV2) stats1).setLatestFlowFileId(((GroupedStatsV2) stats2).getLatestFlowFileId());
            }
        }
    }

    /**
     * Add 2 stats together and return a new stats object
     *
     * @param stats1 stats object
     * @param stats2 stats object
     * @return a new stats object
     */
    public static GroupedStats add(GroupedStats stats1, GroupedStats stats2) {
        GroupedStats stats = new GroupedStats();
        addStats1(stats, stats1);
        addStats1(stats, stats2);
        return stats;
    }

    /**
     * Add a list of stats together and return a new object
     *
     * @param groupedStats stats
     * @return new stats
     */
    public static GroupedStats add(GroupedStats... groupedStats) {
        GroupedStats allStats = new GroupedStats();
        for (GroupedStats stats : groupedStats) {
            addStats1(allStats, stats);
        }
        return allStats;
    }

    /**
     * Add a list of stats together and return a new object
     *
     * @param groupedStats stats to add
     * @return a new stats object
     */
    public static GroupedStats add(List<GroupedStats> groupedStats) {
        return add(groupedStats.toArray(new GroupedStats[groupedStats.size()]));
    }

    public static GroupedStats add(GroupedStats stats, ProvenanceEventRecordDTO event) {
        Long eventId = event.getEventId();
        if (stats instanceof GroupedStatsV2) {
            ((GroupedStatsV2) stats).setLatestFlowFileId(event.getFlowFileUuid());
        }
        stats.addTotalCount(1L);
        stats.addBytesIn(event.getInputContentClaimFileSizeBytes() != null ? event.getInputContentClaimFileSizeBytes() : 0L);
        stats.addBytesOut(event.getOutputContentClaimFileSizeBytes() != null ? event.getOutputContentClaimFileSizeBytes() : 0L);
        //reset the duration
        stats.addDuration(event.getEventDuration());
        stats.setSourceConnectionIdentifier(event.getSourceConnectionIdentifier());

        if (event.isFailure()) {
            stats.addProcessorsFailed(1L);

        }
        if (event.isStartOfJob()) {
            stats.addJobsStarted(1L);
        }
     /*
        if (event.isFinalJobEvent()) {
            stats.addJobsFinished(1L);
            Long jobTime = FeedEventStatistics.getInstance().getFeedFlowFileDuration(event);
            stats.addJobDuration(jobTime);
            if (FeedEventStatistics.getInstance().hasFailures(event)) {
                stats.addJobsFailed(1L);
            } else {
                stats.addSuccessfulJobDuration(jobTime);
                //count successful jobs?
            }

        }
        */
        stats.setTime(event.getEventTime());

        if (stats.getMinTime() == null) {
            stats.setMinTime(event.getEventTime());
        }

        if (stats.getMaxTime() == null) {
            stats.setMaxTime(event.getEventTime());
        }
        if (event.getEventTime() > stats.getMaxTime()) {
            stats.setMaxTime(event.getEventTime());
        }
        if (event.getEventTime() < stats.getMinTime()) {
            stats.setMinTime(event.getEventTime());
        }

        if (Math.abs(stats.getMaxEventId()) < Math.abs(eventId)) {
            stats.setMaxEventId(eventId);
        }

        return stats;

    }

    /**
     * Group stats together by processor for a given feed
     *
     * @param feedName     feed name
     * @param groupedStats Map of processorIdentity to list of stats for that processor
     */
    public static AggregatedFeedProcessorStatistics groupStatsByProcessor(String feedName, Map<GroupedStatsIdentity, List<GroupedStats>> groupedStats) {
        Long sendJmsTimeMillis = 3000L;
        String collectionId = UUID.randomUUID().toString();

        //Create a random id for the starting processor.
        //the starting feed processor id is not needed as we already know the feed name associated with these stats
        String startingProcessorId = UUID.randomUUID().toString();
        AggregatedFeedProcessorStatisticsV2
            feedProcessorStatistics = new AggregatedFeedProcessorStatisticsV2(startingProcessorId, collectionId, sendJmsTimeMillis);
       feedProcessorStatistics.setFeedName(feedName);

        for (Map.Entry<GroupedStatsIdentity, List<GroupedStats>> stats : groupedStats.entrySet()) {
            String processorName = stats.getKey().getProcessorName();
            String processorId = stats.getKey().getProcessorId();

            Map<String, AggregatedProcessorStatistics> processorStatsMap = feedProcessorStatistics.getProcessorStats();
            if (!processorStatsMap.containsKey(processorName)) {
                processorStatsMap.put(processorName, new AggregatedProcessorStatisticsV2(processorId, processorName, collectionId));
            }
            AggregatedProcessorStatistics
                processorStatistics = processorStatsMap.get(processorName);

            for (GroupedStats s : stats.getValue()) {
                GroupedStatsUtil.addStats1(processorStatistics.getStats(GroupedStats.DEFAULT_SOURCE_CONNECTION_ID), s);
            }
           /*
            AggregatedProcessorStatistics
                processorStatistics =
                feedProcessorStatistics.getProcessorStats()
                    .computeIfAbsent(processorName, k -> new AggregatedProcessorStatisticsV2(processorId, k, collectionId));

            stats.getValue().stream().forEach( s ->  GroupedStatsUtil.add(processorStatistics.getStats(GroupedStats.DEFAULT_SOURCE_CONNECTION_ID), s));
            */

        }
        return feedProcessorStatistics;

    }

    /**
     * Gather feed stats for a list of events
     */
    public static AggregatedFeedProcessorStatisticsHolder gatherStats(final List<ProvenanceEventRecordDTO> events) {
        Map<String, Map<GroupedStatsIdentity, List<GroupedStats>>> feedStatsByProcessor = new ConcurrentHashMap<>();

        //events.stream().forEach(e -> {
        for (ProvenanceEventRecordDTO e : events) {

            if (!feedStatsByProcessor.containsKey(e.getFeedName())) {
                feedStatsByProcessor.put(e.getFeedName(), new ConcurrentHashMap<GroupedStatsIdentity, List<GroupedStats>>());
            }
            // feedStatsByProcessor.putIfAbsent(e.getFeedName(), );

            Map<GroupedStatsIdentity, List<GroupedStats>> feedStats = feedStatsByProcessor.get(e.getFeedName());

            GroupedStatsIdentity identity = new GroupedStatsIdentity(e.getComponentId(), e.getComponentName());
            if (!feedStats.containsKey(identity)) {
                feedStats.put(identity, new ArrayList<GroupedStats>());
            }
            //feedStats.putIfAbsent(identity, new ArrayList<>());

            List<GroupedStats> feedProcessorStats = feedStats.get(identity);

            //Add the new stats
            GroupedStats statsV2 = GroupedStatsUtil.add(new GroupedStatsV2(), e);
            feedProcessorStats.add(statsV2);

        }
        //);

        List<AggregatedFeedProcessorStatistics> statsList = new ArrayList<>();

        for (Map.Entry<String, Map<GroupedStatsIdentity, List<GroupedStats>>> feedStats : feedStatsByProcessor.entrySet()) {
            AggregatedFeedProcessorStatistics feedProcessorStatistics = GroupedStatsUtil.groupStatsByProcessor(feedStats.getKey(), feedStats.getValue());
            statsList.add(feedProcessorStatistics);
        }
       /* feedStatsByProcessor.entrySet().stream().forEach(feedStats -> {
            AggregatedFeedProcessorStatistics feedProcessorStatistics = GroupedStatsUtil.groupStatsByProcessor(feedStats.getKey(), feedStats.getValue());
            statsList.add(feedProcessorStatistics);
        });
        */
        AggregatedFeedProcessorStatisticsHolderV3 feedProcessorStatisticsHolderV3 = new AggregatedFeedProcessorStatisticsHolderV3();
        feedProcessorStatisticsHolderV3.setFeedStatistics(statsList);
        return feedProcessorStatisticsHolderV3;
    }

}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInita565044099f695d0d8b0b98efe177e7e::getLoader();


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe "is_tagger" do
  context "Tagger Method Generation" do

    before(:each) do
      @tagger = TaggableUser.new()
    end

    it "should add #is_tagger? query method to the class-side" do
      TaggableUser.should respond_to(:is_tagger?)
    end

    it "should return true from the class-side #is_tagger?" do
      TaggableUser.is_tagger?.should be_true
    end

    it "should return false from the base #is_tagger?" do
      ActiveRecord::Base.is_tagger?.should be_false
    end

    it "should add #is_tagger? query method to the singleton" do
      @tagger.should respond_to(:is_tagger?)
    end

    it "should add #tag method on the instance-side" do
      @tagger.should respond_to(:tag)
    end

    it "should generate an association for #owned_taggings and #owned_tags" do
      @tagger.should respond_to(:owned_taggings)
    end
  end

  describe "#tag" do
    context 'when called with a non-existent tag context' do
      before(:each) do
        @tagger = TaggableUser.new()
        @taggable = TaggableModel.new(:name=>"Richard Prior")
      end

      it "should by default not throw an exception " do
        @taggable.tag_list_on(:foo).should be_empty
        lambda {
          @tagger.tag(@taggable, :with=>'this, and, that', :on=>:foo)
        }.should_not raise_error
      end

      it 'should by default create the tag context on-the-fly' do
        @taggable.tag_list_on(:here_ond_now).should be_empty
        @tagger.tag(@taggable, :with=>'that', :on=>:here_ond_now)
        @taggable.tag_list_on(:here_ond_now).should include('that')
      end

      it "should throw an exception when the default is over-ridden" do
        @taggable.tag_list_on(:foo_boo).should be_empty
        lambda {
          @tagger.tag(@taggable, :with=>'this, and, that', :on=>:foo_boo, :force=>false)
        }.should raise_error
      end

      it "should not create the tag context on-the-fly when the default is over-ridden" do
        @taggable.tag_list_on(:foo_boo).should be_empty
        @tagger.tag(@taggable, :with=>'this, and, that', :on=>:foo_boo, :force=>false) rescue
        @taggable.tag_list_on(:foo_boo).should be_empty
      end

    end

  end

end


text:
using Aliyun.OSS;
using Kooboo.CMS.Content.Models;
using Kooboo.CMS.Content.Persistence.AliyunOSS.Utilities;
using Kooboo.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kooboo.CMS.Content.Persistence.AliyunOSS
{
    public static class OssClientExtensions
    {
        public static ObjectListing ListBlobsWithPrefix(this OssClient client, string bucket, string prefix)
        {
            return client.ListObjects(bucket, prefix);
        }

        public static IEnumerable<OssObjectSummary> ListBlobsInFolder(this OssClient client,
            string bucket,
            MediaFolder folder)
        {
            var folderPath = MediaPathUtility.FolderPath(folder.FullName, folder.Repository.Name);
            return client
                .ListObjects(new ListObjectsRequest(bucket)
                {
                    Delimiter = "/",
                    Prefix = folderPath
                })
                .ObjectSummaries
                .Where(it => !it.Key.EndsWith("/"));
        }

        //public static byte[] GetObjectData(this OssClient client, string bucket, string key)
        //{
        //    if (!client.DoesObjectExist(bucket, key))
        //    {
        //        return new byte[] { };
        //    }
        //    var obj = client.GetObject(bucket, key);
        //    using (var requestStream = obj.Content)
        //    {
        //        using (var fs = new MemoryStream())
        //        {
        //            int length = 4 * 1024;
        //            var buf = new byte[length];
        //            do
        //            {
        //                length = requestStream.Read(buf, 0, length);
        //                fs.Write(buf, 0, length);
        //            } while (length != 0);
        //            fs.Flush();
        //            fs.Position = 0;
        //            return fs.ReadData();
        //        }
        //    }
        //}
    }
}


text:
namespace BookingApp.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ManagerIsBanned : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.AppUsers", "IsBanned", c => c.Boolean(nullable: false));
        }

        public override void Down()
        {
            DropColumn("dbo.AppUsers", "IsBanned");
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mem. Amer. Acad. Arts 16: 198 (1931)

#### Original name
Corethromyces gracilicaulis Thaxt.

### Remarks
null


text:
using VisualRecognition.ViewModels;
using WatsonServices.Models.VisualRecognition;

namespace VisualRecognition.Mappers
{
    internal static class ImageFaceMapper
    {
        internal static ImageFaceViewModel Map(ImageFace fromModel)
        {
            if (fromModel == null)
                return null;

            var toModel = new ImageFaceViewModel();
            toModel.Age = ImageFaceAgeMapper.Map(fromModel.Age);
            toModel.Gender = ImageFaceGenderMapper.Map(fromModel.Gender);
            toModel.Identity = ImageFaceIdentityMapper.Map(fromModel.Identity);
            toModel.Location = ImageLocationMapper.Map(fromModel.Location);
            return toModel;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  Wildfly Camel :: Example :: Camel CXF
  %%
  Copyright (C) 2013 - 2014 RedHat
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.wildfly.camel.example</groupId>
        <artifactId>example-camel</artifactId>
        <version>12.1.0-SNAPSHOT</version>
    </parent>

    <name>Wildfly Camel :: Example :: Camel CXF JAX-WS Secure</name>

    <artifactId>example-camel-cxf-jaxws-secure</artifactId>
    <packaging>war</packaging>

    <dependencies>

        <!-- Provided -->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.ejb</groupId>
            <artifactId>jboss-ejb-api_3.2_spec</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.servlet</groupId>
            <artifactId>jboss-servlet-api_4.0_spec</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <!-- Build -->
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <configuration>
                    <skip>${deploy.skip}</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>wildfly-cli-before-deploy</id>
                        <phase>install</phase>
                        <goals>
                            <goal>execute-commands</goal>
                        </goals>
                        <configuration>
                            <fork>true</fork>
                            <jbossHome>${env.JBOSS_HOME}</jbossHome>
                            <scripts>
                                <script>${project.basedir}/configure-basic-security.cli</script>
                            </scripts>
                        </configuration>
                    </execution>
                    <execution>
                        <id>wildfly-deploy</id>
                        <phase>install</phase>
                        <goals>
                            <goal>deploy-only</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>wildfly-undeploy</id>
                        <phase>clean</phase>
                        <goals>
                            <goal>undeploy</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>wildfly-cli-after-undeploy</id>
                        <phase>clean</phase>
                        <goals>
                            <goal>execute-commands</goal>
                        </goals>
                        <configuration>
                            <fork>true</fork>
                            <jbossHome>${env.JBOSS_HOME}</jbossHome>
                            <scripts>
                                <script>${project.basedir}/remove-basic-security.cli</script>
                            </scripts>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <!-- Profiles -->
    <profiles>
        <profile>
            <id>deploy</id>
            <properties>
                <deploy.skip>false</deploy.skip>
            </properties>
        </profile>
        <profile>
            <id>openshift</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <configuration>
                            <skipSource>true</skipSource>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-war-plugin</artifactId>
                        <configuration>
                            <warName>ROOT</warName>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
from pysnmp.hlapi.asyncore import ntforg

__all__ = ['sendNotification', 'next']

def next(iter):
    return iter.next()

#
# Synchronous one-liner SNMP Notification Originator application
#

def sendNotification(snmpEngine, authData, transportTarget, contextData,
                     notifyType, varBinds, **options):

    def cbFun(snmpEngine, sendRequestHandle,
              errorIndication, errorStatus, errorIndex,
              varBinds, cbCtx):
        cbCtx['errorIndication'] = errorIndication
        cbCtx['errorStatus'] = errorStatus
        cbCtx['errorIndex'] = errorIndex
        cbCtx['varBinds'] = varBinds

    cbCtx = {}

    if varBinds:
        ntforg.sendNotification(
            snmpEngine,
            authData,
            transportTarget,
            contextData,
            notifyType,
            varBinds,
            cbFun, cbCtx,
            options.get('lookupMib', True)
        )

        snmpEngine.transportDispatcher.runDispatcher()

        errorIndication = cbCtx.get('errorIndication')
        errorStatus = cbCtx.get('errorStatus')
        errorIndex = cbCtx.get('errorIndex')
        varBinds = cbCtx.get('varBinds', [])
    else:
        errorIndication = errorStatus = errorIndex = None
        varBinds = []

    yield errorIndication, errorStatus, errorIndex, varBinds


text:
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

	<property name="now" value="now()" dbms="mysql,h2" />
	<property name="now" value="current_timestamp" dbms="postgresql" />
	<property name="now" value="sysdate" dbms="oracle" />

	<property name="autoIncrement" value="true" dbms="mysql" />
	<property name="autoIncrement" value="false" dbms="oracle" />

	<changeSet id="20160706200000" author="dhabib">
		<addForeignKeyConstraint constraintName="fk_user_persistent_token"
			baseTableSchemaName="BCDSS" baseColumnNames="user_id" baseTableName="AUDT_PERSISTENT_TOKEN"
			referencedColumnNames="user_id" referencedTableSchemaName="BCDSS" referencedTableName="SEC_APP_USER" />

		<addForeignKeyConstraint constraintName="fk_evt_pers_audit_evt_data"
			baseColumnNames="event_id" baseTableSchemaName="BCDSS" baseTableName="AUDT_EVENT_DATA"
			referencedColumnNames="event_id" referencedTableSchemaName="BCDSS" referencedTableName="AUDT_EVENT" />
	</changeSet>
</databaseChangeLog>


text:
<!DOCTYPE html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <meta http-equiv="x-ua-compatible" content="ie=edge">

        <link rel="shortcut icon" href="../../assets/images/favicon.png">

      <meta name="generator" content="mkdocs-0.17.2, mkdocs-material-1.10.1">

        <title>Local Data - P2UX Developer</title>

      <link rel="stylesheet" href="../../assets/stylesheets/application-a20f419c8e.css">

        <link rel="stylesheet" href="../../assets/stylesheets/application-23f75ab9c7.palette.css">

        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">

      <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

      <link rel="stylesheet" href="../../stylesheets/extra.css">

    <svg class="md-svg">
      <defs>

      </defs>
    </svg>
    <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="drawer">
    <input class="md-toggle" data-md-toggle="search" type="checkbox" id="search">

                  Data Sources

                  Specific Types of Sources

            Local Data

    <form class="md-search__form" name="search">
      <input type="text" class="md-search__input" name="query" required placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query">

      <button type="reset" class="md-icon md-search__icon" data-md-component="reset"></button>
    </form>

            Type to start searching

    P2UX Developer

      Latest News

      <input class="md-toggle md-nav__toggle" data-md-toggle="nav-2" type="checkbox" id="nav-2">

      iOS/tvOS

        iOS/tvOS

      Quick Start

      Custom Code

      <input class="md-toggle md-nav__toggle" data-md-toggle="nav-3" type="checkbox" id="nav-3">

      Android

        Android

      Quick Start

      Custom Code

      <input class="md-toggle md-nav__toggle" data-md-toggle="nav-4" type="checkbox" id="nav-4">

      Application Content

        Application Content

      Application License

      Application Environments

      Application Bundle Updates

      Dynamic Application Bundle

      Static Application Bundle

      Splash Screens

      <input class="md-toggle md-nav__toggle" data-md-toggle="nav-5" type="checkbox" id="nav-5">

      Data Linking

        Data Linking

      Filters and Conditionals

      <input class="md-toggle md-nav__toggle" data-md-toggle="nav-6" type="checkbox" id="nav-6" checked>

      Data Sources

        Data Sources

      Overview

      Basic Data Sources

      <input class="md-toggle md-nav__toggle" data-md-toggle="nav-6-3" type="checkbox" id="nav-6-3" checked>

      Specific Types of Sources

        Specific Types of Sources

      Static Data

    <input class="md-toggle md-nav__toggle" data-md-toggle="toc" type="checkbox" id="toc">

        Local Data

      Local Data

    Table of contents

    Request Object Attributes

    Data Schema

    Default Data

      RESTful Data

      MQTT Data

    Table of contents

    Request Object Attributes

    Data Schema

    Default Data

Local Data Sources¶

Local Data Sources are collections of data that store data locally on the device where the application is installed. Since it follows the standard Data Source protocol, data from the repository can be used directly in UI and can also be parameterized using arguments for query purposes. Data is stored as JSON in a file and can optionally be encrypted. Keep in mind that Local Data Sources are modifiable as they are treated like a database. If you want read-only sources of data for an application, use Static Data Sources instead.

Note

As of the last version of this document, Data Sources can only be defined using a JSON editor. It is assumed that the reader understands the basics of JSON structure to be able to edit the data source. A better targeted Data Source editor is being developed to make creation of Data Sources simpiler.

Request Object Attributes¶

In addition to the basic Request Object Attributes provided by Data Sources, Local Data Sources have additional attributes used for data and parameters.

Attribute
Type
Description

seed
mixed
(OPTIONAL) - The initial data for the request. When an application is newly installed, this data is used until changes are made by the application.

maxentries
number
(OPTIONAL) - This value is used for schema types of Array and Object. It indicates the maximum entries to be stored. If a create or update operation is performed and the array is at its max then the last entry from the end or beginning of the array will be removed.

Data Schema¶

All requests require a schema object that defines the structure of the data repository. For Local Data Sources, the top level object needs to be either an Array or an Object. If the top level object is an Object, it is used like an array where the key for the object is the unique identifier of an object instance and the value is an instance of the data Object.

This example shows a request with an array collection of "user" objects. The request is called users in a data source named Internal Data.

{
  "name": {
    "en_US": "Internal Data"
  },
  "type": "LOCAL",
  "systemtype": "internal_data",
  "requests": {
    "users": {
      "request": {
        "version": 1
      },
      "schema": {
        "type": "Array",
        "index": "ident",
        "item": {
          "type": "Object",
          "item": {
            "ident": {
              "type": "String"
            },
            "firstname": {
              "type": "String"
            },
            "lastname": {
              "type": "String"
            },
            "picture": {
              "type": "String"
            },
            "password": {
              "type": "String"
            },
            "email": {
              "type": "String"
            }
          }
        }
      }
    }
  }
}

Default Data¶

Local Data Source requests can be seeded with data to provide an initial data set for the application. The initial data is provided within the request object with the key seed. If the initial data changes, the version of the request must be incremented to force clients to reseed the database with the provided data.

!!! note Version Migration
    As of version 1.1 of the P2UX Rendering Libraries (PRL), Local Data Sources don't support a version migration schema. This is planned for version 1.2 of the client libraries.

This example shows a request with seeded data. The request is called messages and contains a default message.

{
  "name": {
    "en_US": "Internal Data"
  },
  "type": "LOCAL",
  "systemtype": "internal_data",
  "requests": {
    "messages": {
      "request": {
        "version": 1,
        "seed":[
          {
            "ident":"ff-default",
            "message": "Welcome to the app, you'll find important messages here.",
            "from":"System",
            "type":0
          }
        ]
      },
      "schema": {
        "type": "Array",
        "index": "ident",
        "item": {
          "type": "Object",
          "item": {
            "ident": {
              "type": "String"
            },
            "message": {
              "type":"String"
            },
            "timestamp": {
              "type": "Date"
            },
            "from": {
              "type": "String"
            },
            "type":{
              "type": "Number"
            }
          }
        }
      }
    }
  }
}

Creating a New Data Source

For Steps to create a new Data Source in Builder, refer to the Data Sources documentation

Last Updated: Jan. 2, 2018

                  Previous

                Static Data

                  Next

                RESTful Data

            Copyright © 2017 P2UX, Inc.

        powered by
        MkDocs
        and

          Material for MkDocs


text:
ActiveRecord::Schema.define(version: 20150825021104) do

  create_table "crime_entries", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
export const localizationText = {
  greek: {
    delete: 'Διαγραφή',
  },
  english: {
    delete: 'Delete',
  }
}

export default localizationText


text:
namespace x
{

	x_Win32::x_Win32()
	{

	}

	x_Win32::~x_Win32()
	{

	}

	x_Bool x_Win32::createWindow(x_String windowTitle, x_Sint32 width, x_Sint32 height)
	{
		WNDCLASSEXW windowClass = {};
		windowClass.cbSize = sizeof(WNDCLASSEXW);
		windowClass.style = CS_OWNDC;
		windowClass.lpfnWndProc = (WNDPROC)WndProc;
		windowClass.cbClsExtra = 0;
		windowClass.cbWndExtra = 0;
		windowClass.hInstance = GetModuleHandle(NULL);
		windowClass.hIcon = NULL;
		windowClass.hCursor = LoadCursorW(NULL, IDC_ARROW);
		windowClass.hbrBackground = 0;
		windowClass.lpszMenuName = NULL;
		windowClass.lpszClassName = windowTitle.getPWchar();
		if (!RegisterClassExW(&windowClass))
		{
			return false;
		}

		DWORD style = WS_VISIBLE | WS_CAPTION | WS_MINIMIZEBOX | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_SYSMENU;
		DWORD extendedStyle = WS_EX_APPWINDOW;

		RECT sizeRect = { 0, 0, width, height };

		AdjustWindowRectEx(&sizeRect, style, false, extendedStyle);

		HWND hWnd = CreateWindowExW(extendedStyle, windowTitle.getPWchar(), windowTitle.getPWchar(), style, CW_USEDEFAULT, CW_USEDEFAULT,
			sizeRect.right - sizeRect.left, sizeRect.bottom - sizeRect.top, NULL, NULL,
			GetModuleHandle(NULL), this);

		if (hWnd)
			x_Platform::s_pWindowHandler->setWindowHandler(hWnd);
		else
			return false;

		SetWindowLongPtrW(hWnd, GWLP_USERDATA, reinterpret_cast<LONGLONG>(this));

		ShowWindow(hWnd, SW_SHOW);

		HDC hDC = GetDC(hWnd);

		if (hDC)
			x_Platform::s_pDeviceContextHandler->setDeviceContextHandler(hDC);
		else
		{
			destroyWindow();
			return false;
		}

		return true;
	}

	void x_Win32::destroyWindow()
	{
		HDC hDC = (HDC)x_Platform::s_pDeviceContextHandler->getDeviceContextHandler();
		HWND hWnd = (HWND)x_Platform::s_pWindowHandler->getWindowHandler();

		if (hDC)
		{
			ReleaseDC(hWnd, hDC);
			x_Platform::s_pDeviceContextHandler->setDeviceContextHandler(nullptr);
		}

		if (hWnd)
		{
			DestroyWindow(hWnd);
			x_Platform::s_pWindowHandler->setWindowHandler(nullptr);
		}

		UnregisterClassW(s_pWindowTitle->getPWchar(), NULL);
	}

	x_Sint32 x_Win32::messagePump()
	{
		MSG msg = {};
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		return (x_Sint32)msg.wParam;
	}

	x_WindowHandler x_Win32::getWindowHandler()
	{
		return *x_Platform::s_pWindowHandler;
	}

	void x_Win32::setWindowHandler(x_WindowHandler windowHandler)
	{
		*x_Platform::s_pWindowHandler = windowHandler;
	}

	x_DeviceContextHandler x_Win32::getDeviceContextHandler()
	{
		return *x_Platform::s_pDeviceContextHandler;
	}

	void x_Win32::setDeviceContextHandler(x_DeviceContextHandler deviceContextHandler)
	{
		*x_Platform::s_pDeviceContextHandler = deviceContextHandler;
	}

	x_LRESULT x_CALLBACK x_Win32::WndProc(x_HWND hWnd, x_UINT message, x_WPARAM wParam, x_LPARAM lParam)
	{
			switch (message)
			{
			//case WM_ERASEBKGND:
			//	return TRUE; // tell Windows that we handled it. (but don't actually draw anything)
			case WM_DESTROY:
				break;
			case WM_CLOSE:
				if (s_pOnClose)
				{
					(*s_pOnClose)();
				}
				break;
			case WM_SIZE:
			{
				if (s_pOnClose)
				{
					RECT winRect;
					GetClientRect((HWND)hWnd, &winRect);

					POINT topLeft;
					topLeft.x = winRect.left;
					topLeft.y = winRect.top;
					ClientToScreen((HWND)hWnd, &topLeft);

					POINT botRight;
					botRight.x = winRect.right;
					botRight.y = winRect.bottom;
					ClientToScreen((HWND)hWnd, &botRight);

					x_Sint32 x = botRight.x - topLeft.x;
					x_Sint32 y = botRight.y - topLeft.y;

					(*s_pOnSize)(x, y);
				}
				break;
			}
			}
		return DefWindowProcW((HWND)hWnd, message, wParam, lParam);
	}

}


text:
import {VMenuLink} from 'orion/ui/helpers';
import * as React from "react";
import {StyleGuidePage} from "./page";

export class TypographyPage extends StyleGuidePage {
    sidebar() {
        return (

                <VMenuLink index={true}>← Home</VMenuLink>
                <VMenuLink hash="#fonts">Fonts</VMenuLink>
                <VMenuLink hash="#headings">Headings</VMenuLink>
                <VMenuLink hash="#paragraphs">Paragraphs</VMenuLink>
                <VMenuLink hash="#tabs">Tabs</VMenuLink>
                <VMenuLink hash="#tooltips">Tooltips</VMenuLink>
                <VMenuLink hash="#modals">Modals</VMenuLink>

        )
    }

    main() {
        return (

Fonts

We use Karla

Headings

h1. Heading

h2. Subtitle

h3. Subheading

h4. Heading

h5. Heading

Paragraphs

                        Created with  .l-body

                    Example:

                        Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                        when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                        It has survived not only five centuries, but also the leap into electronic typesetting,
                        remaining essentially unchanged.

                        Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                        when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                        It has survived not only five centuries, but also the leap into electronic typesetting,
                        remaining essentially unchanged.

                        Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                        when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                        It has survived not only five centuries, but also the leap into electronic typesetting,
                        remaining essentially unchanged.

                        Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                        when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                        uding versions of Lorem Ipsum.

        )
    }

}


text:
package org.elasticsearch.xpack.ml.job;

import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.AckedClusterStateUpdateTask;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.CheckedConsumer;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.analysis.AnalysisRegistry;
import org.elasticsearch.persistent.PersistentTasksCustomMetaData;
import org.elasticsearch.xpack.core.XPackPlugin;
import org.elasticsearch.xpack.core.ml.MachineLearningField;
import org.elasticsearch.xpack.core.ml.MlMetadata;
import org.elasticsearch.xpack.core.ml.MlTasks;
import org.elasticsearch.xpack.core.ml.action.PutJobAction;
import org.elasticsearch.xpack.core.ml.action.RevertModelSnapshotAction;
import org.elasticsearch.xpack.core.ml.action.UpdateJobAction;
import org.elasticsearch.xpack.core.ml.action.util.QueryPage;
import org.elasticsearch.xpack.core.ml.job.config.AnalysisLimits;
import org.elasticsearch.xpack.core.ml.job.config.CategorizationAnalyzerConfig;
import org.elasticsearch.xpack.core.ml.job.config.DataDescription;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import org.elasticsearch.xpack.core.ml.job.config.JobState;
import org.elasticsearch.xpack.core.ml.job.config.JobUpdate;
import org.elasticsearch.xpack.core.ml.job.config.MlFilter;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.ModelSizeStats;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.ModelSnapshot;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.ml.MachineLearning;
import org.elasticsearch.xpack.ml.job.categorization.CategorizationAnalyzer;
import org.elasticsearch.xpack.ml.job.persistence.JobResultsPersister;
import org.elasticsearch.xpack.ml.job.persistence.JobResultsProvider;
import org.elasticsearch.xpack.ml.job.process.autodetect.UpdateParams;
import org.elasticsearch.xpack.ml.notifications.Auditor;
import org.elasticsearch.xpack.ml.utils.ChainTaskExecutor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Allows interactions with jobs. The managed interactions include:
 *

 *
creation

 *
deletion

 *
updating

 *
starting/stopping of datafeed jobs

 *

 */
public class JobManager extends AbstractComponent {

    private static final DeprecationLogger DEPRECATION_LOGGER =
            new DeprecationLogger(Loggers.getLogger(JobManager.class));

    private final Environment environment;
    private final JobResultsProvider jobResultsProvider;
    private final ClusterService clusterService;
    private final Auditor auditor;
    private final Client client;
    private final UpdateJobProcessNotifier updateJobProcessNotifier;

    private volatile ByteSizeValue maxModelMemoryLimit;

    /**
     * Create a JobManager
     */
    public JobManager(Environment environment, Settings settings, JobResultsProvider jobResultsProvider,
                      ClusterService clusterService, Auditor auditor,
                      Client client, UpdateJobProcessNotifier updateJobProcessNotifier) {
        super(settings);
        this.environment = environment;
        this.jobResultsProvider = Objects.requireNonNull(jobResultsProvider);
        this.clusterService = Objects.requireNonNull(clusterService);
        this.auditor = Objects.requireNonNull(auditor);
        this.client = Objects.requireNonNull(client);
        this.updateJobProcessNotifier = updateJobProcessNotifier;

        maxModelMemoryLimit = MachineLearningField.MAX_MODEL_MEMORY_LIMIT.get(settings);
        clusterService.getClusterSettings()
                .addSettingsUpdateConsumer(MachineLearningField.MAX_MODEL_MEMORY_LIMIT, this::setMaxModelMemoryLimit);
    }

    private void setMaxModelMemoryLimit(ByteSizeValue maxModelMemoryLimit) {
        this.maxModelMemoryLimit = maxModelMemoryLimit;
    }

    /**
     * Gets the job that matches the given {@code jobId}.
     *
     * @param jobId the jobId
     * @return The {@link Job} matching the given {code jobId}
     * @throws ResourceNotFoundException if no job matches {@code jobId}
     */
    public Job getJobOrThrowIfUnknown(String jobId) {
        return getJobOrThrowIfUnknown(jobId, clusterService.state());
    }

    /**
     * Gets the job that matches the given {@code jobId}.
     *
     * @param jobId the jobId
     * @param clusterState the cluster state
     * @return The {@link Job} matching the given {code jobId}
     * @throws ResourceNotFoundException if no job matches {@code jobId}
     */
    public static Job getJobOrThrowIfUnknown(String jobId, ClusterState clusterState) {
        Job job = MlMetadata.getMlMetadata(clusterState).getJobs().get(jobId);
        if (job == null) {
            throw ExceptionsHelper.missingJobException(jobId);
        }
        return job;
    }

    private Set<String> expandJobIds(String expression, boolean allowNoJobs, ClusterState clusterState) {
        return MlMetadata.getMlMetadata(clusterState).expandJobIds(expression, allowNoJobs);
    }

    /**
     * Get the jobs that match the given {@code expression}.
     * Note that when the {@code jobId} is {@link MetaData#ALL} all jobs are returned.
     *
     * @param expression   the jobId or an expression matching jobIds
     * @param clusterState the cluster state
     * @param allowNoJobs  if {@code false}, an error is thrown when no job matches the {@code jobId}
     * @return A {@link QueryPage} containing the matching {@code Job}s
     */
    public QueryPage<Job> expandJobs(String expression, boolean allowNoJobs, ClusterState clusterState) {
        Set<String> expandedJobIds = expandJobIds(expression, allowNoJobs, clusterState);
        MlMetadata mlMetadata = MlMetadata.getMlMetadata(clusterState);
        List<Job> jobs = new ArrayList<>();
        for (String expandedJobId : expandedJobIds) {
            jobs.add(mlMetadata.getJobs().get(expandedJobId));
        }
        logger.debug("Returning jobs matching [" + expression + "]");
        return new QueryPage<>(jobs, jobs.size(), Job.RESULTS_FIELD);
    }

    /**
     * Validate the char filter/tokenizer/token filter names used in the categorization analyzer config (if any).
     * This validation has to be done server-side; it cannot be done in a client as that won't have loaded the
     * appropriate analysis modules/plugins.
     * The overall structure can be validated at parse time, but the exact names need to be checked separately,
     * as plugins that provide the functionality can be installed/uninstalled.
     */
    static void validateCategorizationAnalyzer(Job.Builder jobBuilder, AnalysisRegistry analysisRegistry, Environment environment)
        throws IOException {
        CategorizationAnalyzerConfig categorizationAnalyzerConfig = jobBuilder.getAnalysisConfig().getCategorizationAnalyzerConfig();
        if (categorizationAnalyzerConfig != null) {
            CategorizationAnalyzer.verifyConfigBuilder(new CategorizationAnalyzerConfig.Builder(categorizationAnalyzerConfig),
                analysisRegistry, environment);
        }
    }

    /**
     * Stores a job in the cluster state
     */
    public void putJob(PutJobAction.Request request, AnalysisRegistry analysisRegistry, ClusterState state,
                       ActionListener<PutJobAction.Response> actionListener) throws IOException {

        request.getJobBuilder().validateAnalysisLimitsAndSetDefaults(maxModelMemoryLimit);
        validateCategorizationAnalyzer(request.getJobBuilder(), analysisRegistry, environment);

        Job job = request.getJobBuilder().build(new Date());

        if (job.getDataDescription() != null && job.getDataDescription().getFormat() == DataDescription.DataFormat.DELIMITED) {
            DEPRECATION_LOGGER.deprecated("Creating jobs with delimited data format is deprecated. Please use xcontent instead.");
        }

        // pre-flight check, not necessarily required, but avoids figuring this out while on the CS update thread
        XPackPlugin.checkReadyForXPackCustomMetadata(state);

        MlMetadata currentMlMetadata = MlMetadata.getMlMetadata(state);
        if (currentMlMetadata.getJobs().containsKey(job.getId())) {
            actionListener.onFailure(ExceptionsHelper.jobAlreadyExists(job.getId()));
            return;
        }

        ActionListener<Boolean> putJobListener = new ActionListener<Boolean>() {
            @Override
            public void onResponse(Boolean indicesCreated) {

                clusterService.submitStateUpdateTask("put-job-" + job.getId(),
                        new AckedClusterStateUpdateTask<PutJobAction.Response>(request, actionListener) {
                            @Override
                            protected PutJobAction.Response newResponse(boolean acknowledged) {
                                auditor.info(job.getId(), Messages.getMessage(Messages.JOB_AUDIT_CREATED));
                                return new PutJobAction.Response(job);
                            }

                            @Override
                            public ClusterState execute(ClusterState currentState) {
                                return updateClusterState(job, false, currentState);
                            }
                        });
            }

            @Override
            public void onFailure(Exception e) {
                if (e instanceof IllegalArgumentException) {
                    // the underlying error differs depending on which way around the clashing fields are seen
                    Matcher matcher = Pattern.compile("(?:mapper|Can't merge a non object mapping) \\[(.*)\\] (?:of different type, " +
                            "current_type \\[.*\\], merged_type|with an object mapping) \\[.*\\]").matcher(e.getMessage());
                    if (matcher.matches()) {
                        String msg = Messages.getMessage(Messages.JOB_CONFIG_MAPPING_TYPE_CLASH, matcher.group(1));
                        actionListener.onFailure(ExceptionsHelper.badRequestException(msg, e));
                        return;
                    }
                }
                actionListener.onFailure(e);
            }
        };

        ActionListener<Boolean> checkForLeftOverDocs = ActionListener.wrap(
                response -> {
                    jobResultsProvider.createJobResultIndex(job, state, putJobListener);
                },
                actionListener::onFailure
        );

        jobResultsProvider.checkForLeftOverDocuments(job, checkForLeftOverDocs);
    }

    public void updateJob(UpdateJobAction.Request request, ActionListener<PutJobAction.Response> actionListener) {
        Job job = getJobOrThrowIfUnknown(request.getJobId());
        validate(request.getJobUpdate(), job, ActionListener.wrap(
                nullValue -> internalJobUpdate(request, actionListener),
                actionListener::onFailure));
    }

    private void validate(JobUpdate jobUpdate, Job job, ActionListener<Void> handler) {
        ChainTaskExecutor chainTaskExecutor = new ChainTaskExecutor(client.threadPool().executor(
                MachineLearning.UTILITY_THREAD_POOL_NAME), true);
        validateModelSnapshotIdUpdate(job, jobUpdate.getModelSnapshotId(), chainTaskExecutor);
        validateAnalysisLimitsUpdate(job, jobUpdate.getAnalysisLimits(), chainTaskExecutor);
        chainTaskExecutor.execute(handler);
    }

    private void validateModelSnapshotIdUpdate(Job job, String modelSnapshotId, ChainTaskExecutor chainTaskExecutor) {
        if (modelSnapshotId != null) {
            chainTaskExecutor.add(listener -> {
                jobResultsProvider.getModelSnapshot(job.getId(), modelSnapshotId, newModelSnapshot -> {
                    if (newModelSnapshot == null) {
                        String message = Messages.getMessage(Messages.REST_NO_SUCH_MODEL_SNAPSHOT, modelSnapshotId,
                                job.getId());
                        listener.onFailure(new ResourceNotFoundException(message));
                        return;
                    }
                    jobResultsProvider.getModelSnapshot(job.getId(), job.getModelSnapshotId(), oldModelSnapshot -> {
                        if (oldModelSnapshot != null
                                && newModelSnapshot.result.getTimestamp().before(oldModelSnapshot.result.getTimestamp())) {
                            String message = "Job [" + job.getId() + "] has a more recent model snapshot [" +
                                    oldModelSnapshot.result.getSnapshotId() + "]";
                            listener.onFailure(new IllegalArgumentException(message));
                        }
                        listener.onResponse(null);
                    }, listener::onFailure);
                }, listener::onFailure);
            });
        }
    }

    private void validateAnalysisLimitsUpdate(Job job, AnalysisLimits newLimits, ChainTaskExecutor chainTaskExecutor) {
        if (newLimits == null || newLimits.getModelMemoryLimit() == null) {
            return;
        }
        Long newModelMemoryLimit = newLimits.getModelMemoryLimit();
        chainTaskExecutor.add(listener -> {
            if (isJobOpen(clusterService.state(), job.getId())) {
                listener.onFailure(ExceptionsHelper.badRequestException("Cannot update " + Job.ANALYSIS_LIMITS.getPreferredName()
                        + " while the job is open"));
                return;
            }
            jobResultsProvider.modelSizeStats(job.getId(), modelSizeStats -> {
                if (modelSizeStats != null) {
                    ByteSizeValue modelSize = new ByteSizeValue(modelSizeStats.getModelBytes(), ByteSizeUnit.BYTES);
                    if (newModelMemoryLimit < modelSize.getMb()) {
                        listener.onFailure(ExceptionsHelper.badRequestException(
                                Messages.getMessage(Messages.JOB_CONFIG_UPDATE_ANALYSIS_LIMITS_MODEL_MEMORY_LIMIT_CANNOT_BE_DECREASED,
                                        new ByteSizeValue(modelSize.getMb(), ByteSizeUnit.MB),
                                        new ByteSizeValue(newModelMemoryLimit, ByteSizeUnit.MB))));
                        return;
                    }
                }
                listener.onResponse(null);
            }, listener::onFailure);
        });
    }

    private void internalJobUpdate(UpdateJobAction.Request request, ActionListener<PutJobAction.Response> actionListener) {
        if (request.isWaitForAck()) {
            // Use the ack cluster state update
            clusterService.submitStateUpdateTask("update-job-" + request.getJobId(),
                    new AckedClusterStateUpdateTask<PutJobAction.Response>(request, actionListener) {
                        private AtomicReference<Job> updatedJob = new AtomicReference<>();

                        @Override
                        protected PutJobAction.Response newResponse(boolean acknowledged) {
                            return new PutJobAction.Response(updatedJob.get());
                        }

                        @Override
                        public ClusterState execute(ClusterState currentState) {
                            Job job = getJobOrThrowIfUnknown(request.getJobId(), currentState);
                            updatedJob.set(request.getJobUpdate().mergeWithJob(job, maxModelMemoryLimit));
                            return updateClusterState(updatedJob.get(), true, currentState);
                        }

                        @Override
                        public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
                            afterClusterStateUpdate(newState, request);
                        }
                    });
        } else {
            clusterService.submitStateUpdateTask("update-job-" + request.getJobId(), new ClusterStateUpdateTask() {
                private AtomicReference<Job> updatedJob = new AtomicReference<>();

                @Override
                public ClusterState execute(ClusterState currentState) throws Exception {
                    Job job = getJobOrThrowIfUnknown(request.getJobId(), currentState);
                    updatedJob.set(request.getJobUpdate().mergeWithJob(job, maxModelMemoryLimit));
                    return updateClusterState(updatedJob.get(), true, currentState);
                }

                @Override
                public void onFailure(String source, Exception e) {
                    actionListener.onFailure(e);
                }

                @Override
                public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
                    afterClusterStateUpdate(newState, request);
                    actionListener.onResponse(new PutJobAction.Response(updatedJob.get()));
                }
            });
        }
    }

    private void afterClusterStateUpdate(ClusterState newState, UpdateJobAction.Request request) {
        JobUpdate jobUpdate = request.getJobUpdate();

        // Change is required if the fields that the C++ uses are being updated
        boolean processUpdateRequired = jobUpdate.isAutodetectProcessUpdate();

        if (processUpdateRequired && isJobOpen(newState, request.getJobId())) {
            updateJobProcessNotifier.submitJobUpdate(UpdateParams.fromJobUpdate(jobUpdate), ActionListener.wrap(
                    isUpdated -> {
                        if (isUpdated) {
                            auditJobUpdatedIfNotInternal(request);
                        }
                    }, e -> {
                        // No need to do anything
                    }
            ));
        } else {
            logger.debug("[{}] No process update required for job update: {}", () -> request.getJobId(), () -> {
                try {
                    XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
                    jobUpdate.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS);
                    return Strings.toString(jsonBuilder);
                } catch (IOException e) {
                    return "(unprintable due to " + e.getMessage() + ")";
                }
            });

            auditJobUpdatedIfNotInternal(request);
        }
    }

    private void auditJobUpdatedIfNotInternal(UpdateJobAction.Request request) {
        if (request.isInternal() == false) {
            auditor.info(request.getJobId(), Messages.getMessage(Messages.JOB_AUDIT_UPDATED, request.getJobUpdate().getUpdateFields()));
        }
    }

    private boolean isJobOpen(ClusterState clusterState, String jobId) {
        PersistentTasksCustomMetaData persistentTasks = clusterState.metaData().custom(PersistentTasksCustomMetaData.TYPE);
        JobState jobState = MlTasks.getJobState(jobId, persistentTasks);
        return jobState == JobState.OPENED;
    }

    private ClusterState updateClusterState(Job job, boolean overwrite, ClusterState currentState) {
        MlMetadata.Builder builder = createMlMetadataBuilder(currentState);
        builder.putJob(job, overwrite);
        return buildNewClusterState(currentState, builder);
    }

    public void notifyFilterChanged(MlFilter filter, Set<String> addedItems, Set<String> removedItems) {
        if (addedItems.isEmpty() && removedItems.isEmpty()) {
            return;
        }

        ClusterState clusterState = clusterService.state();
        QueryPage<Job> jobs = expandJobs("*", true, clusterService.state());
        for (Job job : jobs.results()) {
            Set<String> jobFilters = job.getAnalysisConfig().extractReferencedFilters();
            if (jobFilters.contains(filter.getId())) {
                if (isJobOpen(clusterState, job.getId())) {
                    updateJobProcessNotifier.submitJobUpdate(UpdateParams.filterUpdate(job.getId(), filter),
                            ActionListener.wrap(isUpdated -> {
                                auditFilterChanges(job.getId(), filter.getId(), addedItems, removedItems);
                            }, e -> {}));
                } else {
                    auditFilterChanges(job.getId(), filter.getId(), addedItems, removedItems);
                }
            }
        }
    }

    private void auditFilterChanges(String jobId, String filterId, Set<String> addedItems, Set<String> removedItems) {
        StringBuilder auditMsg = new StringBuilder("Filter [");
        auditMsg.append(filterId);
        auditMsg.append("] has been modified; ");

        if (addedItems.isEmpty() == false) {
            auditMsg.append("added items: ");
            appendCommaSeparatedSet(addedItems, auditMsg);
            if (removedItems.isEmpty() == false) {
                auditMsg.append(", ");
            }
        }

        if (removedItems.isEmpty() == false) {
            auditMsg.append("removed items: ");
            appendCommaSeparatedSet(removedItems, auditMsg);
        }

        auditor.info(jobId, auditMsg.toString());
    }

    private static void appendCommaSeparatedSet(Set<String> items, StringBuilder sb) {
        sb.append("[");
        Strings.collectionToDelimitedString(items, ", ", "'", "'", sb);
        sb.append("]");
    }

    public void updateProcessOnCalendarChanged(List<String> calendarJobIds) {
        ClusterState clusterState = clusterService.state();
        MlMetadata mlMetadata = MlMetadata.getMlMetadata(clusterState);

        List<String> existingJobsOrGroups =
                calendarJobIds.stream().filter(mlMetadata::isGroupOrJob).collect(Collectors.toList());

        Set<String> expandedJobIds = new HashSet<>();
        existingJobsOrGroups.forEach(jobId -> expandedJobIds.addAll(expandJobIds(jobId, true, clusterState)));
        for (String jobId : expandedJobIds) {
            if (isJobOpen(clusterState, jobId)) {
                updateJobProcessNotifier.submitJobUpdate(UpdateParams.scheduledEventsUpdate(jobId), ActionListener.wrap(
                        isUpdated -> {
                            if (isUpdated) {
                                auditor.info(jobId, Messages.getMessage(Messages.JOB_AUDIT_CALENDARS_UPDATED_ON_PROCESS));
                            }
                        }, e -> {}
                ));
            }
        }
    }

    public void revertSnapshot(RevertModelSnapshotAction.Request request, ActionListener<RevertModelSnapshotAction.Response> actionListener,
            ModelSnapshot modelSnapshot) {

        final ModelSizeStats modelSizeStats = modelSnapshot.getModelSizeStats();
        final JobResultsPersister persister = new JobResultsPersister(settings, client);

        // Step 3. After the model size stats is persisted, also persist the snapshot's quantiles and respond
        // -------
        CheckedConsumer<IndexResponse, Exception> modelSizeStatsResponseHandler = response -> {
            persister.persistQuantiles(modelSnapshot.getQuantiles(), WriteRequest.RefreshPolicy.IMMEDIATE,
                    ActionListener.wrap(quantilesResponse -> {
                        // The quantiles can be large, and totally dominate the output -
                        // it's clearer to remove them as they are not necessary for the revert op
                        ModelSnapshot snapshotWithoutQuantiles = new ModelSnapshot.Builder(modelSnapshot).setQuantiles(null).build();
                        actionListener.onResponse(new RevertModelSnapshotAction.Response(snapshotWithoutQuantiles));
                    }, actionListener::onFailure));
        };

        // Step 2. When the model_snapshot_id is updated on the job, persist the snapshot's model size stats with a touched log time
        // so that a search for the latest model size stats returns the reverted one.
        // -------
        CheckedConsumer<Boolean, Exception> updateHandler = response -> {
            if (response) {
                ModelSizeStats revertedModelSizeStats = new ModelSizeStats.Builder(modelSizeStats).setLogTime(new Date()).build();
                persister.persistModelSizeStats(revertedModelSizeStats, WriteRequest.RefreshPolicy.IMMEDIATE, ActionListener.wrap(
                        modelSizeStatsResponseHandler, actionListener::onFailure));
            }
        };

        // Step 1. Do the cluster state update
        // -------
        Consumer<Long> clusterStateHandler = response -> clusterService.submitStateUpdateTask("revert-snapshot-" + request.getJobId(),
                new AckedClusterStateUpdateTask<Boolean>(request, ActionListener.wrap(updateHandler, actionListener::onFailure)) {

            @Override
            protected Boolean newResponse(boolean acknowledged) {
                if (acknowledged) {
                    auditor.info(request.getJobId(), Messages.getMessage(Messages.JOB_AUDIT_REVERTED, modelSnapshot.getDescription()));
                    return true;
                }
                actionListener.onFailure(new IllegalStateException("Could not revert modelSnapshot on job ["
                        + request.getJobId() + "], not acknowledged by master."));
                return false;
            }

            @Override
            public ClusterState execute(ClusterState currentState) {
                Job job = getJobOrThrowIfUnknown(request.getJobId(), currentState);
                Job.Builder builder = new Job.Builder(job);
                builder.setModelSnapshotId(modelSnapshot.getSnapshotId());
                builder.setEstablishedModelMemory(response);
                return updateClusterState(builder.build(), true, currentState);
            }
        });

        // Step 0. Find the appropriate established model memory for the reverted job
        // -------
        jobResultsProvider.getEstablishedMemoryUsage(request.getJobId(), modelSizeStats.getTimestamp(), modelSizeStats, clusterStateHandler,
                actionListener::onFailure);
    }

    private static MlMetadata.Builder createMlMetadataBuilder(ClusterState currentState) {
        return new MlMetadata.Builder(MlMetadata.getMlMetadata(currentState));
    }

    private static ClusterState buildNewClusterState(ClusterState currentState, MlMetadata.Builder builder) {
        XPackPlugin.checkReadyForXPackCustomMetadata(currentState);
        ClusterState.Builder newState = ClusterState.builder(currentState);
        newState.metaData(MetaData.builder(currentState.getMetaData()).putCustom(MlMetadata.TYPE, builder.build()).build());
        return newState.build();
    }
}


text:
<?php

/**
 * \Exception
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
namespace Magento\Framework\Backup\Exception;

class FtpConnectionFailed extends \Magento\Framework\Backup\BackupException
{
}


text:
package org.apache.isis.viewer.restfulobjects.tck.domainobjectorservice.id.action.invoke;

import javax.ws.rs.core.Response;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation;
import org.apache.isis.viewer.restfulobjects.applib.LinkRepresentation;
import org.apache.isis.viewer.restfulobjects.applib.client.RestfulClient;
import org.apache.isis.viewer.restfulobjects.applib.client.RestfulResponse;
import org.apache.isis.viewer.restfulobjects.applib.client.RestfulResponse.HttpStatusCode;
import org.apache.isis.viewer.restfulobjects.applib.domainobjects.ActionResultRepresentation;
import org.apache.isis.viewer.restfulobjects.applib.domainobjects.DomainServiceResource;
import org.apache.isis.viewer.restfulobjects.applib.domainobjects.ObjectActionRepresentation;
import org.apache.isis.viewer.restfulobjects.applib.domainobjects.ScalarValueRepresentation;
import org.apache.isis.viewer.restfulobjects.applib.util.JsonNodeUtils;
import org.apache.isis.viewer.restfulobjects.tck.IsisWebServerRule;
import org.apache.isis.viewer.restfulobjects.tck.Util;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class Put_whenStringArgs_then_ok {

    @Rule
    public IsisWebServerRule webServerRule = new IsisWebServerRule();

    private RestfulClient client;

    private DomainServiceResource serviceResource;

    @Before
    public void setUp() throws Exception {
        client = webServerRule.getClient();

        serviceResource = client.getDomainServiceResource();
    }

    /**
     * Tests might change state, so discard such that will be recreated by next test.
     */
    @After
    public void tearDown() throws Exception {
        webServerRule.discardWebApp();
    }

    @Test
    public void usingClientFollow() throws Exception {

        // given
        final JsonRepresentation givenAction = Util.givenAction(client, "ActionsEntities", "concatenate");
        final ObjectActionRepresentation actionRepr = givenAction.as(ObjectActionRepresentation.class);

        final LinkRepresentation invokeLink = actionRepr.getInvoke();
        final JsonRepresentation args =invokeLink.getArguments();

        // when
        args.mapPut("str1.value", "IVA VENDITE 21%");
        args.mapPut("str2.value", "AAA");

        // when
        final RestfulResponse<ActionResultRepresentation> restfulResponse = client.followT(invokeLink, args);

        // then
        then(restfulResponse, "IVA VENDITE 21%AAA");
    }

    @Test
    public void usingResourceProxy() throws Exception {

        // given, when
        final JsonRepresentation args = JsonRepresentation.newMap();
        args.mapPut("str1.value", "IVA VENDITE 21%");
        args.mapPut("str2.value", "AAA");

        final Response response = serviceResource.invokeActionIdempotent("ActionsEntities", "concatenate", JsonNodeUtils.asInputStream(args));
        final RestfulResponse<ActionResultRepresentation> restfulResponse = RestfulResponse.ofT(response);

        // then
        then(restfulResponse, "IVA VENDITE 21%AAA");
    }

    private void then(RestfulResponse<ActionResultRepresentation> restfulResponse, final String expected) throws Exception {
        assertThat(restfulResponse.getStatus(), is(HttpStatusCode.OK));
        final ActionResultRepresentation entity = restfulResponse.getEntity();
        final ScalarValueRepresentation svr = entity.getResult().as(ScalarValueRepresentation.class);
        assertThat(svr.getValue().asString(), is(expected));
    }

}