text:
#ifndef HISTOGRAM_BASE_H
#define	HISTOGRAM_BASE_H

#include <iomanip> // std::setw, etc
#include <algorithm> // std::max_element
#include <fstream> // std::ofstream
#include <iostream> // std::cerr
#include <cassert> // assert

#include <boost/date_time/posix_time/posix_time.hpp> // boost::posix_time

#include <mutation_accumulation/patterns/observer.h> // patterns::Subject
#include <mutation_accumulation/simulation/files.h> // monte_carlo::open_file_for_output

/*************************************************************************/

/* consider moving implementation of large, implicitly inlined member functions to implementation file
 * (Item 30) */

/**
 * this namespace includes classes that empirically calculate various probability distributions
 */
namespace probability {

    /**
     * convenience class that contains a sample space and corresponding probability distribution\n
     * this class is copyable, unlike Histogram
     */
    template <class sample_type>
    class SampleSpace_Probability {
    public:

        std::vector<sample_type> _sample_space;
        std::vector<double> _probability;

        explicit SampleSpace_Probability(
                const std::vector<sample_type> &sample_space,
                const std::vector<double> &probability)
        :
        _sample_space(sample_space),
        _probability(probability) {

        }

        explicit SampleSpace_Probability() {

        }

        const std::vector<sample_type> sample_space() const {
            return _sample_space;
        }

        const std::vector<double> probability() const {
            return _probability;
        }

    };

    /**
     * abstract base class that holds the frequencies associated with a given sample space\n
     * cannot instantiate this class
     *
     * many of the member functions of this class could be made non-member (Item 23)\n
     */
    template <class sample_type>
    class Histogram : public patterns::Subject {
    public:

        typedef sample_type sample_t;
        typedef long long int number_trials_t;
        typedef long long int frequency_t;

    private:

        const std::vector<sample_type> sample_space;
        std::vector<frequency_t> histogram;
        std::vector<double> probability;
        number_trials_t number_trials;

        const std::string _fileName;

    private:

        typedef boost::posix_time::time_duration Duration_t;
        typedef boost::posix_time::ptime Posix_Time_t;
        typedef boost::posix_time::minutes Minutes_t;
        typedef boost::posix_time::second_clock Second_Clock_t;

        Duration_t interval; // interval between checkpoints
        Posix_Time_t next_checkpoint; // next checkpoint

    private:

        /* implementation member functions available to Histogram */

        /**
         * normalize histogram
         */
        void normalize() {

            if (number_trials > static_cast<number_trials_t>(0)) {

                for (int ii = 0; ii < sample_space.size(); ii++)
                    probability.at(ii) = (double) histogram.at(ii) / (double) number_trials;
            }

        }

        /**
         * write probability to disk
         */
        void store() {

            /* open file for (over-)writing */
            const boost::shared_ptr<std::ofstream> ofstream_ptr = monte_carlo::open_file_for_output(_fileName);

            for (int ii = 0; ii < probability.size(); ii++) {

                *ofstream_ptr << std::setw(10) << std::setprecision(3) << sample_space.at(ii);
                *ofstream_ptr << std::setw(20) << std::setprecision(10) << probability.at(ii);
                *ofstream_ptr << std::endl;

            }
        }

        /**
         * returns true if just passed a temporal checkpoint\n
         * should make a base class called Timer with virtual function onTick: Item 39\n
         * Histogram would contain a HistogramTimer class inheriting from Timer (Item 39)
         */
        const bool just_passed_checkpoint() {

            /* determine if time since start has exceeded current check point */
            const bool return_value = next_checkpoint < Second_Clock_t::local_time();

            if (return_value == true) {

                /* increment check point until it is greater than current time */
                while (next_checkpoint < Second_Clock_t::local_time())
                    next_checkpoint += interval;

            }

            return return_value;

        }

    protected:

        /* implementation member functions available to Histogram and derived classes */

        /**
         * constructor
         */
        explicit Histogram(const std::vector<sample_type> &sample_space_, const std::string &fileName)
        : patterns::Subject(), sample_space(sample_space_), number_trials(static_cast<number_trials_t>(0)), _fileName(fileName) {

            histogram = std::vector<frequency_t>(sample_space_.size(), 0);
            probability = std::vector<double>(sample_space_.size(), -1.0);

            interval = Minutes_t(15);
            next_checkpoint = Second_Clock_t::local_time() + interval;

        }

        /**
         * must declare default constructor: \n
         * compiler provides default constructor only if no custom constructors exist\n
         *
         * this is an empty constructor\n
         * compiler should generate code to construct private data members (Item 30)
         */
        explicit Histogram() {

        }

        /**
         * increment histogram at position ii\n
         */
        void increment_histogram(const int &ii) {

            /* increment histogram */
            histogram.at(ii)++;

        }

        /**
         * update histogram of frequencies and notify any observers
         */
        virtual void updateHistogram_notify(const sample_type &sample) = 0; // implement in derived classes

    public:

        /**
         * virtual destructor\n
         * ensures that objects can be deleted properly using interface base class pointers\n
         * this function is public so that one can call delete through a base-class pointer
         */
        virtual ~Histogram() {

            store();
        }

        /**
         * update\n
         *
         */
        void update(const sample_type &sample) {

            /* update internal state */
            {
                /* update number of trials */
                number_trials++;

                /* update histogram of frequencies and notify any observers */
                updateHistogram_notify(sample);

                /* update probabilities */
                normalize();
            }

            /* write current state to disk at regular intervals */
            if (just_passed_checkpoint())
                store();

        }

        /**
         * get largest frequency
         */
        const frequency_t get_largest_frequency() const {

            return *(std::max_element(histogram.begin(), histogram.end()));

        }

        /**
         * get end frequency
         */
        const frequency_t get_end_frequency() const {

            return histogram.back();

        }

        /**
         * get sample space
         */
        const std::vector<sample_type> get_sample_space() const {

            return sample_space;

        }

        /**
         * get probability
         */
        const std::vector<double> get_probability() const {

            return probability;

        }

        /**
         * return number trials
         */
        const number_trials_t get_number_trials() const {

            return number_trials;

        }

    };

} // end namespace probability

#endif	/* HISTOGRAM_BASE_H */


text:
Clementine.add('models', function(module) {

  function Beer(data) {
    this.id = data.Id;
    this.dateAdded = data.TimeStamp;
    this.upvotes = data.Upvotes;
    this.neutralvotes = data.Neutralvotes;
    this.downvotes = data.Downvotes;
    this.name = data.Name;
    this.label = data.Label;
    this.abv = data.ABV;
    this.ibu = data.IBU;
    this.description = data.Description;
    this.styleName = data.StyleName;
    this.rating = data.RatingScore.toFixed(2);
    this.ratingCount = data.RatingCount;
    this.breweryName = data.Brewery.Name;
    this.breweryLabel = data.Brewery.Label;
    this.breweryCountry = data.Brewery.Country;
    this.breweryState = data.Brewery.State;
    this.breweryCity = data.Brewery.City;
    this.breweryLatitude = data.Brewery.Latitude;
    this.breweryLongitude = data.Brewery.Longitude;
  }

  function HistoryBeer(data) {
    this.name = data.Name;
    this.upvotes = data.Upvotes;
    this.neutralvotes = data.Neutralvotes;
    this.downvotes = data.Downvotes;
  }

  function BeersByDate(data) {
    this.beers = _.map(data, function (beer) { return new HistoryBeer(beer);});
  }

  function BeersByVote(data) {
    this.beers = _.map(data, function (beer) { return new HistoryBeer(beer);});
  }

  module.exports = {
    Beer: Beer,
    BeersByDate: BeersByDate,
    BeersByVote: BeersByVote
  };

});

redpajama_set_name: RedPajamaGithub


text:
import { CombinedRuleGroup, CombinedRuleNamespace } from 'app/types/unified-alerting';

import { sortRulesByName, flattenGrafanaManagedRules } from './useCombinedRuleNamespaces';

describe('flattenGrafanaManagedRules', () => {
  it('should properly transform grafana managed namespaces', () => {
    // the rules from both ungrouped groups should go in the default group
    const ungroupedGroup1 = {
      name: 'my-rule',
      rules: [{ name: 'my-rule' }],
    } as CombinedRuleGroup;

    const ungroupedGroup2 = {
      name: 'another-rule',
      rules: [{ name: 'another-rule' }],
    } as CombinedRuleGroup;

    // the rules from both these groups should go in their own group name
    const group1 = {
      name: 'group1',
      rules: [{ name: 'rule-1' }, { name: 'rule-2' }],
    } as CombinedRuleGroup;

    const group2 = {
      name: 'group2',
      rules: [{ name: 'rule-1' }, { name: 'rule-2' }],
    } as CombinedRuleGroup;

    const namespace1 = {
      rulesSource: 'grafana',
      name: 'ns1',
      groups: [ungroupedGroup1, ungroupedGroup2, group1, group2],
    };

    const namespace2 = {
      rulesSource: 'grafana',
      name: 'ns2',
      groups: [ungroupedGroup1],
    };

    const input = [namespace1, namespace2] as CombinedRuleNamespace[];
    const [ns1, ns2] = flattenGrafanaManagedRules(input);

    expect(ns1.groups).toEqual([
      {
        name: 'default',
        rules: sortRulesByName([...ungroupedGroup1.rules, ...ungroupedGroup2.rules, ...group1.rules, ...group2.rules]),
      },
    ]);

    expect(ns2.groups).toEqual([
      {
        name: 'default',
        rules: ungroupedGroup1.rules,
      },
    ]);
  });
});


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using XenAdmin.Controls;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAPI;
using XenAdmin.Commands;

namespace XenAdmin.Wizards.BugToolWizardFiles
{
    public partial class GenericSelectHostsPage : XenTabPage
    {
        private readonly CollectionChangeEventHandler Host_CollectionChangedWithInvoke;
        private bool inupdate;

        public GenericSelectHostsPage()
        {
            InitializeComponent();

            buildList();
            Host_CollectionChangedWithInvoke = Program.ProgramInvokeHandler(Host_CollectionChanged);
            HostListTreeView.ShowImages = true;
            HostListTreeView.ShowCheckboxes = true;
            HostListTreeView.ShowDescription = true;
            HostListTreeView.ItemCheckChanged += HostListTreeView_ItemCheckChanged;

            ConnectionsManager.XenConnections.CollectionChanged += XenConnections_CollectionChanged;
        }

        #region XenTabPage overrides

        public override string HelpID { get { return "SelectServers"; } }

        public override string Text { get { return Messages.BUGTOOL_PAGE_SERVERS_TEXT; } }

        public override string PageTitle { get { return Messages.BUGTOOL_PAGE_SERVERS_TITLE; } }

        public override bool EnableNext()
        {
            return HostListTreeView.CheckedItems().Count > 0;
        }

        protected override void PageLoadedCore(PageLoadedDirection direction)
        {
            EnableDisableButtons();
        }

        #endregion

        public void SelectHosts(List<IXenObject> selectedObjects)
        {
            if (selectedObjects.Count == 0 || HostListTreeView.Items.Count == 0)
                return;

            HostListTreeView.BeginUpdate();
            HostListTreeView.ClearSelected();

            for (int index = 0; index < HostListTreeView.Items.Count; index++)
            {
                var node = HostListTreeView.Items[index] as HostCustomTreeNode;
                if (node == null)
                    continue;

                IXenConnection con = node.Tag as IXenConnection;
                if (con != null)
                {
                    var pool = Helpers.GetPool(con);
                    if (pool == null)
                    {
                        Host coordinator = Helpers.GetCoordinator(con);
                        if (coordinator != null && selectedObjects.Contains(coordinator))
                            node.State = CheckState.Checked;
                    }
                    else
                    {
                        if (selectedObjects.Contains(pool))
                        {
                            foreach (var subnode in node.ChildNodes)
                                subnode.State = CheckState.Checked;
                        }
                    }
                    continue;
                }

                var host = node.Tag as Host;
                if (host != null && selectedObjects.Contains(host))
                    node.State = CheckState.Checked;
            }

            var checkedItems = HostListTreeView.CheckedItems();
            //focus on first checked item so the user can find it in a long list
            if (checkedItems.Count > 0)
            {
                HostListTreeView.SelectedItems.Add(checkedItems.First());
            }

            HostListTreeView.EndUpdate();
        }

        public List<Host> SelectedHosts
        {
            get
            {
                List<Host> hosts = new List<Host>();
                foreach (HostCustomTreeNode node in HostListTreeView.CheckedItems())
                {
                    IXenConnection c = node.Tag as IXenConnection;
                    if (c != null)
                    {
                        if (Helpers.GetPool(c) == null)
                        {
                            Host coordinator = Helpers.GetCoordinator(c);
                            if (coordinator != null)
                                hosts.Add(coordinator);
                        }
                        continue;
                    }

                    Host host = node.Tag as Host;
                    if (host != null)
                        hosts.Add(host);
                }

                return hosts;
            }
        }

        private void buildList()
        {
            Program.AssertOnEventThread();

            if (inupdate)
                return;

            inupdate = true;
            HostListTreeView.BeginUpdate();

            try
            {
                // Save old checked states to preserve across update
                var oldCheckStates = new Dictionary<string, CheckState>();
                foreach (HostCustomTreeNode node in HostListTreeView.Items)
                {
                    if (node.HostOrPoolUuid != null)
                        oldCheckStates.Add(node.HostOrPoolUuid, node.State);
                }

                HostListTreeView.ClearAllNodes();
                DeregisterEvents();

                foreach (IXenConnection connection in ConnectionsManager.XenConnectionsCopy)
                {
                    connection.ConnectionStateChanged += connection_ConnectionStateChanged;
                    connection.Cache.RegisterCollectionChanged<Host>(Host_CollectionChangedWithInvoke);
                    connection.CachePopulated += connection_CachePopulated;

                    if (!connection.IsConnected)
                        continue;  // don't show disconnected connections CA-60514

                    HostCustomTreeNode node = new HostCustomTreeNode(true)
                                                  {
                                                      Text = Helpers.GetName(connection),
                                                      Tag = connection,
                                                      Enabled = true,
                                                      Description = "",
                                                      State = CheckState.Unchecked,
                                                      Image = Images.GetImage16For(connection)
                                                  };

                    HostListTreeView.AddNode(node);

                    // Save uuid of pool to this node
                    Pool pool = Helpers.GetPoolOfOne(connection);
                    if (pool == null)
                        continue;

                    pool.PropertyChanged += pool_PropertyChanged;

                    node.HostOrPoolUuid = pool.uuid;
                    node.State = (oldCheckStates.ContainsKey(node.HostOrPoolUuid) && node.Enabled) ?
                        oldCheckStates[node.HostOrPoolUuid] :
                        CheckState.Unchecked;

                    if (Helpers.GetPool(connection) != null)
                    {
                        node.Image = Images.GetImage16For(pool);

                        foreach (Host host in connection.Cache.Hosts)
                        {
                            bool isHostLive = host.IsLive();
                            HostCustomTreeNode childnode = new HostCustomTreeNode(true)
                                                               {
                                                                   Text = Helpers.GetName(host),
                                                                   Tag = host,
                                                                   HostOrPoolUuid = host.uuid,
                                                                   Enabled = isHostLive,
                                                                   Description = isHostLive ? "" : Messages.HOST_NOT_LIVE,
                                                                   Image = Images.GetImage16For(host)
                                                               };

                            childnode.State = (oldCheckStates.ContainsKey(childnode.HostOrPoolUuid) && childnode.Enabled) ?
                                oldCheckStates[childnode.HostOrPoolUuid] :
                                CheckState.Unchecked;

                            HostListTreeView.AddChildNode(node, childnode);

                            RegisterHostEvents(host);
                        }
                    }
                    else
                    {
                        Host coordinator = Helpers.GetCoordinator(connection);
                        if (coordinator != null)
                        {
                            bool isCoordinatorLive = coordinator.IsLive();
                            node.Enabled = isCoordinatorLive;
                            node.Description = isCoordinatorLive ? "" : Messages.HOST_NOT_LIVE;
                            node.Image = Images.GetImage16For(coordinator);

                            RegisterHostEvents(coordinator);
                        }
                    }
                }
            }
            finally
            {
                inupdate = false;
                HostListTreeView.EndUpdate();
                EnableDisableButtons();
            }
        }

        private void DeregisterEvents()
        {
            foreach (IXenConnection connection in ConnectionsManager.XenConnectionsCopy)
            {
                connection.ConnectionStateChanged -= connection_ConnectionStateChanged;
                connection.Cache.DeregisterCollectionChanged<Host>(Host_CollectionChangedWithInvoke);
                connection.CachePopulated -= connection_CachePopulated;

                Pool pool = Helpers.GetPoolOfOne(connection);
                if (pool == null)
                    continue;

                pool.PropertyChanged -= pool_PropertyChanged;

                if (Helpers.GetPool(connection) != null)
                {
                    foreach (Host host in connection.Cache.Hosts)
                        DeregisterHostEvents(host);
                }
                else
                {
                    Host coordinator = Helpers.GetCoordinator(connection);
                    if (coordinator != null)
                        DeregisterHostEvents(coordinator);
                }
            }
        }

        private void RegisterHostEvents(Host host)
        {
            Host_metrics metrics = host.Connection.Resolve(host.metrics);
            if (metrics != null)
                metrics.PropertyChanged += hostMetrics_PropertyChanged;
            host.PropertyChanged += host_PropertyChanged;
        }

        private void DeregisterHostEvents(Host host)
        {
            Host_metrics metrics = host.Connection.Resolve(host.metrics);
            if (metrics != null)
                metrics.PropertyChanged -= hostMetrics_PropertyChanged;
            host.PropertyChanged -= host_PropertyChanged;
        }

        private void connection_CachePopulated(IXenConnection conn)
        {
            Program.Invoke(this, buildList);
        }

        private void Host_CollectionChanged(object sender, CollectionChangeEventArgs e)
        {
            buildList();
        }

        private void pool_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "name_label" || e.PropertyName == "master")
            {
                Program.Invoke(this, buildList);
            }
        }

        private void hostMetrics_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "live")
            {
                Program.Invoke(this, buildList);
            }
        }

        private void host_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "name_label" || e.PropertyName == "enabled" || e.PropertyName == "patches" || e.PropertyName == "metrics")
            {
                Program.Invoke(this, buildList);
            }
        }

        private void connection_ConnectionStateChanged(IXenConnection conn)
        {
            Program.Invoke(this, (CollectionChangeEventHandler)XenConnections_CollectionChanged, this, null);
        }

        private void XenConnections_CollectionChanged(object sender, CollectionChangeEventArgs e)
        {
            Program.BeginInvoke(Program.MainWindow,buildList);
        }

        private void EnableDisableButtons()
        {
            if (!Visible)
                return; // CA-28387

            OnPageUpdated();

            SelectAllButton.Enabled = HostListTreeView.CheckableItems().Count != 0;
            SelectNoneButton.Enabled = HostListTreeView.CheckedItems().Count > 0;
        }

        #region Control event handlers

        private void SelectNoneButton_Click(object sender, EventArgs e)
        {
            HostListTreeView.SecretNode.State = CheckState.Unchecked;
            HostListTreeView.Refresh();
            EnableDisableButtons();
        }

        private void SelectAllButton_Click(object sender, EventArgs e)
        {
            HostListTreeView.SecretNode.State = CheckState.Checked;
            HostListTreeView.Refresh();
            EnableDisableButtons();
        }

        private void connectbutton_Click(object sender, EventArgs e)
        {
            new AddHostCommand(Program.MainWindow, ParentForm).Run();
        }

        private void HostListTreeView_ItemCheckChanged(object sender, EventArgs e)
        {
            EnableDisableButtons();
        }

        #endregion
    }

    public class HostCustomTreeNode : CustomTreeNode
    {
        public string HostOrPoolUuid;

        public HostCustomTreeNode(bool selectable)
            : base(selectable)
        {}

        // Fixed for CA-57131.
        // Though it would be better to use the usual search mechanism for building
        // the tree, so that the order is absolutely guaranteed to be the same.
        protected override int SameLevelSortOrder(CustomTreeNode other)
        {
            if (other.Tag is IXenConnection && this.Tag is IXenConnection)
            {
                return (this.Tag as IXenConnection).CompareTo(other.Tag as IXenConnection);
            }
            else if (other.Tag is IXenConnection)
            {
                return -1;
            }
            else if (this.Tag is IXenConnection)
            {
                return 1;
            }
            else if (this.Tag is Host && other.Tag is Host)
            {
                return (this.Tag as Host).CompareTo(other.Tag as Host);
            }
            else
            {
                return base.SameLevelSortOrder(other);
            }
        }
    }
}


text:
package org.itas.xcnet.common.status.support;

import org.itas.xcnet.common.Extension;
import org.itas.xcnet.common.status.Status;
import org.itas.xcnet.common.status.StatusChecker;
import org.itas.xcnet.common.status.Status.Level;

/**
 * Memory Status
 *
 * @author liuzhen<liuxing521a@163.com>
 * @createTime 2015年5月15日下午2:18:14
 */
@Extension("memory")
public class MemoryStatusChecker implements StatusChecker {

	@Override
	public Status check() {
		Runtime runtime = Runtime.getRuntime();
		long freeMemory = runtime.freeMemory();
		long totalMemory = runtime.totalMemory();
		long maxMemory = runtime.maxMemory();
		boolean warn = (maxMemory - (totalMemory - freeMemory)) > 2048; // 剩余空间小于2M报警

		StringBuilder sb = new StringBuilder();
		sb.append("maxMemory:").append(maxMemory/(1024*1024)).append("M, ");
		sb.append("totalMemory:").append(totalMemory/(1024*1024)).append("M, ");
		sb.append("usedMemory:").append((totalMemory - freeMemory)/(1024*1024)).append("M");

		return new Status(warn ? Level.OK : Level.WARN, sb.toString());
	}

}


text:
<?php
namespace Site\CartoBundle\Security;
use Symfony\Component\Security\Core\Authentication\SimplePreAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use \Site\CartoBundle\Entity\Utilisateur;
class SSOAuthenticator implements SimplePreAuthenticatorInterface
{
    protected $userProvider;
    protected $em;

    public function __construct(CustomUserProvider $userProvider)
    {
        $this->userProvider = $userProvider;

    }

    public function createToken(Request $request, $providerKey)
    {

        return new PreAuthenticatedToken("",null,$providerKey,array());
    }

    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {

        //Récupère l'id de l'utilisateur dans le cookie
        $userid = $this->userProvider->getCookieToken();

        //Si le cookie n'existe pas !
        if (!$userid) {
            return new \Symfony\Component\Security\Core\Authentication\Token\AnonymousToken($providerKey,"anon.");
        }

        //On récupère l'utilisateur dans la base de données
        $utilisateur = new Utilisateur();
        $utilisateur = $this->userProvider->loadUserByUsername($userid);
        if($utilisateur == null)
        {
            //Si l'utilisateur n'existe pas, il va falloir le créer dans la base de données de carto
            $utilisateur = $this->userProvider->createNewUser($userid);
        }
        //IMPORTANT
        $token = new UsernamePasswordToken(
            $utilisateur,
            null,
            $providerKey,
            $utilisateur->getRoles()
        );

        return $token;
    }

    public function supportsToken(TokenInterface $token, $providerKey)
    {
        return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
    }
}


text:
package org.camunda.bpm.engine.test.api.runtime;

import static org.camunda.bpm.engine.test.api.runtime.util.SetBusinessKeyListener.BUSINESS_KEY_VARIABLE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.concurrent.TimeUnit;

import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.engine.test.api.runtime.util.SetBusinessKeyListener;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;

@RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_FULL)
public class SetBusinessKeyTest {

  protected ProcessEngineRule rule = new ProvidedProcessEngineRule();
  protected ProcessEngineTestRule testRule = new ProcessEngineTestRule(rule);

  @Rule
  public RuleChain ruleChain = RuleChain.outerRule(rule).around(testRule);

  protected static final String PROCESS_KEY = "process";

  protected static final BpmnModelInstance SYNC_SERVICE_TASK_PROCESS =
      Bpmn.createExecutableProcess(PROCESS_KEY)
      .startEvent("startEvent")
      .serviceTask()
        .camundaClass(SetBusinessKeyDelegate.class)
      .userTask("userTask2")
      .endEvent("endEvent")
      .done();

  protected static final BpmnModelInstance ASYNC_SERVICE_TASK_PROCESS =
      Bpmn.createExecutableProcess(PROCESS_KEY)
      .startEvent("startEvent")
      .serviceTask()
        .camundaAsyncBefore()
        .camundaClass(SetBusinessKeyDelegate.class)
      .userTask("userTask2")
      .endEvent("endEvent")
      .done();

  protected RuntimeService runtimeService;
  protected TaskService taskService;
  protected HistoryService historyService;
  protected ManagementService managementService;

  @Before
  public void initServices() {
    runtimeService = rule.getRuntimeService();
    taskService = rule.getTaskService();
    historyService = rule.getHistoryService();
    managementService = rule.getManagementService();
  }

  @Test
  public void testNewKeyInSyncServiceTask() {
    // given
    testRule.deploy(SYNC_SERVICE_TASK_PROCESS);

    // when
    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testNewKeyInAsyncServiceTask() {
    // given
    testRule.deploy(ASYNC_SERVICE_TASK_PROCESS);

    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // when
    executeJob();

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testNewKeyInStartExecListener() {
    // given
    String listener = ExecutionListener.EVENTNAME_START;
    BpmnModelInstance process = createModelExecutionListener(listener);
    testRule.deploy(process);

    // when
    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testNewKeyInEndExecListener() {
    // given
    String listener = ExecutionListener.EVENTNAME_END;
    BpmnModelInstance process = createModelExecutionListener(listener);
    testRule.deploy(process);

    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    completeTask("userTask1");

    // assume
    assertNotNull(taskService.createTaskQuery().taskDefinitionKey("userTask2").singleResult());

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testNewKeyInStartTaskListener() {
    // given
    String listener = TaskListener.EVENTNAME_CREATE;
    BpmnModelInstance process = createModelTaskListener(listener);
    testRule.deploy(process);

    // when
    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testNewKeyInAssignTaskListener() {
    // given
    String listener = TaskListener.EVENTNAME_ASSIGNMENT;
    BpmnModelInstance process = createModelTaskListener(listener);
    testRule.deploy(process);

    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // when
    taskService.setAssignee(taskService.createTaskQuery().singleResult().getId(), "newUserId");

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testNewKeyInEndTaskListener() {
    // given
    String listener = TaskListener.EVENTNAME_COMPLETE;
    BpmnModelInstance process = createModelTaskListener(listener);
    testRule.deploy(process);

    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    completeTask("userTask1");

    // assume
    assertNotNull(taskService.createTaskQuery().taskDefinitionKey("userTask2").singleResult());

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  @Deployment
  public void testNewKeyInTimeoutTaskListener() {
    // given
    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // when
    ClockUtil.offset(TimeUnit.MINUTES.toMillis(70L));
    testRule.waitForJobExecutorToProcessAllJobs(5000L);

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testUpdateKeyInSyncServiceTask() {
    // given
    testRule.deploy(SYNC_SERVICE_TASK_PROCESS);

    // when
    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, "aBusinessKey", Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testUpdateKeyInAsyncServiceTask() {
    // given
    testRule.deploy(ASYNC_SERVICE_TASK_PROCESS);

    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, "aBusinessKey", Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // when
    executeJob();

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testUpdateKeyInStartExecListener() {
    // given
    String listener = ExecutionListener.EVENTNAME_START;
    BpmnModelInstance process = createModelExecutionListener(listener);
    testRule.deploy(process);

    // when
    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, "aBusinessKey", Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testUpdateKeyInEndExecListener() {
    // given
    String listener = ExecutionListener.EVENTNAME_END;
    BpmnModelInstance process = createModelExecutionListener(listener);
    testRule.deploy(process);

    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, "aBusinessKey", Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    completeTask("userTask1");

    // assume
    assertNotNull(taskService.createTaskQuery().taskDefinitionKey("userTask2").singleResult());

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testUpdateKeyInEndTaskListener() {
    // given
    String listener = TaskListener.EVENTNAME_COMPLETE;
    BpmnModelInstance process = createModelTaskListener(listener);
    testRule.deploy(process);

    String newBusinessKeyValue = "newBusinessKey";
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, "aBusinessKey", Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // when
    completeTask("userTask1");

    // assume
    assertNotNull(taskService.createTaskQuery().taskDefinitionKey("userTask2").singleResult());

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  @Test
  public void testUpdateKeyNullValueInStartTaskListener() {
    // given
    String listener = TaskListener.EVENTNAME_CREATE;
    BpmnModelInstance process = createModelTaskListener(listener);
    testRule.deploy(process);

    // when
    String newBusinessKeyValue = null;
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, "aBusinessKey", Variables.createVariables().putValue(BUSINESS_KEY_VARIABLE, newBusinessKeyValue));

    // then
    checkBusinessKeyChanged(newBusinessKeyValue);
  }

  protected void checkBusinessKeyChanged(String newBusinessKeyValue) {
    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processDefinitionKey(PROCESS_KEY).singleResult();
    assertNotNull(processInstance);
    assertEquals(newBusinessKeyValue, processInstance.getBusinessKey());

    HistoricProcessInstance historicInstance = historyService.createHistoricProcessInstanceQuery().singleResult();
    assertNotNull(historicInstance);
    assertEquals(newBusinessKeyValue, historicInstance.getBusinessKey());
  }

  protected BpmnModelInstance createModelExecutionListener(String listener) {
    return Bpmn.createExecutableProcess(PROCESS_KEY)
    .startEvent("startEvent")
    .userTask("userTask1").name("User task")
      .camundaExecutionListenerExpression(listener,
            "${execution.setProcessBusinessKey(execution.getVariable(\"" + BUSINESS_KEY_VARIABLE + "\"))}")
    .userTask("userTask2")
    .endEvent("endEvent")
    .done();
  }

  protected BpmnModelInstance createModelTaskListener(String listener) {
    return Bpmn.createExecutableProcess(PROCESS_KEY)
    .startEvent("startEvent")
    .userTask("userTask1").name("User task")
      .camundaTaskListenerClass(listener, SetBusinessKeyListener.class)
    .userTask("userTask2")
    .endEvent("endEvent")
    .done();
  }

  protected void executeJob() {
    Job job = managementService.createJobQuery().singleResult();
    assertNotNull(job);
    managementService.executeJob(job.getId());
  }

  protected void completeTask(String key) {
    Task task = taskService.createTaskQuery().taskDefinitionKey(key).singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());
  }

  public static class SetBusinessKeyDelegate implements JavaDelegate {

    @Override
    public void execute(DelegateExecution execution) throws Exception {
      String newKeyValue = (String) execution.getVariable(BUSINESS_KEY_VARIABLE);
      execution.setProcessBusinessKey(newKeyValue);
    }

  }

}


text:
<!DOCTYPE html>
<title>Prefetched signed exchange and certificate must not be fetched again</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/get-host-info.sub.js"></script>
<script src="/common/utils.js"></script>
<script src="./resources/sxg-util.js"></script>
<body>
<script>
promise_test(async (t) => {
  const id = token();
  const sxgUrl = get_host_info().HTTPS_REMOTE_ORIGIN + '/signed-exchange/resources/prefetch-test-sxg.py?id=' + id;

  await new Promise(resolve => {
    const link = document.createElement('link');
    link.rel = 'prefetch';
    link.href = sxgUrl;
    link.as = 'document';
    link.addEventListener('error', t.step_func(() => {
        assert_unreached('Prefetch should not fail');
    }));
    link.addEventListener('load', t.step_func(() => {
        resolve();
    }));
    document.body.appendChild(link);
  });
  const message_promise = new Promise((resolve) => {
    window.addEventListener('message', (event) => {
      resolve(event.data);
    }, false);
  });
  const win = window.open(sxgUrl, "_blank");
  const message = await message_promise;
  win.close();
  assert_equals(message, 'loaded');
}, 'Prefetched signed exchange and certificate must not be fetched again.');

</script>
</body>


text:
class Laplacian_LIMSolver3D : public LIMSolver3D
{
public:

  Laplacian_LIMSolver3D();
  ~Laplacian_LIMSolver3D();

private:

  Eigen::SparseMatrix<double> L;

  // implementation of abstract functions of LIMSolver2D
  void debugOutput(std::stringstream& info);
  void prepareProblemData(std::vector<int>& hessRowIdx, std::vector<int>& hessColIdx);
  double computeFunction(const Eigen::Matrix<double,Eigen::Dynamic,1>& x);
  void computeGradient(const Eigen::Matrix<double,Eigen::Dynamic,1>& x, Eigen::Matrix<double,Eigen::Dynamic,1>& grad);
  void computeHessian(const Eigen::Matrix<double,Eigen::Dynamic,1>& x, const Eigen::Matrix<double*,Eigen::Dynamic,1>& hess);
};

#endif


text:
package com.amazonaws.services.pinpoint.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.pinpoint.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * JourneyCustomMessageMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class JourneyCustomMessageMarshaller {

    private static final MarshallingInfo<String> DATA_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Data").build();

    private static final JourneyCustomMessageMarshaller instance = new JourneyCustomMessageMarshaller();

    public static JourneyCustomMessageMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(JourneyCustomMessage journeyCustomMessage, ProtocolMarshaller protocolMarshaller) {

        if (journeyCustomMessage == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(journeyCustomMessage.getData(), DATA_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}