text:
package com.intellij.openapi.extensions.impl;

import com.intellij.openapi.extensions.*;
import com.intellij.util.pico.AssignableToComponentAdapter;
import com.intellij.util.xmlb.XmlSerializer;
import org.jdom.Element;
import org.picocontainer.*;
import org.picocontainer.defaults.AssignabilityRegistrationException;
import org.picocontainer.defaults.CachingComponentAdapter;
import org.picocontainer.defaults.ConstructorInjectionComponentAdapter;
import org.picocontainer.defaults.NotConcreteRegistrationException;

/**
 * @author Alexander Kireyev
 * todo: optimize memory print
 */
public class ExtensionComponentAdapter implements LoadingOrder.Orderable, AssignableToComponentAdapter {
  public static final ExtensionComponentAdapter[] EMPTY_ARRAY = new ExtensionComponentAdapter[0];
  private Object myComponentInstance;
  private final String myImplementationClassName;
  private final Element myExtensionElement;
  private final PicoContainer myContainer;
  private final PluginDescriptor myPluginDescriptor;
  private final boolean myDeserializeInstance;
  private ComponentAdapter myDelegate;
  private Class myImplementationClass;

  public ExtensionComponentAdapter(
    String implementationClass,
    Element extensionElement,
    PicoContainer container,
    PluginDescriptor pluginDescriptor,
    boolean deserializeInstance) {
    myImplementationClassName = implementationClass;
    myExtensionElement = extensionElement;
    myContainer = container;
    myPluginDescriptor = pluginDescriptor;
    myDeserializeInstance = deserializeInstance;
  }

  public Object getComponentKey() {
    return this;
  }

  public Class getComponentImplementation() {
    return loadClass(myImplementationClassName);
  }

  public Object getComponentInstance(final PicoContainer container) throws PicoInitializationException, PicoIntrospectionException, AssignabilityRegistrationException, NotConcreteRegistrationException {
    //assert myContainer == container : "Different containers: " + myContainer + " - " + container;
    if (myComponentInstance == null) {
      if (Element.class.equals(getComponentImplementation())) {
        myComponentInstance = myExtensionElement;
      }
      else {
        Object componentInstance = getDelegate().getComponentInstance(container);

        if (myDeserializeInstance) {
          try {
            XmlSerializer.deserializeInto(componentInstance, myExtensionElement);
          }
          catch (Exception e) {
            throw new PicoInitializationException(e);
          }
        }

        ExtensionInitializer initializer = (ExtensionInitializer)container.getComponentInstance(ExtensionInitializer.class);
        if (initializer != null) {
          initializer.initExtension(componentInstance);
        }
        myComponentInstance = componentInstance;
      }
      if (myComponentInstance instanceof PluginAware) {
        PluginAware pluginAware = (PluginAware) myComponentInstance;
        pluginAware.setPluginDescriptor(myPluginDescriptor);
      }
    }

    return myComponentInstance;
  }

  public void verify(PicoContainer container) throws PicoIntrospectionException {
    throw new UnsupportedOperationException("Method verify is not supported in " + getClass());
  }

  public void accept(PicoVisitor visitor) {
    throw new UnsupportedOperationException("Method accept is not supported in " + getClass());
  }

  public Object getExtension() {
    return getComponentInstance(myContainer);
  }

  public LoadingOrder getOrder() {
    return LoadingOrder.readOrder(myExtensionElement.getAttributeValue("order"));
  }

  public String getOrderId() {
    return myExtensionElement.getAttributeValue("id");
  }

  private Element getExtensionElement() {
    return myExtensionElement;
  }

  public Element getDescribingElement() {
    return getExtensionElement();
  }

  public PluginId getPluginName() {
    return myPluginDescriptor.getPluginId();
  }

  public PluginDescriptor getPluginDescriptor() {
    return myPluginDescriptor;
  }

  private Class loadClass(final String className) {
    if (myImplementationClass == null) {
      try {
        ClassLoader classLoader = myPluginDescriptor != null ? myPluginDescriptor.getPluginClassLoader() : getClass().getClassLoader();
        if (classLoader == null) {
          classLoader = getClass().getClassLoader();
        }
        myImplementationClass = Class.forName(className, true, classLoader);
      }
      catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
      }
    }
    return myImplementationClass;
  }

  private synchronized ComponentAdapter getDelegate() {
    if (myDelegate == null) {
      myDelegate = new CachingComponentAdapter(new ConstructorInjectionComponentAdapter(getComponentKey(), loadClass(myImplementationClassName), null, true));
    }

    return myDelegate;
  }

  public boolean isAssignableTo(Class aClass) {
    return aClass.getName().equals(myImplementationClassName);
  }

  public String getAssignableToClassName() {
    return myImplementationClassName;
  }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.02.08 at 03:02:05 PM PST
//

package com.wb.nextgenlibrary.parser.md.schema.v2_3;

import java.util.ArrayList;
import java.util.List;
import com.wb.nextgenlibrary.parser.XmlAccessType;
import com.wb.nextgenlibrary.parser.XmlAccessorType;
import com.wb.nextgenlibrary.parser.XmlAnyElement;
import com.wb.nextgenlibrary.parser.XmlType;
import org.w3c.dom.Element;

/**
 *
Java class for ContainerSpecific-type complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ContainerSpecific-type">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ContainerSpecific-type", propOrder = {
    "any"
})
public class ContainerSpecificType {

    @XmlAnyElement(lax = true)
    protected List<Object> any;

    /**
     * Gets the value of the any property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the any property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getAny().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Object }
     * {@link Element }
     *
     *
     */
    public List<Object> getAny() {
        if (any == null) {
            any = new ArrayList<Object>();
        }
        return this.any;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package io.sundr.dependency;

import io.sundr.Function;

import java.util.LinkedHashSet;
import java.util.Set;

public class TopologicalSort<T> {

    private final Function<T, Set<T>> collectDependencies;

    public TopologicalSort(Function<T, Set<T>> collectDependencies) {
        this.collectDependencies = collectDependencies;
    }

    public Set<T> sort(Iterable<T> items) {
        Set<T> sorted = new LinkedHashSet<T>();
        Set<T> visited = new LinkedHashSet<T>();
        for (T e : items) {
            visit(e, visited, sorted);
        }
        return sorted;
    }

    public void visit(T item, Set<T> visited, Set<T> sorted) {
        if (!visited.add(item)) {
            return;
        }
        for (T t : collectDependencies.apply(item)) {
            visit(t, visited, sorted);
        }
        sorted.add(item);
    }

    public Set<T> collectDependencies(T item) {
        return collectDependencies.apply(item);
    }
}


text:
data_dir=$(dirname $0)/data

function create_user
{
user="$@"
openssl genrsa -out ${user}.key 1024
openssl req -new -key ${user}.key -out ${user}.csr <<END
UK
Gloucestershire
Cheltenham
Ripjar
Engineering
${user}
${user}@example.com
.

END
openssl x509 -req -in ${user}.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 9999 -out ${user}.crt
}

function create_ca
{
openssl genrsa -out ca.key 2048
openssl req -new -x509 -key ca.key -days 9999 -out ca.crt <<END
UK
Gloucestershire
Cheltenham
Ripjar
Engineering
ca
ca@example.com
END
}

# Server key/cert
function create_server
{
openssl genrsa -out server.key 1024
openssl req -new -key server.key -out server.csr <<END
.
.
.
.
.
localhost
.
.
.
END
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 9999 -out server.crt
}

rm -rf $data_dir
mkdir -p $data_dir
cd $data_dir

create_ca
create_server
create_user "ann"
create_user "bob"

echo "Remember to update expected cert values in integration tests!"

cd -


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Coverage Report :: Librarian</title>

    [ all classes ]
    [ com.twu.biblioteca ]

Coverage Summary for Class: Librarian (com.twu.biblioteca)

  Class

  Method, %

  Line, %

  Librarian

    100%

    (3/ 3)

    100%

    (22/ 22)

    Librarian$$EnhancerByMockitoWithCGLIB$$47763405

  total

    100%

    (3/ 3)

    100%

    (22/ 22)

1 package com.twu.biblioteca;
2
3 import java.util.ArrayList;
4
5 public class Librarian {
6     ArrayList availableBooksList,checkedoutBooksList;
7     Library library;
8     BibliotecaView bibliotecaView;
9     public Librarian(ArrayList<Book> availableBooksList, ArrayList<Book> checkedoutBookList, Library library, BibliotecaView bibliotecaView) {
10         this.availableBooksList = availableBooksList;
11         this.checkedoutBooksList = checkedoutBookList;
12         this.library = library;
13         this.bibliotecaView = bibliotecaView;
14     }
15
16     public boolean checkOutBook(String bookName) {
17         for (int bookNumber = 0; bookNumber < availableBooksList.size(); bookNumber++)
18             if (availableBooksList.get(bookNumber).hashCode() == bookName.hashCode()) {
19                 Book book =library.removeBook(availableBooksList,bookNumber);
20                 library.addBook(checkedoutBooksList,book);
21                 bibliotecaView.display(Messages.SUCCESSFUL_CHECKOUT);
22                 return true;
23             }
24         bibliotecaView.display(Messages.UNSUCCESSFUL_CHECKOUT);
25         return false;
26     }
27
28     public boolean returnBook(String bookName) {
29         for (int bookNumber = 0; bookNumber < checkedoutBooksList.size(); bookNumber++)
30             if (checkedoutBooksList.get(bookNumber).hashCode() == bookName.hashCode()) {
31                 Book book = library.removeBook(checkedoutBooksList,bookNumber);
32                 library.addBook(availableBooksList,book);
33                 bibliotecaView.display(Messages.SUCCESSFUL_RETURN);
34                 return true;
35             }
36         bibliotecaView.display(Messages.UNSUCCESSFUL_RETURN);
37         return false;
38     }
39
40
41 }

generated on 2015-06-17 16:42


text:
#ifndef CCE_SERVICE_HH
#define CCE_SERVICE_HH

#include <time.h>

#include <array>
#include <memory>
#include <ostream>
#include <string>
#include <unordered_map>
#include <utility>

#include "com/centreon/engine/check_result.hh"
#include "com/centreon/engine/common.hh"
#include "com/centreon/engine/customvariable.hh"
#include "com/centreon/engine/hash.hh"
#include "com/centreon/engine/logging.hh"
#include "com/centreon/engine/notifier.hh"

/* Forward declaration. */
CCE_BEGIN()
class contact;
namespace commands {
class command;
}
class host;
class service;
class servicegroup;
class serviceescalation;
CCE_END()

typedef std::unordered_map<std::pair<std::string, std::string>,
                           std::shared_ptr<com::centreon::engine::service>,
                           pair_hash>
    service_map;
typedef std::unordered_map<std::pair<std::string, std::string>,
                           com::centreon::engine::service*,
                           pair_hash>
    service_map_unsafe;
typedef std::unordered_map<std::pair<uint64_t, uint64_t>,
                           std::shared_ptr<com::centreon::engine::service>,
                           pair_hash>
    service_id_map;

CCE_BEGIN()

class service : public notifier {
 public:
  static std::array<std::pair<uint32_t, std::string>, 4> const
      tab_service_states;

  enum service_state { state_ok, state_warning, state_critical, state_unknown };

  service(std::string const& hostname,
          std::string const& description,
          std::string const& display_name,
          std::string const& check_command,
          bool checks_enabled,
          bool accept_passive_checks,
          enum service::service_state initial_state,
          uint32_t check_interval,
          uint32_t retry_interval,
          uint32_t notification_interval,
          int max_attempts,
          uint32_t first_notification_delay,
          uint32_t recovery_notification_delay,
          std::string const& notification_period,
          bool notifications_enabled,
          bool is_volatile,
          std::string const& check_period,
          std::string const& event_handler,
          bool event_handler_enabled,
          std::string const& notes,
          std::string const& notes_url,
          std::string const& action_url,
          std::string const& icon_image,
          std::string const& icon_image_alt,
          bool flap_detection_enabled,
          double low_flap_threshold,
          double high_flap_threshold,
          bool check_freshness,
          int freshness_threshold,
          bool obsess_over,
          std::string const& timezone);
  ~service() = default;
  void set_host_id(uint64_t host_id);
  uint64_t get_host_id() const;
  void set_service_id(uint64_t service_id);
  uint64_t get_service_id() const;
  void set_hostname(std::string const& name);
  std::string const& get_hostname() const;
  void set_description(std::string const& desc);
  std::string const& get_description() const;
  void set_event_handler_args(std::string const& event_hdl_args);
  std::string const& get_event_handler_args() const;
  void set_check_command_args(std::string const& cmd_args);
  std::string const& get_check_command_args() const;
  time_t get_last_time_ok() const;
  void set_last_time_ok(time_t last_time);
  time_t get_last_time_warning() const;
  void set_last_time_warning(time_t last_time);
  time_t get_last_time_unknown() const;
  void set_last_time_unknown(time_t last_time);
  time_t get_last_time_critical() const;
  void set_last_time_critical(time_t last_time);
  enum service_state get_current_state() const;
  void set_current_state(enum service_state current_state);
  enum service_state get_last_state() const;
  void set_last_state(enum service_state last_state);
  enum service_state get_last_hard_state() const;
  void set_last_hard_state(enum service_state last_hard_state);
  enum service_state get_initial_state() const;
  void set_initial_state(enum service_state current_state);
  int get_process_performance_data(void) const;
  void set_process_performance_data(int perf_data);
  bool get_check_flapping_recovery_notification(void) const;
  void set_check_flapping_recovery_notification(bool check);
  bool recovered() const override;
  int get_current_state_int() const override;
  std::string const& get_current_state_as_string() const override;

  int handle_async_check_result(check_result* queued_check_result);
  int log_event();
  void check_for_flapping(bool update, bool allow_flapstart_notification);
  int handle_service_event();
  int obsessive_compulsive_service_check_processor();
  int update_service_performance_data();
  int run_scheduled_check(int check_options, double latency);
  virtual int run_async_check(int check_options,
                              double latency,
                              bool scheduled_check,
                              bool reschedule_check,
                              bool* time_is_valid,
                              time_t* preferred_time) noexcept;
  bool schedule_check(time_t check_time, int options) override;
  void set_flap(double percent_change,
                double high_threshold,
                double low_threshold,
                int allow_flapstart_notification);
  // handles a service that has stopped flapping
  void clear_flap(double percent_change,
                  double high_threshold,
                  double low_threshold);
  void enable_flap_detection();
  void disable_flap_detection();
  void update_status() override;
  bool verify_check_viability(int check_options,
                              bool* time_is_valid,
                              time_t* new_time);
  void grab_macros_r(nagios_macros* mac) override;
  int notify_contact(nagios_macros* mac,
                     contact* cntct,
                     reason_type type,
                     std::string const& not_author,
                     std::string const& not_data,
                     int options,
                     int escalated) override;
  void update_notification_flags() override;
  void check_for_expired_acknowledgement();
  void schedule_acknowledgement_expiration();
  bool operator==(service const& other) = delete;
  bool operator!=(service const& other) = delete;  // throw();
  bool is_valid_escalation_for_notification(escalation const* e,
                                            int options) const override;
  bool is_result_fresh(time_t current_time, int log_this);
  void handle_flap_detection_disabled();
  timeperiod* get_notification_timeperiod() const override;
  bool get_notify_on_current_state() const override;

  bool authorized_by_dependencies(
      dependency::types dependency_type) const override;
  static void check_for_orphaned();
  static void check_result_freshness();
  bool is_in_downtime() const override;
  void resolve(int& w, int& e);

  std::list<servicegroup*> const& get_parent_groups() const;
  std::list<servicegroup*>& get_parent_groups();
  void set_host_ptr(host* h);
  host const* get_host_ptr() const;
  host* get_host_ptr();
  bool get_host_problem_at_last_check() const;

  static service_map services;
  static service_id_map services_by_id;

 private:
  uint64_t _host_id;
  uint64_t _service_id;
  std::string _hostname;
  std::string _description;
  std::string _event_handler_args;
  std::string _check_command_args;

  int _process_performance_data;
  bool _check_flapping_recovery_notification;

  time_t _last_time_ok;
  time_t _last_time_warning;
  time_t _last_time_unknown;
  time_t _last_time_critical;
  enum service_state _initial_state;
  enum service_state _current_state;
  enum service_state _last_hard_state;
  enum service_state _last_state;
  std::list<servicegroup*> _servicegroups;
  host* _host_ptr;
  bool _host_problem_at_last_check;
};
CCE_END()

com::centreon::engine::service* add_service(
    uint64_t host_id,
    uint64_t service_id,
    std::string const& host_name,
    std::string const& description,
    std::string const& display_name,
    std::string const& check_period,
    enum com::centreon::engine::service::service_state initial_state,
    int max_attempts,
    double check_interval,
    double retry_interval,
    double notification_interval,
    uint32_t first_notification_delay,
    uint32_t recovery_notification_delay,
    std::string const& notification_period,
    bool notify_recovery,
    bool notify_unknown,
    bool notify_warning,
    bool notify_critical,
    bool notify_flapping,
    bool notify_downtime,
    bool notifications_enabled,
    bool is_volatile,
    std::string const& event_handler,
    bool event_handler_enabled,
    std::string const& check_command,
    bool checks_enabled,
    bool accept_passive_checks,
    bool flap_detection_enabled,
    double low_flap_threshold,
    double high_flap_threshold,
    bool flap_detection_on_ok,
    bool flap_detection_on_warning,
    bool flap_detection_on_unknown,
    bool flap_detection_on_critical,
    bool stalk_on_ok,
    bool stalk_on_warning,
    bool stalk_on_unknown,
    bool stalk_on_critical,
    int process_perfdata,
    bool check_freshness,
    int freshness_threshold,
    std::string const& notes,
    std::string const& notes_url,
    std::string const& action_url,
    std::string const& icon_image,
    std::string const& icon_image_alt,
    int retain_status_information,
    int retain_nonstatus_information,
    bool obsess_over,
    std::string const& timezone);

std::ostream& operator<<(std::ostream& os,
                         com::centreon::engine::service const& obj);
std::ostream& operator<<(std::ostream& os, service_map_unsafe const& obj);

CCE_BEGIN()

com::centreon::engine::service& find_service(uint64_t host_id,
                                             uint64_t service_id);
bool is_service_exist(std::pair<uint64_t, uint64_t> const& id);
std::pair<uint64_t, uint64_t> get_host_and_service_id(std::string const& host,
                                                      std::string const& svc);
uint64_t get_service_id(std::string const& host, std::string const& svc);

CCE_END()

#endif  // !CCE_SERVICE_HH


text:
require 'spec_helper'

describe User, 'associations' do
  it { should have_many(:thredded_notification_preferences) }
  it { should have_many(:thredded_posts) }
  it { should have_many(:thredded_private_topics) }
  it { should have_many(:thredded_private_users) }
  it { should have_many(:thredded_roles) }
  it { should have_many(:thredded_messageboards).through(:thredded_roles) }
  it { should have_many(:thredded_topics) }

  it { should have_one(:thredded_user_detail) }
  it { should have_one(:thredded_user_preference) }
end

describe User, '.to_s' do
  it 'returns the username string' do
    user = create(:user, name: 'Joseph')

    expect(user.to_s).to eq 'Joseph'
  end
end


text:
package com.lardi.phonebook.web.rest;

import com.lardi.phonebook.dto.BaseResponse;
import com.lardi.phonebook.dto.ObjectResponse;
import com.lardi.phonebook.dto.UserDTO;
import com.lardi.phonebook.entity.User;
import com.lardi.phonebook.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.convert.ConversionService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Nikolay Yashchenko
 */
@RestController
@RequestMapping(value = "/api/user")
public class UserEndpoint {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserEndpoint.class);

    @Autowired
    private UserService userService;

    @Autowired
    @Qualifier("myConversionService")
    private ConversionService conversionService;

    @Autowired
    @Qualifier("userDTOValidator")
    private Validator userDTOValidator;

    @InitBinder("userDTO")
    public void initUserDTOValidator(WebDataBinder webDataBinder) {
        webDataBinder.addValidators(userDTOValidator);
    }

    @RequestMapping(value = "/registration", method = RequestMethod.POST)
    @PreAuthorize("hasRole('ROLE_ANONYMOUS')")
    public ResponseEntity registration(@Validated @RequestBody UserDTO userDTO, BindingResult bindingResult,
                                       HttpServletRequest request) {

        if (bindingResult.hasErrors()) {
            return ResponseEntity.badRequest().body(new BaseResponse(bindingResult));
        }

        User user = conversionService.convert(userDTO, User.class);
        user = userService.create(user);

        String password = userDTO.getPassword();
        userDTO = conversionService.convert(user, UserDTO.class);

        try {
            request.login(userDTO.getLogin(), password);
        } catch (ServletException e) {
            LOGGER.error("error while login: " + e.getLocalizedMessage());
        }

        return ResponseEntity.ok(new ObjectResponse<>(userDTO));
    }
}


text:
cask 'virtualbox-beta' do
  if MacOS.version <= :lion
    version '4.3.32-103443'
    sha256 '08defbf310b7ba5852fa8dd951438bb9b1528bb1544211568861986110e807f7'
  else
    version '5.1.7,111038'
    sha256 '8c018c9af1656abf5c2c868c8010734c9d3e48e868cd85190089e35fb4e5ca37'
  end

  url "http://www.virtualbox.org/download/testcase/VirtualBox-#{version.before_comma}-#{version.after_comma}-OSX.dmg"
  name 'Oracle VirtualBox'
  homepage 'https://www.virtualbox.org/wiki/Testbuilds'

  auto_updates true

  pkg 'VirtualBox.pkg'
  binary '/Applications/VirtualBox.app/Contents/MacOS/VBoxManage'
  binary '/Applications/VirtualBox.app/Contents/MacOS/VBoxHeadless'

  uninstall script:  { executable: 'VirtualBox_Uninstall.tool', args: %w[--unattended] },
            pkgutil: 'org.virtualbox.pkg.*'

  zap delete: [
                '/Library/Application Support/VirtualBox',
                '~/Library/VirtualBox',
              ],
      rmdir:  '~/VirtualBox VMs'
end


text:
const webpack = require('webpack');
const { resolve, join } = require('path');
const { existsSync } = require('fs');
const { isInstalledVersionPreactXOrAbove } = require('./utils');
const { merge } = require('webpack-merge');
const { filter } = require('minimatch');
const SizePlugin = require('size-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const CrittersPlugin = require('critters-webpack-plugin');
const renderHTMLPlugin = require('./render-html-plugin');
const PushManifestPlugin = require('./push-manifest');
const baseConfig = require('./webpack-base-config');
const BabelEsmPlugin = require('babel-esm-plugin');
const { InjectManifest } = require('workbox-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const RefreshPlugin = require('@prefresh/webpack');
const { normalizePath, warn } = require('../../util');

const cleanFilename = name =>
	name.replace(
		/(^\/(routes|components\/(routes|async))\/|(\/index)?\.[jt]sx?$)/g,
		''
	);

/**
 * @returns {Promise<import('webpack').Configuration>}
 */
async function clientConfig(env) {
	const { source, src, cwd } = env;
	const IS_SOURCE_PREACT_X_OR_ABOVE = isInstalledVersionPreactXOrAbove(cwd);
	const asyncLoader = IS_SOURCE_PREACT_X_OR_ABOVE
		? require.resolve('@preact/async-loader')
		: require.resolve('@preact/async-loader/legacy');

	let entry = {
		bundle: resolve(__dirname, './../entry'),
		polyfills: resolve(__dirname, './polyfills'),
	};

	let swInjectManifest = [];
	if (env.sw) {
		let swPath = join(__dirname, '..', '..', '..', 'sw', 'sw.js');
		const userSwPath = join(src, 'sw.js');
		if (existsSync(userSwPath)) {
			swPath = userSwPath;
		} else {
			warn(`Could not find sw.js in ${src}. Using the default service worker.`);
		}

		if (env.esm) {
			swInjectManifest.push(
				new InjectManifest({
					swSrc: swPath,
					swDest: 'sw-esm.js',
					include: [
						/200\.html$/,
						/\.esm.js$/,
						/\.css$/,
						/\.(png|jpg|svg|gif|webp)$/,
					],
					webpackCompilationPlugins: [
						new webpack.DefinePlugin({
							'process.env.ESM': true,
						}),
					],
				})
			);
		}

		swInjectManifest.push(
			new InjectManifest({
				swSrc: swPath,
				include: [/200\.html$/, /\.js$/, /\.css$/, /\.(png|jpg|svg|gif|webp)$/],
				exclude: [/\.esm\.js$/],
			})
		);
	}

	let copyPatterns = [
		existsSync(source('manifest.json')) && { from: 'manifest.json' },
		// copy any static files
		existsSync(source('assets')) && { from: 'assets', to: 'assets' },
		// copy sw-debug
		!env.isProd && {
			from: resolve(__dirname, '../../resources/sw-debug.js'),
			to: 'sw-debug.js',
		},
		// copy files from static to build directory
		existsSync(source('static')) && {
			from: resolve(source('static')),
			to: '.',
		},
	].filter(Boolean);

	return {
		entry: entry,
		output: {
			path: env.dest,
			publicPath: '/',
			filename: env.isProd ? '[name].[chunkhash:5].js' : '[name].js',
			chunkFilename: '[name].chunk.[chunkhash:5].js',
		},

		resolveLoader: {
			alias: {
				async: asyncLoader,
			},
		},

		// automatic async components :)
		module: {
			rules: [
				{
					test: /\.[jt]sx?$/,
					include: [
						filter(source('routes') + '/{*,*/index}.{js,jsx,ts,tsx}'),
						filter(
							source('components') +
								'/{routes,async}/{*,*/index}.{js,jsx,ts,tsx}'
						),
					],
					loader: asyncLoader,
					options: {
						name(filename) {
							filename = normalizePath(filename);
							let relative = filename.replace(normalizePath(src), '');
							if (!relative.includes('/routes/')) return false;
							return 'route-' + cleanFilename(relative);
						},
						formatName(filename) {
							filename = normalizePath(filename);
							let relative = filename.replace(normalizePath(source('.')), '');
							return cleanFilename(relative);
						},
					},
				},
			],
		},

		plugins: [
			new webpack.DefinePlugin({
				'process.env.ES_BUILD': false,
				'process.env.ADD_SW': env.sw,
				'process.env.PRERENDER': env.prerender,
			}),
			new PushManifestPlugin(),
			...(await renderHTMLPlugin(env)),
			...getBabelEsmPlugin(env),
			copyPatterns.length !== 0 &&
				new CopyWebpackPlugin({
					patterns: copyPatterns,
				}),
			...swInjectManifest,
		].filter(Boolean),
	};
}

function getBabelEsmPlugin(env) {
	const esmPlugins = [];
	if (env.esm) {
		esmPlugins.push(
			new BabelEsmPlugin({
				filename: env.isProd ? '[name].[chunkhash:5].esm.js' : '[name].esm.js',
				chunkFilename: '[name].chunk.[chunkhash:5].esm.js',
				excludedPlugins: ['BabelEsmPlugin', 'InjectManifest'],
				beforeStartExecution: plugins => {
					plugins.forEach(plugin => {
						if (
							plugin.constructor.name === 'DefinePlugin' &&
							plugin.definitions
						) {
							for (const definition in plugin.definitions) {
								if (definition === 'process.env.ES_BUILD') {
									plugin.definitions[definition] = true;
								}
							}
						} else if (
							plugin.constructor.name === 'DefinePlugin' &&
							!plugin.definitions
						) {
							throw new Error(
								'WebpackDefinePlugin found but not `process.env.ES_BUILD`.'
							);
						}
					});
				},
			})
		);
	}
	return esmPlugins;
}

/**
 * @returns {import('webpack').Configuration}
 */
function isProd(env) {
	let limit = 200 * 1000; // 200kb
	const prodConfig = {
		performance: Object.assign(
			{
				hints: 'warning',
				maxAssetSize: limit,
				maxEntrypointSize: limit,
			},
			env.pkg.performance
		),

		plugins: [
			new webpack.DefinePlugin({
				'process.env.ESM': env.esm,
			}),
			new SizePlugin(),
		],

		optimization: {
			minimizer: [
				new TerserPlugin({
					cache: true,
					parallel: true,
					terserOptions: {
						output: { comments: false },
						mangle: true,
						compress: {
							keep_fargs: false,
							pure_getters: true,
							hoist_funs: true,
							pure_funcs: [
								'classCallCheck',
								'_classCallCheck',
								'_possibleConstructorReturn',
								'Object.freeze',
								'invariant',
								'warning',
							],
						},
					},
					extractComments: false,
					sourceMap: true,
				}),
				new OptimizeCssAssetsPlugin({
					cssProcessorOptions: {
						// Fix keyframes in different CSS chunks minifying to colliding names:
						reduceIdents: false,
					},
				}),
			],
		},
	};

	if (env['inline-css']) {
		prodConfig.plugins.push(
			new CrittersPlugin({
				preload: 'media',
				pruneSource: false,
				logLevel: 'silent',
				additionalStylesheets: ['*.css'],
			})
		);
	}

	if (env.analyze) {
		prodConfig.plugins.push(new BundleAnalyzerPlugin());
	}

	if (env.brotli) {
		prodConfig.plugins.push(
			new CompressionPlugin({
				filename: '[path].br[query]',
				algorithm: 'brotliCompress',
				test: /\.esm\.js$/,
			})
		);
	}

	return prodConfig;
}

function setupProxy(target) {
	if (!target) {
		return;
	}

	const errorTemplate = warn =>
		`Invalid proxy configuration in package.json. ${warn} Skipping and using default.`;

	if (typeof target !== 'string') {
		warn(errorTemplate('If provided, "proxy" must be a string.'));
		return;
	} else if (!/https?:\/\//.test(target)) {
		warn(
			errorTemplate(
				'If provided, "proxy" must start with "http://" or "https://".'
			)
		);
		return;
	}

	return {
		target,
		logLevel: 'warn',
		context: (pathname, req) => {
			return (
				req.method != 'GET' ||
				(!(/^\/?assets/.test(pathname) || pathname.startsWith('/ws')) &&
					req.headers.accept.indexOf('html') === -1)
			);
		},
		secure: false,
		changeOrigin: true,
		ws: true,
		xfwd: true,
	};
}

/**
 * @returns {import('webpack').Configuration}
 */
function isDev(env) {
	const { cwd, src } = env;

	return {
		infrastructureLogging: {
			level: 'info',
		},
		plugins: [
			new webpack.NamedModulesPlugin(),
			env.refresh && new RefreshPlugin(),
		].filter(Boolean),

		devServer: {
			hot: true,
			compress: true,
			devMiddleware: {
				publicPath: '/',
				stats: 'errors-warnings',
			},
			static: {
				directory: src,
				watch: {
					ignored: [resolve(cwd, 'build'), resolve(cwd, 'node_modules')],
				},
			},
			https: env.https,
			port: env.port,
			host: process.env.HOST || env.host || '0.0.0.0',
			allowedHosts: 'all',
			historyApiFallback: true,
			client: {
				logging: 'none',
				overlay: false,
			},
			proxy: setupProxy(env.pkg.proxy),
		},
	};
}

module.exports = async function createClientConfig(env) {
	return merge(
		baseConfig(env),
		await clientConfig(env),
		(env.isProd ? isProd : isDev)(env)
	);
};


text:
meteor-ment.io
==============

A meteor package wrap for ment.io. https://github.com/jeff-collins/ment.io


text:
class timeSync {
public:
    uint32_t        times[TIME_SYNC_CYCLES];
    int8_t          num = -1;
    bool            adopt;

    String buildTimeStamp( void );
    bool processTimeStamp( String &str);
    void calcAdjustment ( bool even );
};

#endif //   _MESH_SYNC_H_


text:
/* 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.
 */

package org.flowable.engine.test.bpmn.deployment;

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

import java.util.ArrayList;
import java.util.List;

import org.flowable.common.engine.impl.history.HistoryLevel;
import org.flowable.engine.impl.test.HistoryTestHelper;
import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.runtime.EventSubscription;
import org.flowable.engine.runtime.ProcessInstance;
import org.junit.jupiter.api.Test;

/**
 * A test specifically written to test how events (start/boundary) are handled when deploying a new version of a process definition.
 *
 * @author Joram Barrez
 */
public class MessageEventsAndNewVersionDeploymentsTest extends PluggableFlowableTestCase {

    private static final String TEST_PROCESS_GLOBAL_BOUNDARY_MESSAGE = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.testGlobalMessageBoundaryEvent.bpmn20.xml";

    private static final String TEST_PROCESS_START_MESSAGE = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.testStartMessageEvent.bpmn20.xml";

    private static final String TEST_PROCESS_NO_EVENTS = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.processWithoutEvents.bpmn20.xml";

    private static final String TEST_PROCESS_BOTH_START_AND_BOUNDARY_MESSAGE = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.testBothBoundaryAndStartMessage.bpmn20.xml";

    private static final String TEST_PROCESS_BOTH_START_AND_BOUNDARY_MESSAGE_SAME_MESSAGE = "org/flowable/engine/test/bpmn/deployment/MessageEventsAndNewVersionDeploymentsTest.testBothBoundaryAndStartMessageSameMessage.bpmn20.xml";

    /*
     * BOUNDARY MESSAGE EVENT
     */

    @Test
    public void testMessageBoundaryEvent() {
        String deploymentId1 = deployBoundaryMessageTestProcess();
        runtimeService.startProcessInstanceByKey("messageTest");
        assertEquals(1, getAllEventSubscriptions().size());

        String deploymentId2 = deployBoundaryMessageTestProcess();
        runtimeService.startProcessInstanceByKey("messageTest");
        assertEquals(2, getAllEventSubscriptions().size());

        assertReceiveMessage("myMessage", 2);

        List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().list();
        assertEquals(2, tasks.size());

        for (org.flowable.task.api.Task task : tasks) {
            assertEquals("Task after message", task.getName());
        }

        cleanup(deploymentId1, deploymentId2);
    }

    /**
     * Verifying that the event subscriptions do get removed when removing a deployment.
     */
    @Test
    public void testBoundaryEventSubscriptionDeletedOnDeploymentDelete() {
        String deploymentId = deployBoundaryMessageTestProcess();
        runtimeService.startProcessInstanceByKey("messageTest");
        assertEquals("My Task", taskService.createTaskQuery().singleResult().getName());

        String deploymentId2 = deployBoundaryMessageTestProcess();
        runtimeService.startProcessInstanceByKey("messageTest");
        assertEquals(2, taskService.createTaskQuery().count());
        assertEquals(2, getAllEventSubscriptions().size());

        repositoryService.deleteDeployment(deploymentId, true);
        assertEquals("My Task", taskService.createTaskQuery().singleResult().getName());
        assertEquals(1, getAllEventSubscriptions().size());

        repositoryService.deleteDeployment(deploymentId2, true);
        assertEquals(0, getAllEventSubscriptions().size());
    }

    /**
     * Verifying that the event subscriptions do get removed when removing a process instance.
     */
    @Test
    public void testBoundaryEventSubscriptionsDeletedOnProcessInstanceDelete() {
        String deploymentId1 = deployBoundaryMessageTestProcess();
        runtimeService.startProcessInstanceByKey("messageTest");
        assertEquals("My Task", taskService.createTaskQuery().singleResult().getName());

        String deploymentId2 = deployBoundaryMessageTestProcess();
        ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("messageTest");
        assertEquals(2, taskService.createTaskQuery().count());
        assertEquals(2, getAllEventSubscriptions().size());

        // Deleting PI of second deployment
        runtimeService.deleteProcessInstance(processInstance2.getId(), "testing");
        assertEquals("My Task", taskService.createTaskQuery().singleResult().getName());
        assertEquals(1, getAllEventSubscriptions().size());

        runtimeService.messageEventReceived("myMessage", getExecutionIdsForMessageEventSubscription("myMessage").get(0));
        assertEquals(0, getAllEventSubscriptions().size());
        assertEquals("Task after message", taskService.createTaskQuery().singleResult().getName());

        cleanup(deploymentId1, deploymentId2);
    }

    /*
     * START MESSAGE EVENT
     */

    @Test
    public void testStartMessageEvent() {
        String deploymentId1 = deployStartMessageTestProcess();
        assertEquals(1, getAllEventSubscriptions().size());
        assertEventSubscriptionsCount(1);
        assertEquals(0, runtimeService.createProcessInstanceQuery().count());
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(1, runtimeService.createProcessInstanceQuery().count());

        String deploymentId2 = deployStartMessageTestProcess();
        assertEventSubscriptionsCount(1);

        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(2, runtimeService.createProcessInstanceQuery().count());
        assertEventSubscriptionsCount(1);

        cleanup(deploymentId1, deploymentId2);
    }

    @Test
    public void testMessageStartEventSubscriptionAfterDeploymentDelete() {

        // Deploy two version of process definition, delete latest and check if all is good

        String deploymentId1 = deployStartMessageTestProcess();
        List<EventSubscription> eventSubscriptions = getAllEventSubscriptions();
        assertEquals(1, eventSubscriptions.size());

        String deploymentId2 = deployStartMessageTestProcess();
        eventSubscriptions = getAllEventSubscriptions();
        assertEventSubscriptionsCount(1);

        repositoryService.deleteDeployment(deploymentId2, true);
        eventSubscriptions = getAllEventSubscriptions();
        assertEquals(1, eventSubscriptions.size());

        cleanup(deploymentId1);
        assertEquals(0, getAllEventSubscriptions().size());

        // Deploy two versions of process definition, delete the first
        deploymentId1 = deployStartMessageTestProcess();
        deploymentId2 = deployStartMessageTestProcess();
        assertEquals(1, getAllEventSubscriptions().size());
        repositoryService.deleteDeployment(deploymentId1, true);
        eventSubscriptions = getAllEventSubscriptions();
        assertEquals(1, eventSubscriptions.size());
        assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId2).singleResult().getId(), eventSubscriptions.get(0).getProcessDefinitionId());

        cleanup(deploymentId2);
        assertEquals(0, getAllEventSubscriptions().size());
    }

    /**
     * v1 -> has start message event v2 -> has no start message event v3 -> has start message event
     */
    @Test
    public void testDeployIntermediateVersionWithoutMessageStartEvent() {
        String deploymentId1 = deployStartMessageTestProcess();
        assertEquals(1, getAllEventSubscriptions().size());
        assertEquals(0, runtimeService.createProcessInstanceQuery().count());
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(1, runtimeService.createProcessInstanceQuery().count());
        assertEventSubscriptionsCount(1);

        String deploymentId2 = deployProcessWithoutEvents();
        assertEquals(0, getAllEventSubscriptions().size());
        assertEquals(1, runtimeService.createProcessInstanceQuery().count());
        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage"));
        assertEquals(1, runtimeService.createProcessInstanceQuery().count());
        assertEventSubscriptionsCount(0);

        String deploymentId3 = deployStartMessageTestProcess();
        assertEquals(1, getAllEventSubscriptions().size());
        assertEquals(1, runtimeService.createProcessInstanceQuery().count());
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(2, runtimeService.createProcessInstanceQuery().count());
        assertEventSubscriptionsCount(1);

        List<EventSubscription> eventSubscriptions = getAllEventSubscriptions();
        assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId3).singleResult().getId(),
                eventSubscriptions.get(0).getProcessDefinitionId());

        cleanup(deploymentId1, deploymentId2, deploymentId3);
    }

    @Test
    public void testDeleteDeploymentWithStartMessageEvents1() {
        String deploymentId1;
        String deploymentId2;
        String deploymentId3;
        deploymentId1 = deployStartMessageTestProcess();
        deploymentId2 = deployProcessWithoutEvents();
        deploymentId3 = deployStartMessageTestProcess();
        repositoryService.deleteDeployment(deploymentId3, true);
        assertEventSubscriptionsCount(0); // the latest is now the one without a message start
        cleanup(deploymentId1, deploymentId2);
    }

    @Test
    public void testDeleteDeploymentWithStartMessageEvents2() {
        String deploymentId1 = deployStartMessageTestProcess();
        String deploymentId2 = deployProcessWithoutEvents();
        String deploymentId3 = deployStartMessageTestProcess();
        repositoryService.deleteDeployment(deploymentId2, true);
        assertEventSubscriptionsCount(1); // the latest is now the one with the message
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId3).singleResult().getId(),
                runtimeService.createProcessInstanceQuery().singleResult().getProcessDefinitionId());
        cleanup(deploymentId1, deploymentId3);
    }

    @Test
    public void testDeleteDeploymentWithStartMessageEvents3() {
        String deploymentId1 = deployStartMessageTestProcess();
        String deploymentId2 = deployProcessWithoutEvents();
        String deploymentId3 = deployStartMessageTestProcess();
        repositoryService.deleteDeployment(deploymentId1, true);
        assertEventSubscriptionsCount(1); // the latest is now the one with the message
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId3).singleResult().getId(),
                runtimeService.createProcessInstanceQuery().singleResult().getProcessDefinitionId());
        cleanup(deploymentId2, deploymentId3);
    }

    @Test
    public void testDeleteDeploymentWithStartMessageEvents4() {
        String deploymentId1 = deployStartMessageTestProcess();
        String deploymentId2 = deployProcessWithoutEvents();
        String deploymentId3 = deployStartMessageTestProcess();
        repositoryService.deleteDeployment(deploymentId2, true);
        repositoryService.deleteDeployment(deploymentId3, true);
        assertEventSubscriptionsCount(1); // the latest is now the one with the message start
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId1).singleResult().getId(),
                runtimeService.createProcessInstanceQuery().singleResult().getProcessDefinitionId());
        cleanup(deploymentId1);
    }

    @Test
    public void testDeleteDeploymentWithStartMessageEvents5() {
        String deploymentId1 = deployStartMessageTestProcess();
        String deploymentId2 = deployProcessWithoutEvents();
        assertEventSubscriptionsCount(0);
        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage"));
        assertEquals(0, runtimeService.createExecutionQuery().count());
        repositoryService.deleteDeployment(deploymentId2, true);
        assertEventSubscriptionsCount(1); // the first is now the one with the signal
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId1).singleResult().getId(),
                runtimeService.createProcessInstanceQuery().singleResult().getProcessDefinitionId());
        cleanup(deploymentId1);
    }

    @Test
    public void testDeleteDeploymentWithStartMessageEvents6() {
        String deploymentId1 = deployStartMessageTestProcess();
        String deploymentId2 = deployProcessWithoutEvents();
        String deploymentId3 = deployStartMessageTestProcess();
        String deploymentId4 = deployProcessWithoutEvents();
        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage"));
        assertEquals(0, runtimeService.createExecutionQuery().count());

        repositoryService.deleteDeployment(deploymentId2, true);
        repositoryService.deleteDeployment(deploymentId3, true);
        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage"));
        assertEquals(0, runtimeService.createExecutionQuery().count());

        repositoryService.deleteDeployment(deploymentId1, true);
        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage"));
        assertEquals(0, runtimeService.createExecutionQuery().count());
        cleanup(deploymentId4);
    }

    @Test
    public void testDeleteDeploymentWithStartMessageEvents7() {
        String deploymentId1 = deployStartMessageTestProcess();
        String deploymentId2 = deployProcessWithoutEvents();
        String deploymentId3 = deployStartMessageTestProcess();
        String deploymentId4 = deployProcessWithoutEvents();
        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage"));
        assertEquals(0, runtimeService.createExecutionQuery().count());

        repositoryService.deleteDeployment(deploymentId2, true);
        repositoryService.deleteDeployment(deploymentId3, true);
        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage"));
        assertEquals(0, runtimeService.createExecutionQuery().count());

        repositoryService.deleteDeployment(deploymentId4, true);
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(1, runtimeService.createProcessInstanceQuery().count());
        cleanup(deploymentId1);
    }

    /*
     * BOTH BOUNDARY AND START MESSAGE
     */

    @Test
    public void testBothBoundaryAndStartEvent() {

        // Deploy process with both boundary and start event

        String deploymentId1 = deployProcessWithBothStartAndBoundaryMessage();
        assertEventSubscriptionsCount(1);
        assertEquals(0, runtimeService.createExecutionQuery().count());

        runtimeService.startProcessInstanceByMessage("myStartMessage");
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(2, runtimeService.createProcessInstanceQuery().count());
        assertEquals(3, getAllEventSubscriptions().size()); // 1 for the start, 2 for the boundary

        // Deploy version with only a boundary signal
        String deploymentId2 = deployBoundaryMessageTestProcess();
        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage"));
        assertEquals(2, runtimeService.createProcessInstanceQuery().count());
        assertEventSubscriptionsCount(2); // 2 boundary events remain

        // Deploy version with signal start
        String deploymentId3 = deployStartMessageTestProcess();
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(3, runtimeService.createProcessInstanceQuery().count());
        assertEventSubscriptionsCount(3);

        // Delete last version again, making the one with the boundary the latest
        repositoryService.deleteDeployment(deploymentId3, true);
        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myStartMessage"));
        assertEquals(2, runtimeService.createProcessInstanceQuery().count()); // -1, cause process instance of deploymentId3 is gone too
        assertEventSubscriptionsCount(2); // The 2 boundary remains

        // Test the boundary signal
        assertReceiveMessage("myBoundaryMessage", 2);
        assertEquals(2, taskService.createTaskQuery().taskName("Task after boundary message").list().size());

        // Delete second version
        repositoryService.deleteDeployment(deploymentId2, true);
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(3, runtimeService.createProcessInstanceQuery().count()); // -1, cause process instance of deploymentId3 is gone too
        assertEventSubscriptionsCount(2); // 2 boundaries

        cleanup(deploymentId1);
    }

    @Test
    public void testBothBoundaryAndStartSameMessageId() {

        // Deploy process with both boundary and start event

        String deploymentId1 = deployProcessWithBothStartAndBoundarySameMessage();
        assertEquals(1, getAllEventSubscriptions().size());
        assertEventSubscriptionsCount(1);
        assertEquals(0, runtimeService.createExecutionQuery().count());

        for (int i = 0; i < 9; i++) {
            // Every iteration will signal the boundary event of the previous iteration!
            runtimeService.startProcessInstanceByMessage("myMessage");
        }

        if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processEngineConfiguration)) {
            assertEquals(9, historyService.createHistoricProcessInstanceQuery().count());
        }
        assertEquals(10, getAllEventSubscriptions().size()); // 1 for the start, 9 for boundary

        // Deploy version with only a start signal. The boundary events should still react though!
        String deploymentId2 = deployStartMessageTestProcess();
        runtimeService.startProcessInstanceByMessage("myStartMessage");
        assertEquals(10, runtimeService.createProcessInstanceQuery().count());
        assertEventSubscriptionsCount(10); // Remains 10: 1 one was removed, but one added for the new message

        assertThatThrownBy(() -> runtimeService.startProcessInstanceByMessage("myMessage"));

        cleanup(deploymentId1, deploymentId2);
    }

    /*
     * HELPERS
     */

    private String deployBoundaryMessageTestProcess() {
        return deploy(TEST_PROCESS_GLOBAL_BOUNDARY_MESSAGE);
    }

    private String deployStartMessageTestProcess() {
        return deploy(TEST_PROCESS_START_MESSAGE);
    }

    private String deployProcessWithoutEvents() {
        return deploy(TEST_PROCESS_NO_EVENTS);
    }

    private String deployProcessWithBothStartAndBoundaryMessage() {
        return deploy(TEST_PROCESS_BOTH_START_AND_BOUNDARY_MESSAGE);
    }

    private String deployProcessWithBothStartAndBoundarySameMessage() {
        return deploy(TEST_PROCESS_BOTH_START_AND_BOUNDARY_MESSAGE_SAME_MESSAGE);
    }

    private String deploy(String path) {
        String deploymentId = repositoryService
                .createDeployment()
                .addClasspathResource(path)
                .deploy()
                .getId();
        return deploymentId;
    }

    private void cleanup(String... deploymentIds) {
        deleteDeployments();
    }

    private List<String> getExecutionIdsForMessageEventSubscription(final String messageName) {
        List<EventSubscription> eventSubscriptions = runtimeService.createEventSubscriptionQuery()
                .eventType("message")
                .eventName(messageName)
                .orderByCreateDate()
                .desc()
                .list();

        List<String> executionIds = new ArrayList<>();
        for (EventSubscription eventSubscription : eventSubscriptions) {
            executionIds.add(eventSubscription.getExecutionId());
        }
        return executionIds;
    }

    private List<EventSubscription> getAllEventSubscriptions() {
        List<EventSubscription> eventSubscriptionEntities = runtimeService.createEventSubscriptionQuery()
                .orderByCreateDate()
                .desc()
                .list();

        for (EventSubscription entity : eventSubscriptionEntities) {
            assertEquals("message", entity.getEventType());
            assertNotNull(entity.getProcessDefinitionId());
        }

        return eventSubscriptionEntities;
    }

    private void assertReceiveMessage(String messageName, int executionIdsCount) {
        List<String> executionIds = getExecutionIdsForMessageEventSubscription(messageName);
        assertEquals(executionIdsCount, executionIds.size());
        for (String executionId : executionIds) {
            runtimeService.messageEventReceived(messageName, executionId);
        }
    }

    private void assertEventSubscriptionsCount(long count) {
        assertEquals(count, getAllEventSubscriptions().size());
    }

}


text:
body{margin:0;padding:0;height:100%;}
.container-main{background-image:url(images/bodybg.gif);background-repeat:repeat-x;background-color:#f4f4f4;text-align:center;padding-top:50px;}
.container-footer{margin:auto;width:700px;}
.container-error{padding-top:10px;margin:auto;width:629px;text-align:center;font-family:Arial;font-size:12px;}
.error-label{color:red;display:block;padding-bottom:10px;text-align:left;}
.wizard-step{margin:auto;width:600px;height:340px;text-align:right;padding:10px;}
.wizard-step td{height:20px;margin:0;padding:0;}
.header-text{font-size:18px;color:#ff5a00;text-align:center;padding-bottom:10px;}
.content{padding-top:10px;margin:auto;width:629px;text-align:center;font-family:Arial;font-size:12px;}
.textbox{width:150px;}
.title{font-weight:700;}
.log{width:600px;height:90px;margin:0 auto;}
.container-installer{margin:auto;}
.container-installer .top .left{width:22px;height:22px;background-image:url(images/topleft.gif);background-position:left top;background-repeat:no-repeat;}
.container-installer .top .center{width:699px;height:22px;background-image:url(images/top.gif);background-repeat:no-repeat;background-position:top;}
.container-installer .top .right{width:22px;height:22px;background-image:url(images/topright.gif);background-position:left top;background-repeat:no-repeat;}
.container-installer .Middle .left{width:22px;height:516px;background-image:url(images/left.gif);background-position:left top;background-repeat:no-repeat;}
.container-installer .Middle .center{background-image:url(images/bg.gif);background-repeat:repeat-y;background-position:top;text-align:center;vertical-align:top;}
.container-installer .Middle .right{width:22px;height:516px;background-image:url(images/right.gif);background-repeat:no-repeat;background-position:left top;}
.container-installer .Bottom .left{width:22px;height:22px;background-image:url(images/bottomleft.gif);background-position:left bottom;background-repeat:no-repeat;}
.container-installer .Bottom .center{width:699px;height:22px;background-image:url(images/bottom.gif);background-repeat:no-repeat;background-position:top;}
.container-installer .Bottom .right{width:22px;height:22px;background-image:url(images/bottomright.gif);background-position:left bottom;background-repeat:no-repeat;}
.hint{font-size:90%;font-style:italic;}
.throbber-header{font-size:145%;}
.throbber{display:none;}
.throbber .curtain{position:fixed;left:0;top:0;width:100%;height:100%;background-color:#3e4d45;opacity:0.9;filter:alpha(opacity=90);}
.throbber .curtain-content{position:absolute;left:0;top:0;width:100%;height:100%;}
.throbber .curtain-content div{text-align:center;padding:250px;color:#FFF;}
.wizard-step, .wizard-step td, .wizard-step label, .wizard-step div, #sqlConnectionInfo table, #sqlConnectionInfo td, #sqlConnectionInfo label {direction:rtl; text-align:right;}


text:
// +k8s:deepcopy-gen=package
// +groupName=metrics.k8s.io

package metrics


text:
<?php

namespace Codeia\Data;

/*
 * This file is a part of the Bloom project.
 * See the LICENSE file at the project root for the terms of use.
 */

/**
 * A column in a data table.
 *
 * forall T
 * name :: Attribute T -> str
 * get :: Attribute T -> Row -> T | null
 * set :: Attribute T -> Row * T -> ()
 *
 * @author Mon Zafra <mz@codeia.ph>
 */
interface Attribute {

    /**
     * @return string
     */
    function name();

    /**
     * @param array|ArrayAccess &$tuple :: Row
     * @param mixed $value
     */
    function set(&$tuple, $value);

    /**
     * @param array|ArrayAccess $tuple :: Row
     * @return mixed
     */
    function get($tuple);
}


text:
package org.onosproject.net.link.impl;

import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Sets;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onosproject.core.Permission;
import org.onosproject.event.EventDeliveryService;
import org.onosproject.event.ListenerRegistry;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Link;
import org.onosproject.net.Link.State;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.link.LinkAdminService;
import org.onosproject.net.link.LinkDescription;
import org.onosproject.net.link.LinkEvent;
import org.onosproject.net.link.LinkListener;
import org.onosproject.net.link.LinkProvider;
import org.onosproject.net.link.LinkProviderRegistry;
import org.onosproject.net.link.LinkProviderService;
import org.onosproject.net.link.LinkService;
import org.onosproject.net.link.LinkStore;
import org.onosproject.net.link.LinkStoreDelegate;
import org.onosproject.net.provider.AbstractProviderRegistry;
import org.onosproject.net.provider.AbstractProviderService;
import org.slf4j.Logger;

import java.util.Set;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
import static org.onosproject.security.AppGuard.checkPermission;

/**
 * Provides basic implementation of the link SB & NB APIs.
 */
@Component(immediate = true)
@Service
public class LinkManager
        extends AbstractProviderRegistry<LinkProvider, LinkProviderService>
        implements LinkService, LinkAdminService, LinkProviderRegistry {

    private static final String DEVICE_ID_NULL = "Device ID cannot be null";
    private static final String LINK_DESC_NULL = "Link description cannot be null";
    private static final String CONNECT_POINT_NULL = "Connection point cannot be null";

    private final Logger log = getLogger(getClass());

    protected final ListenerRegistry<LinkEvent, LinkListener>
            listenerRegistry = new ListenerRegistry<>();

    private final LinkStoreDelegate delegate = new InternalStoreDelegate();

    private final DeviceListener deviceListener = new InternalDeviceListener();

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected LinkStore store;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected DeviceService deviceService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected EventDeliveryService eventDispatcher;

    @Activate
    public void activate() {
        store.setDelegate(delegate);
        eventDispatcher.addSink(LinkEvent.class, listenerRegistry);
        deviceService.addListener(deviceListener);
        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        store.unsetDelegate(delegate);
        eventDispatcher.removeSink(LinkEvent.class);
        deviceService.removeListener(deviceListener);
        log.info("Stopped");
    }

    @Override
    public int getLinkCount() {
        checkPermission(Permission.LINK_READ);

        return store.getLinkCount();
    }

    @Override
    public Iterable<Link> getLinks() {
        checkPermission(Permission.LINK_READ);

        return store.getLinks();
    }

    @Override
    public Iterable<Link> getActiveLinks() {
        checkPermission(Permission.LINK_READ);

        return FluentIterable.from(getLinks())
                .filter(new Predicate<Link>() {

                    @Override
                    public boolean apply(Link input) {
                        return input.state() == State.ACTIVE;
                    }
                });
    }

    @Override
    public Set<Link> getDeviceLinks(DeviceId deviceId) {
        checkPermission(Permission.LINK_READ);

        checkNotNull(deviceId, DEVICE_ID_NULL);
        return Sets.union(store.getDeviceEgressLinks(deviceId),
                          store.getDeviceIngressLinks(deviceId));
    }

    @Override
    public Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
        checkPermission(Permission.LINK_READ);

        checkNotNull(deviceId, DEVICE_ID_NULL);
        return store.getDeviceEgressLinks(deviceId);
    }

    @Override
    public Set<Link> getDeviceIngressLinks(DeviceId deviceId) {
        checkPermission(Permission.LINK_READ);

        checkNotNull(deviceId, DEVICE_ID_NULL);
        return store.getDeviceIngressLinks(deviceId);
    }

    @Override
    public Set<Link> getLinks(ConnectPoint connectPoint) {
        checkPermission(Permission.LINK_READ);

        checkNotNull(connectPoint, CONNECT_POINT_NULL);
        return Sets.union(store.getEgressLinks(connectPoint),
                          store.getIngressLinks(connectPoint));
    }

    @Override
    public Set<Link> getEgressLinks(ConnectPoint connectPoint) {
        checkPermission(Permission.LINK_READ);

        checkNotNull(connectPoint, CONNECT_POINT_NULL);
        return store.getEgressLinks(connectPoint);
    }

    @Override
    public Set<Link> getIngressLinks(ConnectPoint connectPoint) {
        checkPermission(Permission.LINK_READ);

        checkNotNull(connectPoint, CONNECT_POINT_NULL);
        return store.getIngressLinks(connectPoint);
    }

    @Override
    public Link getLink(ConnectPoint src, ConnectPoint dst) {
        checkPermission(Permission.LINK_READ);

        checkNotNull(src, CONNECT_POINT_NULL);
        checkNotNull(dst, CONNECT_POINT_NULL);
        return store.getLink(src, dst);
    }

    @Override
    public void removeLinks(ConnectPoint connectPoint) {
        if (deviceService.getRole(connectPoint.deviceId()) != MastershipRole.MASTER) {
            return;
        }
        removeLinks(getLinks(connectPoint), false);
    }

    @Override
    public void removeLinks(DeviceId deviceId) {
        if (deviceService.getRole(deviceId) != MastershipRole.MASTER) {
            return;
        }
        removeLinks(getDeviceLinks(deviceId), false);
    }

    @Override
    public void addListener(LinkListener listener) {
        checkPermission(Permission.LINK_EVENT);

        listenerRegistry.addListener(listener);
    }

    @Override
    public void removeListener(LinkListener listener) {
        checkPermission(Permission.LINK_EVENT);

        listenerRegistry.removeListener(listener);
    }

    // Auxiliary interceptor for device remove events to prune links that
    // are associated with the removed device or its port.
    private class InternalDeviceListener implements DeviceListener {
        @Override
        public void event(DeviceEvent event) {
            if (event.type() == DeviceEvent.Type.DEVICE_REMOVED) {
                removeLinks(event.subject().id());
            } else if (event.type() == DeviceEvent.Type.PORT_REMOVED) {
                removeLinks(new ConnectPoint(event.subject().id(),
                                             event.port().number()));
            }
        }
    }

    @Override
    protected LinkProviderService createProviderService(LinkProvider provider) {
        return new InternalLinkProviderService(provider);
    }

    // Personalized link provider service issued to the supplied provider.
    private class InternalLinkProviderService
            extends AbstractProviderService<LinkProvider>
            implements LinkProviderService {

        InternalLinkProviderService(LinkProvider provider) {
            super(provider);
        }

        @Override
        public void linkDetected(LinkDescription linkDescription) {
            checkNotNull(linkDescription, LINK_DESC_NULL);
            checkValidity();

            LinkEvent event = store.createOrUpdateLink(provider().id(),
                                                       linkDescription);
            if (event != null) {
                log.info("Link {} detected", linkDescription);
                post(event);
            }
        }

        @Override
        public void linkVanished(LinkDescription linkDescription) {
            checkNotNull(linkDescription, LINK_DESC_NULL);
            checkValidity();

            ConnectPoint src = linkDescription.src();
            ConnectPoint dst = linkDescription.dst();

            LinkEvent event = store.removeOrDownLink(src, dst);
            if (event != null) {
                log.info("Link {} vanished", linkDescription);
                post(event);
            }
        }

        @Override
        public void linksVanished(ConnectPoint connectPoint) {
            checkNotNull(connectPoint, "Connect point cannot be null");
            checkValidity();

            log.debug("Links for connection point {} vanished", connectPoint);
            // FIXME: This will remove links registered by other providers
            removeLinks(getLinks(connectPoint), true);
        }

        @Override
        public void linksVanished(DeviceId deviceId) {
            checkNotNull(deviceId, DEVICE_ID_NULL);
            checkValidity();

            log.debug("Links for device {} vanished", deviceId);
            removeLinks(getDeviceLinks(deviceId), true);
        }
    }

    // Removes all links in the specified set and emits appropriate events.
    private void  removeLinks(Set<Link> links, boolean isSoftRemove) {
        for (Link link : links) {
            LinkEvent event = isSoftRemove ?
                    store.removeOrDownLink(link.src(), link.dst()) :
                    store.removeLink(link.src(), link.dst());
            if (event != null) {
                log.info("Link {} removed/vanished", event.subject());
                post(event);
            }
        }
    }

    // Posts the specified event to the local event dispatcher.
    private void post(LinkEvent event) {
        if (event != null) {
            eventDispatcher.post(event);
        }
    }

    // Store delegate to re-post events emitted from the store.
    private class InternalStoreDelegate implements LinkStoreDelegate {
        @Override
        public void notify(LinkEvent event) {
            post(event);
        }
    }
}


text:
package org.apache.dubbo.rpc.protocol.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.serialize.ObjectInput;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcResult;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.embedded.RedisServer;

import java.io.ByteArrayInputStream;
import java.io.IOException;

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

public class RedisProtocolTest {
    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
    private RedisServer redisServer;
    private URL registryUrl;

    @Rule
    public TestName name = new TestName();

    @Before
    public void setUp() throws Exception {
        int redisPort = NetUtils.getAvailablePort();
        if (name.getMethodName().equals("testAuthRedis") || name.getMethodName().equals("testWrongAuthRedis")) {
            String password = "123456";
            this.redisServer = RedisServer.builder().port(redisPort).setting("requirepass " + password).build();
            this.registryUrl = URL.valueOf("redis://username:"+password+"@localhost:"+redisPort+"?db.index=0");
        } else {
            this.redisServer = RedisServer.builder().port(redisPort).build();
            this.registryUrl = URL.valueOf("redis://localhost:" + redisPort);
        }
        this.redisServer.start();
    }

    @After
    public void tearDown() {
        this.redisServer.stop();
    }

    @Test
    public void testReferClass() {
        Invoker<IDemoService> refer = protocol.refer(IDemoService.class, registryUrl);

        Class<IDemoService> serviceClass = refer.getInterface();
        assertThat(serviceClass.getName(), is("org.apache.dubbo.rpc.protocol.redis.IDemoService"));
    }

    @Test
    public void testInvocation() {
        Invoker<IDemoService> refer = protocol.refer(IDemoService.class,
                registryUrl
                        .addParameter("max.idle", 10)
                        .addParameter("max.active", 20));
        IDemoService demoService = this.proxy.getProxy(refer);

        String value = demoService.get("key");
        assertThat(value, is(nullValue()));

        demoService.set("key", "newValue");
        value = demoService.get("key");
        assertThat(value, is("newValue"));

        demoService.delete("key");
        value = demoService.get("key");
        assertThat(value, is(nullValue()));

        refer.destroy();
    }

    @Test(expected = RpcException.class)
    public void testUnsupportedMethod() {
        Invoker<IDemoService> refer = protocol.refer(IDemoService.class, registryUrl);
        IDemoService demoService = this.proxy.getProxy(refer);

        demoService.unsupported(null);
    }

    @Test(expected = RpcException.class)
    public void testWrongParameters() {
        Invoker<IDemoService> refer = protocol.refer(IDemoService.class, registryUrl);
        IDemoService demoService = this.proxy.getProxy(refer);

        demoService.set("key", "value", "wrongValue");
    }

    @Test(expected = RpcException.class)
    public void testWrongRedis() {
        Invoker<IDemoService> refer = protocol.refer(IDemoService.class, URL.valueOf("redis://localhost:1"));
        IDemoService demoService = this.proxy.getProxy(refer);

        demoService.get("key");
    }

    @Test(expected = UnsupportedOperationException.class)
    public void testExport() {
        protocol.export(protocol.refer(IDemoService.class, registryUrl));
    }

    @Test
    public void testAuthRedis() {
        // default db.index=0
        Invoker<IDemoService> refer = protocol.refer(IDemoService.class,
                registryUrl
                        .addParameter("max.idle", 10)
                        .addParameter("max.active", 20));
        IDemoService demoService = this.proxy.getProxy(refer);

        String value = demoService.get("key");
        assertThat(value, is(nullValue()));

        demoService.set("key", "newValue");
        value = demoService.get("key");
        assertThat(value, is("newValue"));

        demoService.delete("key");
        value = demoService.get("key");
        assertThat(value, is(nullValue()));

        refer.destroy();

        //change db.index=1
        String password = "123456";
        int database = 1;
        this.registryUrl = this.registryUrl.setPassword(password).addParameter("db.index", database);
        refer = protocol.refer(IDemoService.class,
                registryUrl
                        .addParameter("max.idle", 10)
                        .addParameter("max.active", 20));
        demoService = this.proxy.getProxy(refer);

        demoService.set("key", "newValue");
        value = demoService.get("key");
        assertThat(value, is("newValue"));

        // jedis gets the result comparison
        JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "localhost", registryUrl.getPort(), 2000, password, database, (String)null);
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            byte[] valueByte = jedis.get("key".getBytes());
            Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(this.registryUrl.getParameter(Constants.SERIALIZATION_KEY, "java"));
            ObjectInput oin = serialization.deserialize(this.registryUrl, new ByteArrayInputStream(valueByte));
            String actual = (String) oin.readObject();
            assertThat(value, is(actual));
        } catch(Exception e) {
            Assert.fail("jedis gets the result comparison is error!");
        } finally {
            if (jedis != null) {
                jedis.close();
            }
            pool.destroy();
        }

        demoService.delete("key");
        value = demoService.get("key");
        assertThat(value, is(nullValue()));

        refer.destroy();
    }

    @Test
    public void testWrongAuthRedis() {
        String password = "1234567";
        this.registryUrl = this.registryUrl.setPassword(password);
        Invoker<IDemoService> refer = protocol.refer(IDemoService.class,
                registryUrl
                        .addParameter("max.idle", 10)
                        .addParameter("max.active", 20));
        IDemoService demoService = this.proxy.getProxy(refer);

        try {
            String value = demoService.get("key");
            assertThat(value, is(nullValue()));
        } catch (RpcException e) {
            if (e.getCause() instanceof JedisConnectionException && e.getCause().getCause() instanceof JedisDataException) {
                Assert.assertEquals("ERR invalid password" , e.getCause().getCause().getMessage());
            } else {
                Assert.fail("no invalid password exception!");
            }
        }

        refer.destroy();
    }
}


text:
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.dom_distiller;

import androidx.annotation.VisibleForTesting;

import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.preferences.Pref;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.components.navigation_interception.InterceptNavigationDelegate;
import org.chromium.components.user_prefs.UserPrefs;
import org.chromium.content_public.browser.WebContents;
import org.chromium.url.GURL;

/**
 * A helper class for using the DOM Distiller.
 */
@JNINamespace("android")
public class DomDistillerTabUtils {
    /** Triggering heuristics encoded in native enum DistillerHeuristicsType. */
    private static Integer sHeuristics;

    /** Used to specify whether mobile friendly is enabled for testing purposes. */
    private static Boolean sExcludeMobileFriendlyForTesting;

    private DomDistillerTabUtils() {
    }

    /**
     * Creates a new WebContents and navigates the {@link WebContents} to view the URL of the
     * current page, while in the background starts distilling the current page. This method takes
     * ownership over the old WebContents after swapping in the new one.
     *
     * @param webContents the WebContents to distill.
     */
    public static void distillCurrentPageAndView(WebContents webContents) {
        DomDistillerTabUtilsJni.get().distillCurrentPageAndView(webContents);
    }

    /**
     * Starts distillation in the source {@link WebContents}. The viewer needs to be handled
     * elsewhere.
     *
     * @param webContents the WebContents to distill.
     */
    public static void distillCurrentPage(WebContents webContents) {
        DomDistillerTabUtilsJni.get().distillCurrentPage(webContents);
    }

    /**
     * Starts distillation in the source {@link WebContents} while navigating the destination
     * {@link WebContents} to view the distilled content. This does not take ownership of any
     * of the WebContents.
     *
     * @param sourceWebContents the WebContents to distill.
     * @param destinationWebContents the WebContents to display the distilled content in.
     */
    public static void distillAndView(
            WebContents sourceWebContents, WebContents destinationWebContents) {
        DomDistillerTabUtilsJni.get().distillAndView(sourceWebContents, destinationWebContents);
    }

    /**
     * Returns the formatted version of the original URL of a distillation, given the original URL.
     *
     * @param url The original URL.
     * @return the formatted URL of the original page.
     */
    public static String getFormattedUrlFromOriginalDistillerUrl(GURL url) {
        return DomDistillerTabUtilsJni.get().getFormattedUrlFromOriginalDistillerUrl(url);
    }

    /**
     * Detect if any heuristic is being used to determine if a page is distillable.
     * This is testing if the heuristic is not "NONE".
     *
     * @return True if heuristics are being used to detect distillable pages.
     */
    public static boolean isDistillerHeuristicsEnabled() {
        return getDistillerHeuristics() != DistillerHeuristicsType.NONE;
    }

    /**
     * Check if the distiller is reporting every page as distillable.
     *
     * @return True if heuristic is ALWAYS_TRUE.
     */
    public static boolean isHeuristicAlwaysTrue() {
        return getDistillerHeuristics() == DistillerHeuristicsType.ALWAYS_TRUE;
    }

    /**
     * Check if the distiller should report mobile-friendly pages as non-distillable.
     *
     * @return True if heuristic is ADABOOST_MODEL, and "Simplified view for accessibility"
     * is disabled.
     */
    public static boolean shouldExcludeMobileFriendly(Tab tab) {
        if (sExcludeMobileFriendlyForTesting != null) return sExcludeMobileFriendlyForTesting;
        WebContents webContents = tab.getWebContents();
        assert webContents != null;
        return !UserPrefs.get(Profile.fromWebContents(webContents))
                        .getBoolean(Pref.READER_FOR_ACCESSIBILITY)
                && getDistillerHeuristics() == DistillerHeuristicsType.ADABOOST_MODEL;
    }

    @VisibleForTesting
    public static void setExcludeMobileFriendlyForTesting(boolean excludeForTesting) {
        sExcludeMobileFriendlyForTesting = excludeForTesting;
    }

    /**
     * Cached version of DomDistillerTabUtilsJni.get().getDistillerHeuristics().
     */
    public static @DistillerHeuristicsType int getDistillerHeuristics() {
        if (sHeuristics == null) {
            sHeuristics = DomDistillerTabUtilsJni.get().getDistillerHeuristics();
        }
        return sHeuristics;
    }

    /**
     * Check if the distilled content should be shown in a Chrome Custom Tab (CCT).
     *
     * @return True if it should.
     */
    public static boolean isCctMode() {
        if (!ChromeFeatureList.isInitialized()) return false;
        return ChromeFeatureList.isEnabled(ChromeFeatureList.READER_MODE_IN_CCT);
    }

    /**
     * Returns true if reader mode prompt should be displayed as a message. Otherwise it will be
     * displayed as an infobar.
     */
    public static boolean useMessagesForReaderModePrompt() {
        return ChromeFeatureList.isEnabled(ChromeFeatureList.MESSAGES_FOR_ANDROID_READER_MODE);
    }

    /**
     * Set an InterceptNavigationDelegate on a WebContents.
     * @param delegate The navigation delegate.
     * @param webContents The WebContents to bind the delegate to.
     */
    public static void setInterceptNavigationDelegate(
            InterceptNavigationDelegate delegate, WebContents webContents) {
        DomDistillerTabUtilsJni.get().setInterceptNavigationDelegate(delegate, webContents);
    }

    @NativeMethods
    interface Natives {
        void distillCurrentPageAndView(WebContents webContents);
        void distillCurrentPage(WebContents webContents);
        void distillAndView(WebContents sourceWebContents, WebContents destinationWebContents);
        String getFormattedUrlFromOriginalDistillerUrl(GURL url);
        int getDistillerHeuristics();
        void setInterceptNavigationDelegate(
                InterceptNavigationDelegate delegate, WebContents webContents);
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cuongnt.qwap.entity.listener;

import com.cuongnt.qwap.entity.File;
import javax.persistence.PostUpdate;

/**
 *
 * @author richard
 */
public class FileListener {

    @PostUpdate
    private void postUpdate(File file) {
        System.out.println("Fuck you");
    }
}


text:
import sys
import logging
import time

from PySide import QtGui, QtCore

logging.basicConfig(level=logging.DEBUG)

class MainWindow(QtGui.QMainWindow):
    #: Use this signal to update the status bar message
    updateStatusBar = QtCore.Signal(str)

    def __init__(self):
        """
        Initialize the main window
        """
        super(MainWindow, self).__init__()
        self.setWindowTitle("2: MainWindow")

        file_menu = self.menuBar().addMenu("&File")
        start_action = file_menu.addAction("&Start")
        start_action.setShortcut("Ctrl+S")
        start_action.triggered.connect(self.on_start_click)

        stop_action = file_menu.addAction("S&top")
        stop_action.setShortcut("Ctrl+T")
        stop_action.triggered.connect(self.on_stop_click)

        file_menu.addSeparator()
        exit_action = file_menu.addAction("&Quit")
        exit_action.setShortcut(QtGui.QKeySequence.Quit)
        exit_action.triggered.connect(self.close)

        help_menu = self.menuBar().addMenu("&Help")
        help_action = help_menu.addAction("&Help")
        help_action.setShortcut(QtGui.QKeySequence.HelpContents)
        help_action.triggered.connect(self.on_help)

        centralWidget = QtGui.QWidget(self)

        # Create 3 buttons
        start_button = QtGui.QPushButton("Start", self)
        start_button.clicked.connect(self.on_start_click)

        stop_button = QtGui.QPushButton("Stop", self)
        stop_button.clicked.connect(self.on_stop_click)

        quit_button = QtGui.QPushButton("Quit", self)
        quit_button.clicked.connect(self.close)
        # Clicked signal causes close signal to be emitted, which is handled
        # by self.closeEvent slot.

        self.progress_bar = QtGui.QProgressBar(self)
        # Using self here because I need to reference this in a slot

        # Lay them out horizontally
        button_container = QtGui.QWidget(self)
        button_layout = QtGui.QHBoxLayout(button_container)
        button_layout.addWidget(start_button)
        button_layout.addWidget(stop_button)
        button_layout.addWidget(quit_button)
        button_container.setLayout(button_layout)

        centralLayout = QtGui.QVBoxLayout(centralWidget)
        centralLayout.addWidget(button_container)
        centralLayout.addWidget(self.progress_bar)
        centralWidget.setLayout(centralLayout)

        self.setCentralWidget(centralWidget)

        self.statusBar().show()
        # Show the status bar to keep the window from moving stuff around
        # when the statusBar is shown the first time.

        self.updateStatusBar.connect(self.update_status_bar)

    @QtCore.Slot()
    def on_start_click(self):
        pi = self.gregory_leibniz(5)
        self.updateStatusBar.emit("pi={}".format(pi))

    @QtCore.Slot()
    def on_stop_click(self):
        self.updateStatusBar.emit("Stop clicked")

    @QtCore.Slot(str)
    def update_status_bar(self, message):
        self.statusBar().showMessage(message)

    @QtCore.Slot()
    def on_help(self):
        QtGui.QMessageBox.information(self,
                "Help",
                "Press Start to start processing.  Press Stop to stop "
                "processing.  Press Quit to exit the program.",
                QtGui.QMessageBox.Ok,
                QtGui.QMessageBox.Ok)

    def gregory_leibniz(self, iterations):
        pi = 0.0
        for i in xrange(iterations):
            if i % 2 == 0:
                pi += 4.0 / (2.0 * i + 1.0)
            else:
                pi -= 4.0 / (2.0 * i + 1.0)
            self.progress_bar.setValue((float(i) / float(iterations)) * 100.0)
            self.updateStatusBar.emit("i={0} pi={1}".format(i, pi))
            time.sleep(1)
        self.progress_bar.setValue(100)
        return pi

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    app.exec_()  # This starts the event loop


text:
set -e

OGDSPEC=http://www.ref.gv.at/uploads/media/OGD-Metadaten_2_1_2012_10.pdf

echo "Beziehen der Spezifikation"
# remove supperfluous pdfs from repeated retrieval (need no history)
rm `basename  $OGDSPEC`.*  || true
rm `basename  $OGDSPEC` || true
# retrieving specification from the internet
wget $OGDSPEC

PDF=`basename  $OGDSPEC`
TXT=`basename  $OGDSPEC .pdf`.txt
CSV=`basename  $OGDSPEC .pdf`.csv

echo "Konvertieren in Text-Datei ..."
pdftotext $PDF > $TXT

echo "Extrahieren der Information als CSV ..."
awk -f convogdatspectocsv.awk $TXT > $CSV

echo "Ende"


text:
package examples.demo

import examples.demo.GModularClockCircle.Clock
import examples.demo.ui._
import rescala._

/**
  * To resolve this circular initialization order, we introduce
  * higher-order reactives. Higher-order reactives are Signals
  * or Events, whose values contain references to other Signals
  * or Events. We have already been using a higher-order
  * reactive for a while, namely since we made the circle's
  * trajectory scale with the ShapesPanel's size. We started
  * using shapes in its initialization, defined as a
  * Var[List[Shape]], and each Shape contains several Signals
  * defining its position, size, etc. Thus, shapes already is a
  * higher-order reactive.
  *
  * To implement our horizontal and vertical bounces, we now use
  * a similar pattern, although their higher-order-ness is much
  * clearer. For both, we define a Var[List[Event[Any]]], which
  * we initialize with an empty List. This signature clearly
  * shows, that the outer Var contains pointers to several inner
  * Events. To be able to use these higher-order reactives in
  * place of the leftButton.pressed and rightButton.pressed, we
  * need to flatten these higher-order reactives into regular
  * Events. The according flatten method is available on any
  * reactive, whose values reference other reactives either
  * directly or indirected through any collection of the scala
  * standard library. The type of reactive returned is a normal
  * reactive (or, one layer less higher-order), with the concrete
  * type depending on the type signature of the higher-order
  * reactive that is being flattened. E.g., a Signal[Signal[T]]
  * will simply become a Signal[T]. A Signal[Event[T]] will
  * become an Event[T]. A Signal[Set[Signal[T]] will become a
  * Signal[Set[T]]. A Signal[List[Event[T]]], as we use it here,
  * is the most complex case, becoming an Event[List[Option[T]]].
  * The Option wrapper models, that not just one, but each Event
  * in the Signal may or may not have emitted a value
  * simultaneously. Higher-order reactives containing only a
  * single Event rather than a multiples do not have this option
  * wrapper because it is redundant -- if the one inner Event
  * did not emit a value, then the flattened result will also
  * not emit a value, i.e., the None case never occurs.
  *
  * Having implemented both higher-order bounce Vars and having
  * changed both velocities to depend on their flattened
  * counterparts, the BouncingBall class is now independent of
  * the ShapesPanel. To complete the refactoring, all that is
  * left to do is add the left and right mouse button to the
  * respective list of bounce sources, equally to how the ball
  * shape is added to the list of displayed shapes for the
  * ShapesPanel.
  */
object LFullyModularBall extends Main {
  class BouncingBall(val initVx: Double, val initVy: Double, val diameter: Signal[Int], val resetIn: Event[Point]) {
    val horizontalBounceSources: Var[List[Event[Any]]] = Var(List())
    val verticalBounceSources: Var[List[Event[Any]]] = Var(List())
    val filteredHorizontalBounceSources = horizontalBounceSources.map(_.map(_.recover{case _: IllegalArgumentException => None}))

    val velocityX = filteredHorizontalBounceSources.flatten[Event[List[Option[Any]]]]
                    .fold(initVx / Clock.NanoSecond) { (old, _) => -old }
    val velocityY = verticalBounceSources.flatten[Event[List[Option[Any]]]]
                    .fold(initVy / Clock.NanoSecond) { (old, _ ) => -old }

    val incX = Clock.ticks.dMap(dt => tick => Right[Point, Double](tick.toDouble * dt.before(velocityX)))
    val incY = Clock.ticks.dMap(dt => tick => Right[Point, Double](tick.toDouble * dt.before(velocityY)))

    val reset = resetIn.map(pos => Left[Point, Double](pos))

    val posX = (reset || incX).fold(0d){
      case (_, Left(Point(x, _))) => x.toDouble
      case (pX, Right(inc)) => pX + inc
    }
    val posY = (reset || incX).fold(0d){
      case (_, Left(Point(_, y))) => y.toDouble
      case (pY, Right(inc)) => pY + inc
    }

    val shape = new Circle(posX.map(_.toInt), posY.map(_.toInt), diameter)
  }

  val shapes = Var[List[Shape]](List.empty)
  val panel = new ShapesPanel(shapes)

  val bouncingBall = new BouncingBall(200d, 150d, Var(50), panel.Mouse.middleButton.pressed)
  shapes.transform(bouncingBall.shape :: _)

  bouncingBall.horizontalBounceSources.transform(panel.Mouse.leftButton.pressed :: _)
  bouncingBall.verticalBounceSources.transform(panel.Mouse.rightButton.pressed :: _)
}


text:
package org.openqa.selenium.testing;

import com.google.common.collect.Lists;

import org.jboss.netty.handler.codec.http.HttpRequest;

import org.littleshoot.proxy.DefaultHttpProxyServer;
import org.littleshoot.proxy.HttpRequestFilter;

import org.openqa.selenium.Proxy;
import org.openqa.selenium.net.NetworkUtils;
import org.openqa.selenium.net.PortProber;

import java.util.List;

public class ProxyServer {
  private DefaultHttpProxyServer proxyServer;
  private final String baseUrl;
  private final List<String> uris = Lists.newLinkedList();

  public ProxyServer() {
    int port = PortProber.findFreePort();

    String address = new NetworkUtils().getPrivateLocalAddress();
    baseUrl = String.format("%s:%d", address, port);

    proxyServer = new DefaultHttpProxyServer(port, new HttpRequestFilter() {
      @Override
      public void filter(HttpRequest httpRequest) {
        String uri = httpRequest.getUri();
        String[] parts = uri.split("/");
        if (parts.length == 0) {
          return;
        }
        String finalPart = parts[parts.length - 1];
        uris.add(finalPart);
      }
    });

    proxyServer.start();
  }

  public String getBaseUrl() {
    return baseUrl;
  }

  /**
   * Checks if a resource has been requested using the short name of the resource.
   *
   * @param resourceName The short name of the resource to check.
   * @return true if the resource has been called.
   */
  public boolean hasBeenCalled(String resourceName) {
    return uris.contains(resourceName);
  }

  public void destroy() {
    proxyServer.stop();
  }

  public Proxy asProxy() {
    Proxy proxy = new Proxy();
    proxy.setHttpProxy(baseUrl);
    return proxy;
  }
}


text:
package hu.prf.messaging.controller;

import java.io.Serializable;
import java.util.List;

import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;

import hu.prf.messaging.dao.UserDAO;
import hu.prf.messaging.entity.User;
import hu.prf.messaging.util.Session;

@Named
@ViewScoped
public class LoginController implements Serializable {

	private static final long serialVersionUID = 1450699621154920134L;

	@Inject
	private UserDAO userDAO;

	@Inject
	private Session session;

	private String email;

	private String password;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Transactional
	public String login() {
		List<User> results = userDAO.findByEmailAndPassword(email, password);
		if (!results.isEmpty()) {
			session.setUserId(results.get(0).getId());
			return "/content/home.xhtml?faces-redirect=true";
		}
		return "/content/login.xhtml?faces-redirect=true&a=login_error";
	}

}


text:
require 'rvc/vim'

opts :show do
  summary "Show issues on the given entities"
  arg :entity, nil, :lookup => VIM::ManagedEntity, :multi => true
end

def show objs
  issues = objs.map(&:configIssue).flatten.uniq
  issues.each do |issue|
    puts issue.fullFormattedMessage
  end
end

rvc_alias :show, :issues