text:
using device::BluetoothAdapter;
using device::BluetoothDevice;
using device::BluetoothGattConnection;
using device::BluetoothDiscoveryFilter;

namespace proximity_auth {
namespace {
const int kMinDiscoveryRSSI = -90;
const int kDelayAfterGattConnectionMilliseconds = 1000;
}  // namespace

BluetoothLowEnergyConnectionFinder::BluetoothLowEnergyConnectionFinder(
    const std::string& remote_service_uuid,
    const std::string& to_peripheral_char_uuid,
    const std::string& from_peripheral_char_uuid,
    const BluetoothLowEnergyDeviceWhitelist* device_whitelist,
    int max_number_of_tries)
    : remote_service_uuid_(device::BluetoothUUID(remote_service_uuid)),
      to_peripheral_char_uuid_(device::BluetoothUUID(to_peripheral_char_uuid)),
      from_peripheral_char_uuid_(
          device::BluetoothUUID(from_peripheral_char_uuid)),
      device_whitelist_(device_whitelist),
      connected_(false),
      max_number_of_tries_(max_number_of_tries),
      delay_after_gatt_connection_(base::TimeDelta::FromMilliseconds(
          kDelayAfterGattConnectionMilliseconds)),
      weak_ptr_factory_(this) {
}

BluetoothLowEnergyConnectionFinder::~BluetoothLowEnergyConnectionFinder() {
  if (discovery_session_) {
    StopDiscoverySession();
  }

  if (connection_) {
    connection_->RemoveObserver(this);
    connection_.reset();
  }

  if (adapter_) {
    adapter_->RemoveObserver(this);
    adapter_ = NULL;
  }
}

void BluetoothLowEnergyConnectionFinder::Find(
    const ConnectionCallback& connection_callback) {
  if (!device::BluetoothAdapterFactory::IsBluetoothAdapterAvailable()) {
    PA_LOG(WARNING) << "Bluetooth is unsupported on this platform. Aborting.";
    return;
  }
  PA_LOG(INFO) << "Finding connection";

  connection_callback_ = connection_callback;

  device::BluetoothAdapterFactory::GetAdapter(
      base::Bind(&BluetoothLowEnergyConnectionFinder::OnAdapterInitialized,
                 weak_ptr_factory_.GetWeakPtr()));
}

// It's not necessary to observe |AdapterPresentChanged| too. When |adapter_| is
// present, but not powered, it's not possible to scan for new devices.
void BluetoothLowEnergyConnectionFinder::AdapterPoweredChanged(
    BluetoothAdapter* adapter,
    bool powered) {
  DCHECK_EQ(adapter_.get(), adapter);
  PA_LOG(INFO) << "Adapter powered: " << powered;

  // Important: do not rely on |adapter->IsDiscoverying()| to verify if there is
  // an active discovery session. We need to create our own with an specific
  // filter.
  if (powered && (!discovery_session_ || !discovery_session_->IsActive()))
    StartDiscoverySession();
}

void BluetoothLowEnergyConnectionFinder::DeviceAdded(BluetoothAdapter* adapter,
                                                     BluetoothDevice* device) {
  DCHECK_EQ(adapter_.get(), adapter);
  DCHECK(device);
  PA_LOG(INFO) << "Device added: " << device->GetAddress();

  // Note: Only consider |device| when it was actually added/updated during a
  // scanning, otherwise the device is stale and the GATT connection will fail.
  // For instance, when |adapter_| change status from unpowered to powered,
  // |DeviceAdded| is called for each paired |device|.
  if (adapter_->IsPowered() && discovery_session_ &&
      discovery_session_->IsActive())
    HandleDeviceUpdated(device);
}

void BluetoothLowEnergyConnectionFinder::DeviceChanged(
    BluetoothAdapter* adapter,
    BluetoothDevice* device) {
  DCHECK_EQ(adapter_.get(), adapter);
  DCHECK(device);
  PA_LOG(INFO) << "Device changed: " << device->GetAddress();

  // Note: Only consider |device| when it was actually added/updated during a
  // scanning, otherwise the device is stale and the GATT connection will fail.
  // For instance, when |adapter_| change status from unpowered to powered,
  // |DeviceAdded| is called for each paired |device|.
  if (adapter_->IsPowered() && discovery_session_ &&
      discovery_session_->IsActive())
    HandleDeviceUpdated(device);
}

void BluetoothLowEnergyConnectionFinder::HandleDeviceUpdated(
    BluetoothDevice* device) {
  if (connected_)
    return;
  const auto& i = pending_connections_.find(device);
  if (i != pending_connections_.end()) {
    PA_LOG(INFO) << "Pending connection to device " << device->GetAddress();
    return;
  }
  if (device->IsPaired() &&
      (HasService(device) ||
       device_whitelist_->HasDeviceWithAddress(device->GetAddress()))) {
    PA_LOG(INFO) << "Connecting to paired device " << device->GetAddress()
                 << " with service (" << HasService(device)
                 << ") or is whitelisted ("
                 << device_whitelist_->HasDeviceWithAddress(
                        device->GetAddress()) << ")";
    pending_connections_.insert(device);
    CreateGattConnection(device);
  }
}

void BluetoothLowEnergyConnectionFinder::DeviceRemoved(
    BluetoothAdapter* adapter,
    BluetoothDevice* device) {
  if (connected_)
    return;

  const auto& i = pending_connections_.find(device);
  if (i != pending_connections_.end()) {
    PA_LOG(INFO) << "Remove pending connection to  " << device->GetAddress();
    pending_connections_.erase(i);
  }
}

void BluetoothLowEnergyConnectionFinder::OnAdapterInitialized(
    scoped_refptr<BluetoothAdapter> adapter) {
  PA_LOG(INFO) << "Adapter ready";

  adapter_ = adapter;
  adapter_->AddObserver(this);

  // Note: it's not possible to connect with the paired directly, as the
  // temporary MAC may not be resolved automatically (see crbug.com/495402). The
  // Bluetooth adapter will fire |OnDeviceChanged| notifications for all
  // Bluetooth Low Energy devices that are advertising.
  std::vector<BluetoothDevice*> devices = adapter_->GetDevices();
  for (auto* device : devices) {
    PA_LOG(INFO) << "Ignoring device " << device->GetAddress()
                 << " present when adapter was initialized.";
  }

  StartDiscoverySession();
}

void BluetoothLowEnergyConnectionFinder::OnDiscoverySessionStarted(
    scoped_ptr<device::BluetoothDiscoverySession> discovery_session) {
  PA_LOG(INFO) << "Discovery session started";
  discovery_session_ = discovery_session.Pass();
}

void BluetoothLowEnergyConnectionFinder::OnStartDiscoverySessionError() {
  PA_LOG(WARNING) << "Error starting discovery session";
}

void BluetoothLowEnergyConnectionFinder::StartDiscoverySession() {
  DCHECK(adapter_);
  if (discovery_session_ && discovery_session_->IsActive()) {
    PA_LOG(INFO) << "Discovery session already active";
    return;
  }

  // Discover only low energy (LE) devices with strong enough signal.
  scoped_ptr<BluetoothDiscoveryFilter> filter(new BluetoothDiscoveryFilter(
      BluetoothDiscoveryFilter::Transport::TRANSPORT_LE));
  filter->SetRSSI(kMinDiscoveryRSSI);

  adapter_->StartDiscoverySessionWithFilter(
      filter.Pass(),
      base::Bind(&BluetoothLowEnergyConnectionFinder::OnDiscoverySessionStarted,
                 weak_ptr_factory_.GetWeakPtr()),
      base::Bind(
          &BluetoothLowEnergyConnectionFinder::OnStartDiscoverySessionError,
          weak_ptr_factory_.GetWeakPtr()));
}

void BluetoothLowEnergyConnectionFinder::OnDiscoverySessionStopped() {
  PA_LOG(INFO) << "Discovery session stopped";
  discovery_session_.reset();
}

void BluetoothLowEnergyConnectionFinder::OnStopDiscoverySessionError() {
  PA_LOG(WARNING) << "Error stopping discovery session";
}

void BluetoothLowEnergyConnectionFinder::StopDiscoverySession() {
  PA_LOG(INFO) << "Stopping discovery sesison";

  if (!adapter_) {
    PA_LOG(WARNING) << "Adapter not initialized";
    return;
  }
  if (!discovery_session_ || !discovery_session_->IsActive()) {
    PA_LOG(INFO) << "No Active discovery session";
    return;
  }

  discovery_session_->Stop(
      base::Bind(&BluetoothLowEnergyConnectionFinder::OnDiscoverySessionStopped,
                 weak_ptr_factory_.GetWeakPtr()),
      base::Bind(
          &BluetoothLowEnergyConnectionFinder::OnStopDiscoverySessionError,
          weak_ptr_factory_.GetWeakPtr()));
}

bool BluetoothLowEnergyConnectionFinder::HasService(
    BluetoothDevice* remote_device) {
  if (remote_device) {
    PA_LOG(INFO) << "Device " << remote_device->GetAddress() << " has "
                 << remote_device->GetUUIDs().size() << " services.";
    std::vector<device::BluetoothUUID> uuids = remote_device->GetUUIDs();
    for (const auto& service_uuid : uuids) {
      if (remote_service_uuid_ == service_uuid) {
        return true;
      }
    }
  }
  return false;
}

void BluetoothLowEnergyConnectionFinder::OnCreateGattConnectionError(
    std::string device_address,
    BluetoothDevice::ConnectErrorCode error_code) {
  PA_LOG(WARNING) << "Error creating connection to device " << device_address
                  << " : error code = " << error_code;

  BluetoothDevice* device = GetDevice(device_address);
  const auto& i = pending_connections_.find(device);
  if (i != pending_connections_.end()) {
    PA_LOG(INFO) << "Remove pending connection to  " << device->GetAddress();
    pending_connections_.erase(i);
  }
}

void BluetoothLowEnergyConnectionFinder::OnGattConnectionCreated(
    scoped_ptr<BluetoothGattConnection> gatt_connection) {
  if (connected_) {
    CloseGattConnection(gatt_connection.Pass());
    return;
  }

  PA_LOG(INFO) << "GATT connection with " << gatt_connection->GetDeviceAddress()
               << " created.";
  connected_ = true;
  pending_connections_.clear();

  gatt_connection_ = gatt_connection.Pass();

  // This is a workaround for crbug.com/498850. Currently, trying to write/read
  // characteristics immediatelly after the GATT connection was established
  // fails with the very informative GATT_ERROR_FAILED.
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&BluetoothLowEnergyConnectionFinder::CompleteConnection,
                 weak_ptr_factory_.GetWeakPtr()),
      delay_after_gatt_connection_);

  StopDiscoverySession();
}

void BluetoothLowEnergyConnectionFinder::CompleteConnection() {
  connection_ = CreateConnection(gatt_connection_.Pass());
  connection_->AddObserver(this);
  connection_->Connect();
}

void BluetoothLowEnergyConnectionFinder::CreateGattConnection(
    device::BluetoothDevice* remote_device) {
  PA_LOG(INFO) << "Creating GATT connection with "
               << remote_device->GetAddress();
  remote_device->CreateGattConnection(
      base::Bind(&BluetoothLowEnergyConnectionFinder::OnGattConnectionCreated,
                 weak_ptr_factory_.GetWeakPtr()),
      base::Bind(
          &BluetoothLowEnergyConnectionFinder::OnCreateGattConnectionError,
          weak_ptr_factory_.GetWeakPtr(), remote_device->GetAddress()));
}

void BluetoothLowEnergyConnectionFinder::CloseGattConnection(
    scoped_ptr<device::BluetoothGattConnection> gatt_connection) {
  DCHECK(gatt_connection);
  PA_LOG(INFO) << "Closing GATT connection with "
               << gatt_connection->GetDeviceAddress();

  // Destroying the BluetoothGattConnection also disconnects it.
  gatt_connection.reset();
}

scoped_ptr<Connection> BluetoothLowEnergyConnectionFinder::CreateConnection(
    scoped_ptr<BluetoothGattConnection> gatt_connection) {
  remote_device_.bluetooth_address = gatt_connection->GetDeviceAddress();

  return make_scoped_ptr(new BluetoothLowEnergyConnection(
      remote_device_, adapter_, remote_service_uuid_, to_peripheral_char_uuid_,
      from_peripheral_char_uuid_, gatt_connection.Pass(),
      max_number_of_tries_));
}

void BluetoothLowEnergyConnectionFinder::OnConnectionStatusChanged(
    Connection* connection,
    Connection::Status old_status,
    Connection::Status new_status) {
  DCHECK_EQ(connection, connection_.get());
  PA_LOG(INFO) << "OnConnectionStatusChanged: " << old_status << " -> "
               << new_status;

  if (!connection_callback_.is_null() && connection_->IsConnected()) {
    adapter_->RemoveObserver(this);
    connection_->RemoveObserver(this);

    // Note: any observer of |connection_| added in |connection_callback_| will
    // also receive this |OnConnectionStatusChanged| notification (IN_PROGRESS
    // -> CONNECTED).
    connection_callback_.Run(connection_.Pass());
    connection_callback_.Reset();
  } else if (old_status == Connection::IN_PROGRESS) {
    PA_LOG(WARNING) << "Connection failed. Retrying.";
    RestartDiscoverySessionWhenReady();
  }
}

void BluetoothLowEnergyConnectionFinder::RestartDiscoverySessionWhenReady() {
  PA_LOG(INFO) << "Trying to restart discovery.";

  // To restart scanning for devices, it's necessary to ensure that:
  // (i) the GATT connection to |remove_device_| is closed;
  // (ii) there is no pending call to
  // |device::BluetoothDiscoverySession::Stop()|.
  // The second condition is satisfied when |OnDiscoveryStopped| is called and
  // |discovery_session_| is reset.
  if ((!gatt_connection_ || !gatt_connection_->IsConnected()) &&
      !discovery_session_) {
    PA_LOG(INFO) << "Ready to start discovery.";
    connection_.reset();
    connected_ = false;
    StartDiscoverySession();
  } else {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::Bind(&BluetoothLowEnergyConnectionFinder::
                                  RestartDiscoverySessionWhenReady,
                              weak_ptr_factory_.GetWeakPtr()));
  }
}

void BluetoothLowEnergyConnectionFinder::SetDelayForTesting(
    base::TimeDelta delay) {
  delay_after_gatt_connection_ = delay;
}

BluetoothDevice* BluetoothLowEnergyConnectionFinder::GetDevice(
    std::string device_address) {
  // It's not possible to simply use
  // |adapter_->GetDevice(GetRemoteDeviceAddress())| to find the device with MAC
  // address |GetRemoteDeviceAddress()|. For paired devices,
  // BluetoothAdapter::GetDevice(XXX) searches for the temporary MAC address
  // XXX, whereas |remote_device_.bluetooth_address| is the real MAC address.
  // This is a bug in the way device::BluetoothAdapter is storing the devices
  // (see crbug.com/497841).
  std::vector<BluetoothDevice*> devices = adapter_->GetDevices();
  for (const auto& device : devices) {
    if (device->GetAddress() == device_address)
      return device;
  }
  return nullptr;
}

}  // namespace proximity_auth


text:
<?xml version="1.0"?>
<!--

     Copyright 2005-2014 Red Hat, Inc.

     Red Hat licenses this file to you 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.

-->
<beans xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_1.xsd"
	version="1.1">

	<scan>
		<exclude name="org.apache.cxf.**" />
                <exclude name="com.google.common.util.concurrent.ServiceManager" />
 	</scan>
</beans>

redpajama_set_name: RedPajamaGithub


text:
@interface AccountWindowController : NSWindowController
{
	IBOutlet NSTextField *jidBox;
	IBOutlet NSTextField *passwordBox;
	IBOutlet NSTextField *serverBox;
}

- (IBAction) yes: (id)sender;
- (IBAction) no: (id)sender;

@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>React v0.14.4 | React</title>
  <meta name="viewport" content="width=device-width">
  <meta property="og:title" content="React v0.14.4 | React">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://facebook.github.io/react/blog/2015/12/29/react-v0.14.4.html">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="A JavaScript library for building user interfaces">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://facebook.github.io/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/react/css/syntax.css">
  <link rel="stylesheet" href="/react/css/codemirror.css">
  <link rel="stylesheet" href="/react/css/react.css">

          React

Docs

Support

Download

Blog

            <input id="algolia-doc-search" type="text" placeholder="Search docs..." />

GitHub

React Native

Recent posts

Create Apps with No Configuration

Mixins Considered Harmful

Introducing React's Error Code System

React v15.0.1

React v15.0

React v0.14.8

React v15.0 Release Candidate 2

React v15.0 Release Candidate

New Versioning Scheme

Discontinuing IE 8 Support in React DOM

All posts ...

  React v0.14.4

  December 29, 2015
  by

      Ben Alpert

Happy December! We have a minor point release today. It has just a few small bug fixes.

The release is now available for download:

React

Dev build with warnings: https://fb.me/react-0.14.4.js

Minified build for production: https://fb.me/react-0.14.4.min.js

React with Add-Ons

Dev build with warnings: https://fb.me/react-with-addons-0.14.4.js

Minified build for production: https://fb.me/react-with-addons-0.14.4.min.js

React DOM (include React in the page before React DOM)

Dev build with warnings: https://fb.me/react-dom-0.14.4.js

Minified build for production: https://fb.me/react-dom-0.14.4.min.js

React DOM Server (include React in the page before React DOM Server)

Dev build with warnings: https://fb.me/react-dom-server-0.14.4.js

Minified build for production: https://fb.me/react-dom-server-0.14.4.min.js

We've also published version 0.14.4 of the react, react-dom, and addons packages on npm and the react package on bower.

Changelog #

React #

Minor internal changes for better compatibility with React Native

React DOM #

The autoCapitalize and autoCorrect props are now set as attributes in the DOM instead of properties to improve cross-browser compatibility

Fixed bug with controlled <select> elements not handling updates properly

React Perf Add-on #

Some DOM operation names have been updated for clarity in the output of .printDOM()

        A Facebook & Instagram collaboration.

        Acknowledgements

        © 2013–2016 Facebook Inc.

        Documentation licensed under CC BY 4.0.


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Megadraft - Draft.JS Rich Text Editor</title>

    <meta name="author" content="Globo.com">
    <meta name="description" content="Megadraft is a Rich Text editor built on top of Facebook's Draft.JS featuring a nice default base of components and extensibility" />
    <meta name="keywords" content="editor, rich text, JavaScript, react, draft.js" />
    <meta name="robots" content="all" />

    <meta property="og:url" content="https://globocom.github.io/megadraft" />
    <meta property="og:title" content="Megadraft - Draft.JS Rich Text Editor" />
    <meta property="og:description" content="Megadraft is a Rich Text editor built on top of Facebook's Draft.JS featuring a nice default base of components and extensibility" />
    <meta property="og:image" content="https://globocom.github.io/megadraft/images/megadraft_logo_black_version_300x300.png" />
    <meta property="og:type" content="website" />
    <meta property="og:locale" content="pt_BR" />
    <link rel="icon" href="images/favicon.ico" type="image/x-icon">

    <link
      href="https://fonts.googleapis.com/css?family=Roboto:400,300,600"
      rel="stylesheet"
      type="text/css">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/styles/github.min.css">
    <link href="styles/app.css" rel="stylesheet">


text:
import angular from 'angular';
import Storage from 'stax2/frontend/services/storage';

import PushnotificationFactory from './pushnotification.factory';

let pushnotificationModule = angular.module ('pushnotification.service', [ Storage ])
.factory ('PushNotification', PushnotificationFactory);

export default pushnotificationModule.name;


text:
<audio data-artist="{{ currentSong.user.username }}" data-title="{{ currentSong.title }}" ng-src="{{ currentSong.stream_url || '' }}" autoplay></audio>

    <button class="control" ng-click="previous()"></button>
    <button class="control" ng-click="togglePlayback()"></button>
    <button class="control" ng-click="next()" ng-disabled="currentSongIndex + 1 === songs.length"></button>

    {{ currentSong.user.username }}

{{ currentSong.title }}


text:
"""Test OCSP."""

import logging
import os
import sys
import unittest

sys.path[0:0] = [""]

import pymongo
from pymongo.errors import ServerSelectionTimeoutError

CA_FILE = os.environ.get("CA_FILE")
OCSP_TLS_SHOULD_SUCCEED = os.environ.get("OCSP_TLS_SHOULD_SUCCEED") == "true"

# Enable logs in this format:
# 2020-06-08 23:49:35,982 DEBUG ocsp_support Peer did not staple an OCSP response
FORMAT = "%(asctime)s %(levelname)s %(module)s %(message)s"
logging.basicConfig(format=FORMAT, level=logging.DEBUG)

if sys.platform == "win32":
    # The non-stapled OCSP endpoint check is slow on Windows.
    TIMEOUT_MS = 5000
else:
    TIMEOUT_MS = 500

def _connect(options):
    uri = ("mongodb://localhost:27017/?serverSelectionTimeoutMS=%s&tlsCAFile=%s&%s") % (
        TIMEOUT_MS,
        CA_FILE,
        options,
    )
    print(uri)
    client = pymongo.MongoClient(uri)
    client.admin.command("ping")

class TestOCSP(unittest.TestCase):
    def test_tls_insecure(self):
        # Should always succeed
        options = "tls=true&tlsInsecure=true"
        _connect(options)

    def test_allow_invalid_certificates(self):
        # Should always succeed
        options = "tls=true&tlsAllowInvalidCertificates=true"
        _connect(options)

    def test_tls(self):
        options = "tls=true"
        if not OCSP_TLS_SHOULD_SUCCEED:
            self.assertRaisesRegex(
                ServerSelectionTimeoutError, "invalid status response", _connect, options
            )
        else:
            _connect(options)

if __name__ == "__main__":
    unittest.main()


text:
package www.yunpan.com.service.impl;

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

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import www.yunpan.com.db.IPermissionDao;
import www.yunpan.com.db.IPermissionRoleDao;
import www.yunpan.com.db.IRoleDao;
import www.yunpan.com.domain.PermissionDomain;
import www.yunpan.com.domain.RoleDomain;
import www.yunpan.com.entity.PermissionEntity;
import www.yunpan.com.entity.PermissionRoleEntity;
import www.yunpan.com.entity.RoleEntity;
import www.yunpan.com.service.IRoleService;

@Service
public class IRoleServiceImpl implements IRoleService {

	@Autowired
	private IRoleDao roleDao;

	@Autowired
    private IPermissionDao permissionDao;

	@Autowired
	private IPermissionRoleDao permissionRoleDao;

	public void insertRole(RoleEntity role) {
		roleDao.insertRole(role);

	}

	public void updateRole(RoleEntity role,String[] permissionIds) {
		permissionRoleDao.deletePermissionRole(role.getId());
		roleDao.updateRole(role);
		if(null!=permissionIds){
			for(String permissionId:permissionIds){
				PermissionEntity permissionEntity=permissionDao.findPermissionById(permissionId);
				if(null!=permissionEntity){
					PermissionRoleEntity permissionRoleEntity=new PermissionRoleEntity();
					permissionRoleEntity.setRoleId(role.getId());
					permissionRoleEntity.setPermissionId(permissionEntity.getId());
					permissionRoleDao.insertPermissionRole(permissionRoleEntity);
				}
			}
		}

	}

	public void deleteRole(String id) {

		roleDao.deleteRole(id);

	}

	public RoleDomain findRoleById(String id) {
		RoleEntity roleEntity= roleDao.findRoleById(id);
		List<PermissionEntity> permissionList=permissionDao.queryPermissionByRole(id);
		List<PermissionDomain> permissionDomainList=new ArrayList<PermissionDomain>();
		for(PermissionEntity entity:permissionList){
			PermissionDomain domain=new PermissionDomain();
			BeanUtils.copyProperties(entity, domain);
			permissionDomainList.add(domain);
		}
		RoleDomain roleDomain=new RoleDomain();
		BeanUtils.copyProperties(roleEntity, roleDomain);
		roleDomain.setPermissions(permissionDomainList);
		return roleDomain;
	}

	public List<RoleEntity> fineAllRole() {
		return roleDao.fineAllRole();
	}

}


text:
id: version-4.0.0-webworkers
title: Webworkers
original_id: webworkers
---

_A new FuseBox v4 feature_

### What are Workers?

Workers are a means of multi-threading in javascript. Because javascript is single-threaded, workers must act as a
_totally separate context_. The following is the problem set which FuseBox works through:

1. Workers never have acess to the `window` object
2. Each worker must have its own bundle
3. All paths to workers must be overwritten to instead point to the workers' bundle.

Fortunately, FuseBox catches Workers and handles all of these by default.

<!--
a very simple and intuitive way of working with `Worker` and `ShareWorker` object. What is the
actual problem and why does it need special treatments? To answer this question let's define requirements first;

- Worker doesn't have access to `window` object hence needs a special treatment
- Worker needs to be in a separate bundle
- Worker might require transpilation (bundling)
- Path to workers need to be overridden

For example:

```ts
new Worker('./path/to/worker.js');
```

This is how a typical worker looks like. But here is a problem. This file needs to be publicly available. Here comes
FuseBox, which offers automatic bundling with path re-writes and it supports production source maps too! Let's break it
down and try an example. -->

---

## Setting it up

1. First, create an entry point file. Similar to your project entry point, this is a file which acts as the root of a
   bundle.

   ```ts
   // src/workers/my-worker.ts
   self.addEventListener(
     'message',
     function (e) {
       setInterval(() => {
         self.postMessage('I am working');
       }, 1000);
     },
     false,
   );
   ```

2. (optional) For the sake of efficiency, it's usually best to put Worker entry point files in a folder that can be
   ignored by the rest of the project. If you don't do this, the _entire project bundle_ will update with every change
   to the worker, instead of just the worker bundle.

   ```ts
   fusebox({
     watch: { ignored: ['src/workers/*'] },
   });
   ```

3. Finally, call `new Worker()` and pass it a **static** path argument to it's entry file.

   ```ts
   const myWorker = new Worker('./workers/my-worker');
   myWorker.postMessage(['hello']);
   myWorker.onmessage = function (e) {
     console.log('Message received from worker', e);
   };
   ```

### Conditional Static Path Arguments

FuseBox requires the path variable passed to the `Worker` or `SharedWorker` object to always be static.

If you want to add some conditions to it, you can do it as described below:

```ts
if (process.env.NODE_ENV === 'development') {
  new Worker('./workers/dev-my-worker');
} else {
  new Worker('./workers/my-worker');
}
```

---

## Default behavior

- Watching - WebWorker bundles will be watched automatically and re-bundled when changed.
- Shared Cache object - to avoid racing conditions everything will be bundling in 1 file

---

## Configuring

In most scenarios, the default configuration should do the trick. But if you would like to add plugins or toggle some
flags, here is what you can do:

```ts
fusebox({
  webWorkers : {
     config: {
       alias : { foo : "bar"}
     };
  }
})
```

There are restrictions, for example the following list of items cannot be overridden:

| field     | value      | reason                                                                 |
| --------- | ---------- | ---------------------------------------------------------------------- |
| homeDir   | [parent]   | The exact same directory,                                              |
| target    | web-worker | FuseBox sets a special target "web-worker",                            |
| devServer | false      | You cannot launch a devServer inside a webworker process               |
| hmr       | false      | WebWorker is an isolated instance, which doesn't have access to window |
| entry     | [differs]  | Entry is being set automatically after the path has been resolved      |
| logging   | [disabled] | Logging is disabled unless `--verbose` flag is passed                  |


text:
package Model;

import Constants.TileType;
import Model.TileList.TileList;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Deck extends TileList {
	private static volatile Deck instance = new Deck();

	private Random randomGenerator = new Random();

	// private constructor
	private Deck() {
	}

	public static Deck getInstance() {
		return instance;
	}

	public void initializeDeck() {
		tileList.clear();
		for (TileType types : TileType.values()) {
			for (int i = 1; i < 10; i++) {
				tileList.add(new Tile(types, i));
				tileList.add(new Tile(types, i));
				tileList.add(new Tile(types, i));
				tileList.add(new Tile(types, i));
			}
		}
		update();
	}

	public Tile drawTile() {
		Tile randomTile;
		randomTile = tileList.get(randomGenerator.nextInt(tileList.size()));
		removeTile(randomTile);

		return randomTile;
	}
}


text:
require_relative "spec_helper"

describe Gemnigma::RotatorEncrypt do
  before :each do
    @rot_enc = Gemnigma::RotatorEncrypt.new
  end

  describe "#initialize" do
    context "with one optionally defined parameter" do
      it "should return an instance of RotatorEncrypt" do
        rot = Gemnigma::RotatorEncrypt.new(Gemnigma::Key.new)
        expect(rot).to be_an_instance_of Gemnigma::RotatorEncrypt
      end

      it "should default to 41521 if an invalid key is used for initialization" do
        rot = Gemnigma::RotatorEncrypt.new(21345)
        expect(rot.key_map).to eql([41, 15, 52, 21])
      end
    end

    context "without parameters" do
      it "should return an instance of RotatorEncrypt" do
        expect(@rot_enc).to be_an_instance_of Gemnigma::RotatorEncrypt
      end

      it "should default to 41521 as the key map" do
        expect(@rot_enc.key_map).to eql([41, 15, 52, 21])
      end
    end
  end

  describe "#char_rotation" do
    it "should be a private method" do
      expect{ @rot_enc.char_rotation }.to raise_error(NoMethodError)
    end

    it "should exist as a method of the class RotatorEncrypt" do
      expect(@rot_enc.private_methods.include? :char_rotation).to be true
    end

    it "should return an array" do
      expect(@rot_enc.send(:char_rotation).class).to eql(Array)
    end

    it "should return an array with a length of 4" do
      expect(@rot_enc.send(:char_rotation).length).to eql(4)
    end

    it "should return an array of numbers" do
      expect(@rot_enc.send(:char_rotation).all? {|num| num.is_a? Integer}).to be true
    end

    it "should the values in two arrays and return a new array" do
      allow(@rot_enc).to receive(:get_offset) { [7,2,2,5] }
      allow(@rot_enc).to receive(:key_map) { [41, 15, 52, 21] }

      expect(@rot_enc.send(:char_rotation)).to eql([48, 17, 54, 26])
    end
  end

  describe "#map_word_to_key" do
    it "should be a private method" do
      expect{ @rot_enc.map_word_to_key }.to raise_error(NoMethodError)
    end

    it "should take one parameter" do
      expect{ @rot_enc.send(:map_word_to_key) }.to raise_error(ArgumentError)
      expect{ @rot_enc.send(:map_word_to_key, "hello", "world") }.to raise_error(ArgumentError)
    end

    it "should return an array" do
      expect(@rot_enc.send(:map_word_to_key, "Hello").class).to eql(Array)
    end

    it "should return an array of arrays" do
      expect(@rot_enc.send(:map_word_to_key, "Hello").all? {|item| item.is_a? Array}).to be true
    end

    it "should return an array of arrays containing a string and a number" do
      result = @rot_enc.send(:map_word_to_key, "Hello").map do |arr|
        arr.all? {|item| item.class == String || item.class == Fixnum}
      end
      expect(result.all?).to be true
    end

    it "should return an array length based on passed in word" do
      expect(@rot_enc.send(:map_word_to_key, "H").length).to eql(1)
      expect(@rot_enc.send(:map_word_to_key, "He").length).to eql(2)
      expect(@rot_enc.send(:map_word_to_key, "Hel").length).to eql(3)
      expect(@rot_enc.send(:map_word_to_key, "Hell").length).to eql(4)
      expect(@rot_enc.send(:map_word_to_key, "Hello").length).to eql(5)
    end
  end

  describe "#rot_encrypt" do
    it "should take one parameter" do
      expect{ @rot_enc.rot_encrypt }.to raise_error(ArgumentError)
    end

    it "should return a new string" do
      expect(@rot_enc.rot_encrypt("hello")).not_to eql("hello")
    end

    it "should encrypt a string based on passed in rotation number" do
      allow(@rot_enc).to receive(:get_offset) { [7,2,2,5] }

      expect(@rot_enc.rot_encrypt("hello")).to eql("qv0.x")
      expect(@rot_enc.rot_encrypt("hello world")).to eql("qv0.xo.b02s")
      expect(@rot_enc.rot_encrypt("a longer string. punctuations . , ")).to eql("jo0bwxteg98er4vyg69al 902z3a1onxio")
      expect(@rot_enc.rot_encrypt("a message from aliens in the land of foo bar")).to eql("jo1419p6nouex3m0uzta1oxag w4g2pamo35gw3bgspe")
      expect(@rot_enc.rot_encrypt("one more for good measure")).to eql( "x4txv564gw3egx3bmo14j99en")
    end

    it "should return a string of lowercase characters only" do
      allow(@rot_enc).to receive(:get_offset) { [7,2,2,5] }

      expect(@rot_enc.rot_encrypt("HELLO")).to eql("qv0.x")
      expect(@rot_enc.rot_encrypt("HELLO WORLD")).to eql("qv0.xo.b02s")
      expect(@rot_enc.rot_encrypt("A LONGER STRING. PUNCTUATIONS . , ")).to eql("jo0bwxteg98er4vyg69al 902z3a1onxio")
      expect(@rot_enc.rot_encrypt("A MESSAGE FROM ALIENS IN THE LAND OF FOO BAR")).to eql("jo1419p6nouex3m0uzta1oxag w4g2pamo35gw3bgspe")
      expect(@rot_enc.rot_encrypt("ONE MORE FOR GOOD MEASURE")).to eql( "x4txv564gw3egx3bmo14j99en")
    end
  end

  describe "#get_offset" do
    it "should be a private method" do
      expect{ @rot_enc.get_offset }.to raise_error(NoMethodError)
    end

    it "should return an array" do
      expect(@rot_enc.send(:get_offset)).to be_an(Array)
    end

    it "should return an array of integers" do
      expect(@rot_enc.send(:get_offset).all? {|item| item.class == Fixnum }).to be true
    end
  end

  describe "#map_key_to_offset" do
    it "should be a private method" do
      expect{ @rot_enc.map_key_to_offset }.to raise_error(NoMethodError)
    end

    it "should return an array" do
      expect(@rot_enc.send(:map_key_to_offset)).to be_an(Array)
    end

    it "should return an array with four items" do
      expect(@rot_enc.send(:map_key_to_offset).length).to eql(4)
    end

    it "should return a nested array" do
      expect(@rot_enc.send(:map_key_to_offset).all? {|item| item.class == Array }).to be true
    end
  end

end


text:
package io.strimzi.operator.cluster.operator.assembly;

import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.apps.StatefulSet;
import io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget;
import io.strimzi.api.kafka.model.Kafka;
import io.strimzi.api.kafka.model.KafkaResources;
import io.strimzi.api.kafka.model.StrimziPodSet;
import io.strimzi.api.kafka.model.status.KafkaStatus;
import io.strimzi.api.kafka.model.storage.Storage;
import io.strimzi.operator.PlatformFeaturesAvailability;
import io.strimzi.operator.cluster.ClusterOperatorConfig;
import io.strimzi.operator.cluster.FeatureGates;
import io.strimzi.operator.cluster.model.Ca;
import io.strimzi.operator.cluster.model.ClusterCa;
import io.strimzi.operator.cluster.model.DnsNameGenerator;
import io.strimzi.operator.cluster.model.ImagePullPolicy;
import io.strimzi.operator.cluster.model.KafkaVersionChange;
import io.strimzi.operator.cluster.model.ModelUtils;
import io.strimzi.operator.cluster.model.ZookeeperCluster;
import io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier;
import io.strimzi.operator.cluster.operator.resource.StatefulSetOperator;
import io.strimzi.operator.common.operator.resource.StrimziPodSetOperator;
import io.strimzi.operator.cluster.operator.resource.ZooKeeperRoller;
import io.strimzi.operator.cluster.operator.resource.ZookeeperLeaderFinder;
import io.strimzi.operator.cluster.operator.resource.ZookeeperScaler;
import io.strimzi.operator.cluster.operator.resource.ZookeeperScalerProvider;
import io.strimzi.operator.common.Annotations;
import io.strimzi.operator.common.Reconciliation;
import io.strimzi.operator.common.ReconciliationLogger;
import io.strimzi.operator.common.Util;
import io.strimzi.operator.common.model.Labels;
import io.strimzi.operator.common.operator.resource.ConfigMapOperator;
import io.strimzi.operator.common.operator.resource.NetworkPolicyOperator;
import io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator;
import io.strimzi.operator.common.operator.resource.PodDisruptionBudgetV1Beta1Operator;
import io.strimzi.operator.common.operator.resource.PodOperator;
import io.strimzi.operator.common.operator.resource.PvcOperator;
import io.strimzi.operator.common.operator.resource.ReconcileResult;
import io.strimzi.operator.common.operator.resource.SecretOperator;
import io.strimzi.operator.common.operator.resource.ServiceAccountOperator;
import io.strimzi.operator.common.operator.resource.ServiceOperator;
import io.strimzi.operator.common.operator.resource.StorageClassOperator;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static java.util.Collections.singletonList;

/**
 * Class used for reconciliation of ZooKeeper. This class contains both the steps of the ZooKeeper
 * reconciliation pipeline and is also used to store the state between them.
 */
@SuppressWarnings({"checkstyle:ClassFanOutComplexity"})
public class ZooKeeperReconciler {
    private static final ReconciliationLogger LOGGER = ReconciliationLogger.create(ZooKeeperReconciler.class.getName());

    private final Reconciliation reconciliation;
    private final Vertx vertx;
    private final long operationTimeoutMs;
    private final ZookeeperCluster zk;
    private final KafkaVersionChange versionChange;
    private final ClusterCa clusterCa;
    private final List<String> maintenanceWindows;
    private final String operatorNamespace;
    private final Labels operatorNamespaceLabels;
    private final boolean isNetworkPolicyGeneration;
    private final PlatformFeaturesAvailability pfa;
    private final FeatureGates featureGates;
    private final int adminSessionTimeoutMs;
    private final ImagePullPolicy imagePullPolicy;
    private final List<LocalObjectReference> imagePullSecrets;

    private final StatefulSetOperator stsOperator;
    private final StrimziPodSetOperator strimziPodSetOperator;
    private final SecretOperator secretOperator;
    private final ServiceAccountOperator serviceAccountOperator;
    private final ServiceOperator serviceOperator;
    private final PvcOperator pvcOperator;
    private final StorageClassOperator storageClassOperator;
    private final ConfigMapOperator configMapOperator;
    private final NetworkPolicyOperator networkPolicyOperator;
    private final PodDisruptionBudgetOperator podDisruptionBudgetOperator;
    private final PodDisruptionBudgetV1Beta1Operator podDisruptionBudgetV1Beta1Operator;
    private final PodOperator podOperator;

    private final ZookeeperScalerProvider zooScalerProvider;
    private final ZookeeperLeaderFinder zooLeaderFinder;

    private final Integer currentReplicas;

    private final Set<String> fsResizingRestartRequest = new HashSet<>();
    private ReconcileResult<StatefulSet> statefulSetDiff;
    private ReconcileResult<StrimziPodSet> podSetDiff;
    private boolean existingCertsChanged = false;
    private String loggingHash = "";

    /**
     * Constructs the ZooKeeper reconciler
     *
     * @param reconciliation            Reconciliation marker
     * @param vertx                     Vert.x instance
     * @param config                    Cluster Operator Configuration
     * @param supplier                  Supplier with Kubernetes Resource Operators
     * @param pfa                       PlatformFeaturesAvailability describing the environment we run in
     * @param kafkaAssembly             The Kafka custom resource
     * @param versionChange             Description of Kafka upgrade / downgrade state
     * @param currentReplicas           The current number of replicas
     * @param oldStorage                The storage configuration of the current cluster (null if it does not exist yet)
     * @param clusterCa                 The Cluster CA instance
     */
    public ZooKeeperReconciler(
            Reconciliation reconciliation,
            Vertx vertx,
            ClusterOperatorConfig config,
            ResourceOperatorSupplier supplier,
            PlatformFeaturesAvailability pfa,
            Kafka kafkaAssembly,
            KafkaVersionChange versionChange,
            Storage oldStorage,
            int currentReplicas,
            ClusterCa clusterCa
    ) {
        this.reconciliation = reconciliation;
        this.vertx = vertx;
        this.operationTimeoutMs = config.getOperationTimeoutMs();
        this.zk = ZookeeperCluster.fromCrd(reconciliation, kafkaAssembly, config.versions(), oldStorage, currentReplicas);
        this.versionChange = versionChange;
        this.currentReplicas = currentReplicas;
        this.clusterCa = clusterCa;
        this.maintenanceWindows = kafkaAssembly.getSpec().getMaintenanceTimeWindows();
        this.operatorNamespace = config.getOperatorNamespace();
        this.operatorNamespaceLabels = config.getOperatorNamespaceLabels();
        this.isNetworkPolicyGeneration = config.isNetworkPolicyGeneration();
        this.pfa = pfa;
        this.featureGates = config.featureGates();
        this.adminSessionTimeoutMs = config.getZkAdminSessionTimeoutMs();
        this.imagePullPolicy = config.getImagePullPolicy();
        this.imagePullSecrets = config.getImagePullSecrets();

        this.stsOperator = supplier.stsOperations;
        this.strimziPodSetOperator = supplier.strimziPodSetOperator;
        this.secretOperator = supplier.secretOperations;
        this.serviceAccountOperator = supplier.serviceAccountOperations;
        this.serviceOperator = supplier.serviceOperations;
        this.pvcOperator = supplier.pvcOperations;
        this.storageClassOperator = supplier.storageClassOperations;
        this.configMapOperator = supplier.configMapOperations;
        this.networkPolicyOperator = supplier.networkPolicyOperator;
        this.podDisruptionBudgetOperator = supplier.podDisruptionBudgetOperator;
        this.podDisruptionBudgetV1Beta1Operator = supplier.podDisruptionBudgetV1Beta1Operator;
        this.podOperator = supplier.podOperations;

        this.zooScalerProvider = supplier.zkScalerProvider;
        this.zooLeaderFinder = supplier.zookeeperLeaderFinder;
    }

    /**
     * The main reconciliation method which triggers the whole reconciliation pipeline. This is the method which is
     * expected to be called from the outside to trigger the reconciliation.
     *
     * @param kafkaStatus   The Kafka Status class for adding conditions to it during the reconciliation
     * @param dateSupplier  Date supplier for checking maintenance windows
     *
     * @return              Future which completes when the reconciliation completes
     */
    public Future<Void> reconcile(KafkaStatus kafkaStatus, Supplier<Date> dateSupplier)    {
        return modelWarnings(kafkaStatus)
                .compose(i -> jmxSecret())
                .compose(i -> manualPodCleaning())
                .compose(i -> networkPolicy())
                .compose(i -> manualRollingUpdate())
                .compose(i -> logVersionChange())
                .compose(i -> serviceAccount())
                .compose(i -> pvcs())
                .compose(i -> service())
                .compose(i -> headlessService())
                .compose(i -> certificateSecret(dateSupplier))
                .compose(i -> loggingAndMetricsConfigMap())
                .compose(i -> podDisruptionBudget())
                .compose(i -> podDisruptionBudgetV1Beta1())
                .compose(i -> statefulSet())
                .compose(i -> podSet())
                .compose(i -> scaleDown())
                .compose(i -> rollingUpdate())
                .compose(i -> podsReady())
                .compose(i -> scaleUp())
                .compose(i -> scalingCheck())
                .compose(i -> serviceEndpointsReady())
                .compose(i -> headlessServiceEndpointsReady())
                .compose(i -> deletePersistentClaims());
    }

    /**
     * Takes the warning conditions from the Model and adds them in the KafkaStatus
     *
     * @param kafkaStatus   The Kafka Status where the warning conditions will be added
     *
     * @return              Completes when the warnings are added to the status object
     */
    protected Future<Void> modelWarnings(KafkaStatus kafkaStatus) {
        kafkaStatus.addConditions(zk.getWarningConditions());
        return Future.succeededFuture();
    }

    /**
     * Manages the secret with JMX credentials when JMX is enabled
     *
     * @return  Completes when the JMX secret is successfully created or updated
     */
    protected Future<Void> jmxSecret() {
        return secretOperator.getAsync(reconciliation.namespace(), KafkaResources.zookeeperJmxSecretName(reconciliation.name()))
                .compose(currentJmxSecret -> {
                    Secret desiredJmxSecret = zk.generateJmxSecret(currentJmxSecret);

                    if (desiredJmxSecret != null)  {
                        // Desired secret is not null => should be updated
                        return secretOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperJmxSecretName(reconciliation.name()), desiredJmxSecret)
                                .map((Void) null);
                    } else if (currentJmxSecret != null)    {
                        // Desired secret is null but current is not => we should delete the secret
                        return secretOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperJmxSecretName(reconciliation.name()), null)
                                .map((Void) null);
                    } else {
                        // Both current and desired secret are null => nothing to do
                        return Future.succeededFuture();
                    }

                });
    }

    /**
     * Will check all Zookeeper pods whether the user requested the pod and PVC deletion through an annotation
     *
     * @return  Completes when the manual pod cleaning is done
     */
    protected Future<Void> manualPodCleaning() {
        return new ManualPodCleaner(
                reconciliation,
                KafkaResources.zookeeperStatefulSetName(reconciliation.name()),
                zk.getSelectorLabels(),
                operationTimeoutMs,
                featureGates.useStrimziPodSetsEnabled(),
                stsOperator,
                strimziPodSetOperator,
                podOperator,
                pvcOperator
        ).maybeManualPodCleaning(zk.generatePersistentVolumeClaims());
    }

    /**
     * Manages the network policy protecting the ZooKeeper cluster
     *
     * @return  Completes when the network policy is successfully created or updated
     */
    protected Future<Void> networkPolicy() {
        if (isNetworkPolicyGeneration) {
            return networkPolicyOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperNetworkPolicyName(reconciliation.name()), zk.generateNetworkPolicy(operatorNamespace, operatorNamespaceLabels))
                    .map((Void) null);
        } else {
            return Future.succeededFuture();
        }
    }

    /**
     * Does manual rolling update of Zoo pods based on an annotation on the StatefulSet or on the Pods. Annotation
     * on StatefulSet level triggers rolling update of all pods. Annotation on pods triggers rolling update only of
     * the selected pods. If the annotation is present on both StatefulSet and one or more pods, only one rolling
     * update of all pods occurs.
     *
     * @return  Future with the result of the rolling update
     */
    protected Future<Void> manualRollingUpdate() {
        Future<HasMetadata> futureController;
        if (featureGates.useStrimziPodSetsEnabled())   {
            futureController = strimziPodSetOperator.getAsync(reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()))
                    .map(podSet -> podSet); // The .map(...) is required to convert to HasMetadata
        } else {
            futureController = stsOperator.getAsync(reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()))
                    .map(sts -> sts); // The .map(...) is required to convert to HasMetadata
        }

        return futureController.compose(controller -> {
            if (controller != null
                    && Annotations.booleanAnnotation(controller, Annotations.ANNO_STRIMZI_IO_MANUAL_ROLLING_UPDATE, false)) {
                // User trigger rolling update of the whole cluster
                return maybeRollZooKeeper(pod -> {
                    LOGGER.debugCr(reconciliation, "Rolling Zookeeper pod {} due to manual rolling update", pod.getMetadata().getName());
                    return singletonList("manual rolling update");
                });
            } else {
                // The controller does not exist or is not annotated
                // But maybe the individual pods are annotated to restart only some of them.
                return manualPodRollingUpdate();
            }
        });
    }

    /**
     * Does rolling update of Zoo pods based on the annotation on Pod level
     *
     * @return  Future with the result of the rolling update
     */
    private Future<Void> manualPodRollingUpdate() {
        return podOperator.listAsync(reconciliation.namespace(), zk.getSelectorLabels())
                .compose(pods -> {
                    List<String> podsToRoll = new ArrayList<>(0);

                    for (Pod pod : pods)    {
                        if (Annotations.booleanAnnotation(pod, Annotations.ANNO_STRIMZI_IO_MANUAL_ROLLING_UPDATE, false)) {
                            podsToRoll.add(pod.getMetadata().getName());
                        }
                    }

                    if (!podsToRoll.isEmpty())  {
                        return maybeRollZooKeeper(pod -> {
                            if (pod != null && podsToRoll.contains(pod.getMetadata().getName())) {
                                LOGGER.debugCr(reconciliation, "Rolling ZooKeeper pod {} due to manual rolling update annotation on a pod", pod.getMetadata().getName());
                                return singletonList("manual rolling update annotation on a pod");
                            } else {
                                return null;
                            }
                        });
                    } else {
                        return Future.succeededFuture();
                    }
                });
    }

    /**
     * Logs any changes to the ZooKeeper version which will be done during the reconciliation. This method only logs
     * them, it doesn't actually change the version.
     *
     * @return  Completes when the upgrade / downgrade information is logged
     */
    private Future<Void> logVersionChange() {
        if (versionChange.isNoop()) {
            LOGGER.debugCr(reconciliation, "Kafka.spec.kafka.version is unchanged therefore no change to Zookeeper is required");
        } else {
            String versionChangeType;

            if (versionChange.isDowngrade()) {
                versionChangeType = "downgrade";
            } else {
                versionChangeType = "upgrade";
            }

            if (versionChange.requiresZookeeperChange()) {
                LOGGER.infoCr(reconciliation, "Kafka {} from {} to {} requires Zookeeper {} from {} to {}",
                        versionChangeType,
                        versionChange.from().version(),
                        versionChange.to().version(),
                        versionChangeType,
                        versionChange.from().zookeeperVersion(),
                        versionChange.to().zookeeperVersion());
            } else {
                LOGGER.infoCr(reconciliation, "Kafka {} from {} to {} requires no change in Zookeeper version",
                        versionChangeType,
                        versionChange.from().version(),
                        versionChange.to().version());

            }
        }

        return Future.succeededFuture();
    }

    /**
     * Manages the ZooKeeper service account
     *
     * @return  Completes when the service account was successfully created or updated
     */
    protected Future<Void> serviceAccount() {
        return serviceAccountOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()), zk.generateServiceAccount())
                .map((Void) null);
    }

    /**
     * Manages the PVCs needed by the ZooKeeper cluster. This method only creates or updates the PVCs. Deletion of PVCs
     * after scale-down happens only at the end of the reconciliation when they are not used anymore.
     *
     * @return  Completes when the PVCs were successfully created or updated
     */
    protected Future<Void> pvcs() {
        List<PersistentVolumeClaim> pvcs = zk.generatePersistentVolumeClaims();

        return new PvcReconciler(reconciliation, pvcOperator, storageClassOperator)
                .resizeAndReconcilePvcs(podIndex -> KafkaResources.zookeeperPodName(reconciliation.name(), podIndex), pvcs)
                .compose(podsToRestart -> {
                    fsResizingRestartRequest.addAll(podsToRestart);
                    return Future.succeededFuture();
                });
    }

    /**
     * Manages the regular CLusterIP service used by ZooKeeper clients
     *
     * @return  Completes when the service was successfully created or updated
     */
    protected Future<Void> service() {
        return serviceOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperServiceName(reconciliation.name()), zk.generateService())
                .map((Void) null);
    }

    /**
     * Manages the headless service
     *
     * @return  Completes when the service was successfully created or updated
     */
    protected Future<Void> headlessService() {
        return serviceOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperHeadlessServiceName(reconciliation.name()), zk.generateHeadlessService())
                .map((Void) null);
    }

    /**
     * Manages the Secret with the node certificates used by the ZooKeeper nodes.
     *
     * @param dateSupplier  Date supplier for checking the maintenance windows
     *
     * @return  Completes when the Secret was successfully created or updated
     */
    protected Future<Void> certificateSecret(Supplier<Date> dateSupplier) {
        return secretOperator.getAsync(reconciliation.namespace(), KafkaResources.zookeeperSecretName(reconciliation.name()))
                .compose(oldSecret -> {
                    return secretOperator
                            .reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperSecretName(reconciliation.name()),
                                    zk.generateCertificatesSecret(clusterCa, Util.isMaintenanceTimeWindowsSatisfied(reconciliation, maintenanceWindows, dateSupplier)))
                            .compose(patchResult -> {
                                if (patchResult instanceof ReconcileResult.Patched) {
                                    // The secret is patched and some changes to the existing certificates actually occurred
                                    existingCertsChanged = ModelUtils.doExistingCertificatesDiffer(oldSecret, patchResult.resource());
                                } else {
                                    existingCertsChanged = false;
                                }

                                return Future.succeededFuture();
                            });
                });
    }

    /**
     * Manages the ConfigMap with logging and metrics configuration.
     *
     * @return  Completes when the ConfigMap was successfully created or updated
     */
    protected Future<Void> loggingAndMetricsConfigMap() {
        return Util.metricsAndLogging(reconciliation, configMapOperator, reconciliation.namespace(), zk.getLogging(), zk.getMetricsConfigInCm())
                .compose(metricsAndLogging -> {
                    ConfigMap logAndMetricsConfigMap = zk.generateConfigurationConfigMap(metricsAndLogging);

                    loggingHash = Util.hashStub(logAndMetricsConfigMap.getData().get(zk.getAncillaryConfigMapKeyLogConfig()));

                    return configMapOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperMetricsAndLogConfigMapName(reconciliation.name()), logAndMetricsConfigMap)
                            .map((Void) null);
                });
    }

    /**
     * Manages the PodDisruptionBudgets on Kubernetes clusters which support v1 version of PDBs
     *
     * @return  Completes when the PDB was successfully created or updated
     */
    protected Future<Void> podDisruptionBudget() {
        if (!pfa.hasPodDisruptionBudgetV1()) {
            return Future.succeededFuture();
        } else {
            PodDisruptionBudget pdb;

            if (featureGates.useStrimziPodSetsEnabled()) {
                pdb = zk.generateCustomControllerPodDisruptionBudget();
            } else {
                pdb = zk.generatePodDisruptionBudget();
            }

            return podDisruptionBudgetOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()), pdb)
                    .map((Void) null);
        }
    }

    /**
     * Manages the PodDisruptionBudgets on Kubernetes clusters which support only v1beta1 version of PDBs
     *
     * @return  Completes when the PDB was successfully created or updated
     */
    protected Future<Void> podDisruptionBudgetV1Beta1() {
        if (pfa.hasPodDisruptionBudgetV1()) {
            return Future.succeededFuture();
        } else {
            io.fabric8.kubernetes.api.model.policy.v1beta1.PodDisruptionBudget pdb;

            if (featureGates.useStrimziPodSetsEnabled()) {
                pdb = zk.generateCustomControllerPodDisruptionBudgetV1Beta1();
            } else {
                pdb = zk.generatePodDisruptionBudgetV1Beta1();
            }

            return podDisruptionBudgetV1Beta1Operator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()), pdb)
                    .map((Void) null);
        }
    }

    /**
     * Create or update the StatefulSet for the ZooKeeper cluster. When StatefulSets are disabled, it will try to delete
     * the old StatefulSet.
     *
     * @return  Future which completes when the StatefulSet is created, updated or deleted
     */
    protected Future<Void> statefulSet() {
        if (featureGates.useStrimziPodSetsEnabled())   {
            // StatefulSets are disabled => delete the StatefulSet if it exists
            return stsOperator.getAsync(reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()))
                    .compose(sts -> {
                        if (sts != null)    {
                            return stsOperator.deleteAsync(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()), false);
                        } else {
                            return Future.succeededFuture();
                        }
                    });
        } else {
            // StatefulSets are enabled => make sure the StatefulSet exists with the right settings
            StatefulSet zkSts = zk.generateStatefulSet(pfa.isOpenshift(), imagePullPolicy, imagePullSecrets);
            Annotations.annotations(zkSts.getSpec().getTemplate()).put(Ca.ANNO_STRIMZI_IO_CLUSTER_CA_CERT_GENERATION, String.valueOf(ModelUtils.caCertGeneration(this.clusterCa)));
            Annotations.annotations(zkSts.getSpec().getTemplate()).put(Annotations.ANNO_STRIMZI_LOGGING_HASH, loggingHash);
            return stsOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()), zkSts)
                    .compose(rr -> {
                        statefulSetDiff = rr;
                        return Future.succeededFuture();
                    });
        }
    }

    /**
     * Create or update the StrimziPodSet for the ZooKeeper cluster with the default number of pods. When PodSets are
     * disabled, it will try to delete the old PodSet. That means either the number of pods the pod set had before or
     * the number of pods based on the Kafka CR if this is a new cluster. Scale-up and scale-down are down separately.
     *
     * @return  Future which completes when the PodSet is created, updated or deleted
     */
    protected Future<Void> podSet() {
        return podSet(currentReplicas > 0 ? currentReplicas : zk.getReplicas());
    }

    /**
     * Create the StrimziPodSet for the ZooKeeper cluster with a specific number of pods. This is used directly
     * during scale-ups or scale-downs.
     *
     * @param replicas  Number of replicas which the PodSet should use
     *
     * @return          Future which completes when the PodSet is created or updated
     */
    private Future<Void> podSet(int replicas) {
        if (featureGates.useStrimziPodSetsEnabled())   {
            Map<String, String> podAnnotations = new LinkedHashMap<>(2);
            podAnnotations.put(Ca.ANNO_STRIMZI_IO_CLUSTER_CA_CERT_GENERATION, String.valueOf(ModelUtils.caCertGeneration(this.clusterCa)));
            podAnnotations.put(Annotations.ANNO_STRIMZI_LOGGING_HASH, loggingHash);

            StrimziPodSet zkPodSet = zk.generatePodSet(replicas, pfa.isOpenshift(), imagePullPolicy, imagePullSecrets, podAnnotations);
            return strimziPodSetOperator.reconcile(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()), zkPodSet)
                    .compose(rr -> {
                        podSetDiff = rr;
                        return Future.succeededFuture();
                    });
        } else {
            return strimziPodSetOperator.getAsync(reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()))
                    .compose(podSet -> {
                        if (podSet != null)    {
                            return strimziPodSetOperator.deleteAsync(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()), false);
                        } else {
                            return Future.succeededFuture();
                        }
                    });
        }
    }

    /**
     * Prepares the Zookeeper connectionString
     * The format is host1:port1,host2:port2,...
     *
     * Used by the Zookeeper Admin client for scaling.
     *
     * @param connectToReplicas     Number of replicas from the ZK STS which should be used
     *
     * @return                      The generated Zookeeper connection string
     */
    private String zkConnectionString(int connectToReplicas, Function<Integer, String> zkNodeAddress)  {
        // Prepare Zoo connection string. We want to connect only to nodes which existed before
        // scaling and will exist after it is finished
        List<String> zooNodes = new ArrayList<>(connectToReplicas);

        for (int i = 0; i < connectToReplicas; i++)   {
            zooNodes.add(String.format("%s:%d", zkNodeAddress.apply(i), ZookeeperCluster.CLIENT_TLS_PORT));
        }

        return  String.join(",", zooNodes);
    }

    /**
     * Helper method for getting the required secrets with certificates and creating the ZookeeperScaler instance
     * for the given cluster. The ZookeeperScaler instance created by this method should be closed manually after
     * it is not used anymore.
     *
     * @param connectToReplicas     Number of pods from the Zookeeper STS which the scaler should use
     *
     * @return                      Zookeeper scaler instance.
     */
    private Future<ZookeeperScaler> zkScaler(int connectToReplicas)  {
        return ReconcilerUtils.clientSecrets(reconciliation, secretOperator)
                .compose(compositeFuture -> {
                    Secret clusterCaCertSecret = compositeFuture.resultAt(0);
                    Secret coKeySecret = compositeFuture.resultAt(1);

                    Function<Integer, String> zkNodeAddress = (Integer i) ->
                            DnsNameGenerator.podDnsNameWithoutClusterDomain(reconciliation.namespace(), KafkaResources.zookeeperHeadlessServiceName(reconciliation.name()), KafkaResources.zookeeperPodName(reconciliation.name(), i));

                    ZookeeperScaler zkScaler = zooScalerProvider
                            .createZookeeperScaler(
                                    reconciliation,
                                    vertx,
                                    zkConnectionString(connectToReplicas, zkNodeAddress),
                                    zkNodeAddress,
                                    clusterCaCertSecret,
                                    coKeySecret,
                                    operationTimeoutMs,
                                    adminSessionTimeoutMs
                            );

                    return Future.succeededFuture(zkScaler);
                });
    }

    /**
     * General method which orchestrates ZooKeeper scale-down from N to M pods. This relies on other methods which scale
     * the pods one by one.
     *
     * @return  Future which completes ZooKeeper scale-down is complete
     */
    protected Future<Void> scaleDown() {
        int desired = zk.getReplicas();

        if (currentReplicas > desired) {
            // With scaling
            LOGGER.infoCr(reconciliation, "Scaling Zookeeper down from {} to {} replicas", currentReplicas, desired);

            // No need to check for pod readiness since we run right after the readiness check
            return zkScaler(desired)
                    .compose(zkScaler -> {
                        Promise<Void> scalingPromise = Promise.promise();

                        scaleDownByOne(zkScaler, currentReplicas, desired)
                                .onComplete(res -> {
                                    zkScaler.close();

                                    if (res.succeeded())    {
                                        scalingPromise.complete(res.result());
                                    } else {
                                        LOGGER.warnCr(reconciliation, "Failed to scale Zookeeper", res.cause());
                                        scalingPromise.fail(res.cause());
                                    }
                                });

                        return scalingPromise.future();
                    });
        } else {
            // No scaling down => do nothing
            return Future.succeededFuture();
        }
    }

    /**
     * Scales-down ZooKeeper by one node. To not break the quorum when scaling down, we always remove the pod from the
     * quorum and only then remove the Pod.
     *
     * @return  Future which completes new pod is removed
     */
    private Future<Void> scaleDownByOne(ZookeeperScaler zkScaler, int current, int desired) {
        if (current > desired) {
            return ReconcilerUtils
                    .podsReady(
                            reconciliation,
                            podOperator,
                            operationTimeoutMs,
                            IntStream.rangeClosed(0, current - 1).mapToObj(i -> KafkaResources.zookeeperPodName(reconciliation.name(), i)).collect(Collectors.toList())
                    )
                    .compose(i -> zkScaler.scale(current - 1))
                    .compose(i -> scaleDownStatefulSetOrPodSet(current - 1))
                    .compose(i -> scaleDownByOne(zkScaler, current - 1, desired));
        } else {
            return Future.succeededFuture();
        }
    }

    /**
     * Scales-down the ZooKeeper StatefulSet or PodSet, depending on what is used. This method only updates the
     * StatefulSet or PodSet, it does not handle the pods or ZooKeeper configuration.
     *
     * @return  Future which completes when StatefulSet or PodSet are scaled-down.
     */
    private Future<Void> scaleDownStatefulSetOrPodSet(int desiredScale)   {
        if (featureGates.useStrimziPodSetsEnabled())   {
            return podSet(desiredScale)
                    // We wait for the pod to be deleted, otherwise it might disrupt the rolling update
                    .compose(ignore -> podOperator.waitFor(
                            reconciliation,
                            reconciliation.namespace(),
                            KafkaResources.zookeeperPodName(reconciliation.name(), desiredScale),
                            "to be deleted",
                            1_000L,
                            operationTimeoutMs,
                            (podNamespace, podName) -> podOperator.get(podNamespace, podName) == null)
                    );
        } else {
            return stsOperator.scaleDown(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()), desiredScale)
                    .map((Void) null);
        }
    }

    /**
     * General method for rolling update of the ZooKeeper cluster. This method handles the whether StatefulSets or
     * PodSets are being used and calls other methods to execute the rolling update if needed.
     *
     * @return  Future which completes when any of the ZooKeeper pods which need rolling is rolled
     */
    protected Future<Void> rollingUpdate() {
        if (featureGates.useStrimziPodSetsEnabled())   {
            return maybeRollZooKeeper(pod -> ReconcilerUtils.reasonsToRestartPod(reconciliation, podSetDiff.resource(), pod, fsResizingRestartRequest, existingCertsChanged, clusterCa));
        } else {
            return maybeRollZooKeeper(pod -> ReconcilerUtils.reasonsToRestartPod(reconciliation, statefulSetDiff.resource(), pod, fsResizingRestartRequest, existingCertsChanged, clusterCa));
        }
    }

    /**
     * Checks if the ZooKeeper cluster needs rolling and if it does, it will roll it.
     *
     * @param podNeedsRestart   Function to determine if the ZooKeeper pod needs to be restarted
     *
     * @return                  Future which completes when any of the ZooKeeper pods which need rolling is rolled
     */
    /* test */ Future<Void> maybeRollZooKeeper(Function<Pod, List<String>> podNeedsRestart) {
        return ReconcilerUtils.clientSecrets(reconciliation, secretOperator)
                .compose(compositeFuture -> {
                    Secret clusterCaCertSecret = compositeFuture.resultAt(0);
                    Secret coKeySecret = compositeFuture.resultAt(1);

                    return maybeRollZooKeeper(podNeedsRestart, clusterCaCertSecret, coKeySecret);
                });
    }

    /**
     * Checks if the ZooKeeper cluster needs rolling and if it does, it will roll it.
     *
     * @param podNeedsRestart       Function to determine if the ZooKeeper pod needs to be restarted
     * @param clusterCaCertSecret   Secret with the Cluster CA certificates
     * @param coKeySecret           Secret with the Cluster Operator certificates
     *
     * @return                      Future which completes when any of the ZooKeeper pods which need rolling is rolled
     */
    private Future<Void> maybeRollZooKeeper(Function<Pod, List<String>> podNeedsRestart, Secret clusterCaCertSecret, Secret coKeySecret) {
        return new ZooKeeperRoller(podOperator, zooLeaderFinder, operationTimeoutMs)
                .maybeRollingUpdate(reconciliation, zk.getSelectorLabels(), podNeedsRestart, clusterCaCertSecret, coKeySecret);
    }

    /**
     * Checks whether the ZooKeeper pods are ready and if not, waits for them to get ready
     *
     * @return  Future which completes when all ZooKeeper pods are ready
     */
    protected Future<Void> podsReady() {
        return ReconcilerUtils
                .podsReady(
                        reconciliation,
                        podOperator,
                        operationTimeoutMs,
                        IntStream
                                .range(0, currentReplicas > 0 && currentReplicas < zk.getReplicas() ? currentReplicas : zk.getReplicas())
                                .mapToObj(i -> KafkaResources.zookeeperPodName(reconciliation.name(), i))
                                .collect(Collectors.toList())
                );
    }

    /**
     * General method which orchestrates ZooKeeper scale-up from N to M pods. This relies on other methods which scale
     * the pods one by one.
     *
     * @return  Future which completes ZooKeeper scale-up is complete
     */
    protected Future<Void> scaleUp() {
        int desired = zk.getReplicas();

        if (currentReplicas > 0 && currentReplicas < desired) {
            LOGGER.infoCr(reconciliation, "Scaling Zookeeper up from {} to {} replicas", currentReplicas, desired);

            return zkScaler(currentReplicas)
                    .compose(zkScaler -> {
                        Promise<Void> scalingPromise = Promise.promise();

                        scaleUpByOne(zkScaler, currentReplicas, desired)
                                .onComplete(res -> {
                                    zkScaler.close();

                                    if (res.succeeded())    {
                                        scalingPromise.complete();
                                    } else {
                                        LOGGER.warnCr(reconciliation, "Failed to scale Zookeeper", res.cause());
                                        scalingPromise.fail(res.cause());
                                    }
                                });

                        return scalingPromise.future();
                    });
        } else {
            // No scaling up => do nothing
            return Future.succeededFuture();
        }
    }

    /**
     * Scales-up ZooKeeper by one node. To not break the quorum when scaling up, we always add only one new pod at once,
     * wait for it to get ready and reconfigure the ZooKeeper quorum to include this pod.
     *
     * @return  Future which completes new pod is created and added to the quorum
     */
    private Future<Void> scaleUpByOne(ZookeeperScaler zkScaler, int current, int desired) {
        if (current < desired) {
            return zkScaleUpStatefulSetOrPodSet(current + 1)
                    .compose(ignore -> podOperator.readiness(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperPodName(reconciliation.name(), current), 1_000, operationTimeoutMs))
                    .compose(ignore -> zkScaler.scale(current + 1))
                    .compose(ignore -> scaleUpByOne(zkScaler, current + 1, desired));
        } else {
            return Future.succeededFuture();
        }
    }

    /**
     * Scales-up the ZooKeeper StatefulSet or PodSet, depending on what is used. This method only updates the
     * StatefulSet or PodSet, it does not handle the pods or ZooKeeper configuration.
     *
     * @return  Future which completes when StatefulSet or PodSet are scaled-up.
     */
    private Future<Void> zkScaleUpStatefulSetOrPodSet(int desiredScale)   {
        if (featureGates.useStrimziPodSetsEnabled())   {
            return podSet(desiredScale);
        } else {
            return stsOperator.scaleUp(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperStatefulSetName(reconciliation.name()), desiredScale)
                    .map((Void) null);
        }
    }

    /**
     * Checks that the ZooKeeper cluster is configured for the correct number of nodes. This method is used to recover
     * from any scaling which previously failed (e.g. added a new ZooKeeper pod but didn't manage to reconfigure the
     * quorum configuration). It also serves as a good test if the ZooKeeper cluster formed or not.
     *
     * @return  Future which completes when the ZooKeeper quorum is configured for the current number of nodes
     */
    protected Future<Void> scalingCheck() {
        // No scaling, but we should check the configuration
        // This can cover any previous failures in the Zookeeper reconfiguration
        LOGGER.debugCr(reconciliation, "Verifying that Zookeeper is configured to run with {} replicas", zk.getReplicas());

        // No need to check for pod readiness since we run right after the readiness check
        return zkScaler(zk.getReplicas())
                .compose(zkScaler -> {
                    Promise<Void> scalingPromise = Promise.promise();

                    zkScaler.scale(zk.getReplicas()).onComplete(res -> {
                        zkScaler.close();

                        if (res.succeeded())    {
                            scalingPromise.complete();
                        } else {
                            LOGGER.warnCr(reconciliation, "Failed to verify Zookeeper configuration", res.cause());
                            scalingPromise.fail(res.cause());
                        }
                    });

                    return scalingPromise.future();
                });
    }

    /**
     * Waits for readiness of the endpoints of the clients service
     *
     * @return  Future which completes when the endpoints are ready
     */
    protected Future<Void> serviceEndpointsReady() {
        return serviceOperator.endpointReadiness(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperServiceName(reconciliation.name()), 1_000, operationTimeoutMs);
    }

    /**
     * Waits for readiness of the endpoints of the headless service
     *
     * @return  Future which completes when the endpoints are ready
     */
    protected Future<Void> headlessServiceEndpointsReady() {
        return serviceOperator.endpointReadiness(reconciliation, reconciliation.namespace(), KafkaResources.zookeeperHeadlessServiceName(reconciliation.name()), 1_000, operationTimeoutMs);
    }

    /**
     * Deletion of PVCs after the cluster is deleted is handled by owner reference and garbage collection. However,
     * this would not help after scale-downs. Therefore, we check if there are any PVCs which should not be present
     * and delete them when they are.
     *
     * This should be called only after the StatefulSet reconciliation, rolling update and scale-down when the PVCs
     * are not used any more by the pods.
     *
     * @return  Future which completes when the PVCs which should be deleted are deleted
     */
    protected Future<Void> deletePersistentClaims() {
        return pvcOperator.listAsync(reconciliation.namespace(), zk.getSelectorLabels())
                .compose(pvcs -> {
                    List<String> maybeDeletePvcs = pvcs.stream().map(pvc -> pvc.getMetadata().getName()).collect(Collectors.toList());
                    List<String> desiredPvcs = zk.generatePersistentVolumeClaims().stream().map(pvc -> pvc.getMetadata().getName()).collect(Collectors.toList());

                    return new PvcReconciler(reconciliation, pvcOperator, storageClassOperator)
                            .deletePersistentClaims(maybeDeletePvcs, desiredPvcs);
                });
    }
}


text:
import json
import unittest

import mock

from google.appengine.api import urlfetch

from dashboard.services import gitiles_service

@mock.patch('google.appengine.api.urlfetch.fetch')
class GitilesTest(unittest.TestCase):

  def testCommitInfo(self, mock_fetch):
    return_value = {
        'commit': 'commit_hash',
        'tree': 'tree_hash',
        'parents': ['parent_hash'],
        'author': {
            'name': 'username',
            'email': 'email@chromium.org',
            'time': 'Fri Jan 01 00:00:00 2016',
        },
        'committer': {
            'name': 'Commit bot',
            'email': 'commit-bot@chromium.org',
            'time': 'Fri Jan 01 00:01:00 2016',
        },
        'message': 'Subject.\n\nCommit message.',
        'tree_diff': [
            {
                'type': 'modify',
                'old_id': 'old_hash',
                'old_mode': 33188,
                'old_path': 'a/b/c.py',
                'new_id': 'new_hash',
                'new_mode': 33188,
                'new_path': 'a/b/c.py',
            },
        ],
    }
    _SetFetchReturnValues(mock_fetch, return_value)
    self.assertEqual(
        gitiles_service.CommitInfo('https://chromium.googlesource.com/repo',
                                   'commit_hash'),
        return_value)
    mock_fetch.assert_called_once_with(
        'https://chromium.googlesource.com/repo/+/commit_hash?format=JSON')

  def testCommitRange(self, mock_fetch):
    return_value = {
        'log': [
            {
                'commit': 'commit_2_hash',
                'tree': 'tree_2_hash',
                'parents': ['parent_2_hash'],
                'author': {
                    'name': 'username',
                    'email': 'email@chromium.org',
                    'time': 'Sat Jan 02 00:00:00 2016',
                },
                'committer': {
                    'name': 'Commit bot',
                    'email': 'commit-bot@chromium.org',
                    'time': 'Sat Jan 02 00:01:00 2016',
                },
                'message': 'Subject.\n\nCommit message.',
            },
            {
                'commit': 'commit_1_hash',
                'tree': 'tree_1_hash',
                'parents': ['parent_1_hash'],
                'author': {
                    'name': 'username',
                    'email': 'email@chromium.org',
                    'time': 'Fri Jan 01 00:00:00 2016',
                },
                'committer': {
                    'name': 'Commit bot',
                    'email': 'commit-bot@chromium.org',
                    'time': 'Fri Jan 01 00:01:00 2016',
                },
                'message': 'Subject.\n\nCommit message.',
            },
        ],
    }
    _SetFetchReturnValues(mock_fetch, return_value)
    self.assertEqual(
        gitiles_service.CommitRange('https://chromium.googlesource.com/repo',
                                    'commit_0_hash', 'commit_2_hash'),
        return_value['log'])
    mock_fetch.assert_called_once_with(
        'https://chromium.googlesource.com/repo/+log/'
        'commit_0_hash..commit_2_hash?format=JSON')

  def testCommitRangePaginated(self, mock_fetch):
    return_value_1 = {
        'log': [
            {'commit': 'commit_4_hash'},
            {'commit': 'commit_3_hash'},
        ],
        'next': 'commit_2_hash',
    }
    return_value_2 = {
        'log': [
            {'commit': 'commit_2_hash'},
            {'commit': 'commit_1_hash'},
        ],
    }

    _SetFetchReturnValues(mock_fetch, return_value_1, return_value_2)

    self.assertEqual(
        gitiles_service.CommitRange('https://chromium.googlesource.com/repo',
                                    'commit_0_hash', 'commit_4_hash'),
        return_value_1['log'] + return_value_2['log'])

  def testFileContents(self, mock_fetch):
    mock_fetch.return_value = mock.MagicMock(
        content='aGVsbG8=', status_code=200)
    self.assertEqual(
        gitiles_service.FileContents('https://chromium.googlesource.com/repo',
                                     'commit_hash', 'path'),
        'hello')
    mock_fetch.assert_called_once_with(
        'https://chromium.googlesource.com/repo/+/commit_hash/path?format=TEXT')

  def testRetries(self, mock_fetch):
    mock_fetch.side_effect = urlfetch.Error()
    with self.assertRaises(urlfetch.Error):
      gitiles_service.FileContents('https://chromium.googlesource.com/repo',
                                   'commit_hash', 'path')

    mock_fetch.side_effect = urlfetch.Error(), mock.MagicMock(
        content='aGVsbG8=', status_code=200)
    self.assertEqual(
        gitiles_service.FileContents('https://chromium.googlesource.com/repo',
                                     'commit_hash', 'path'),
        'hello')

    mock_fetch.side_effect = Exception(), mock.MagicMock(
        content='aGVsbG8=', status_code=200)
    with self.assertRaises(Exception):
      gitiles_service.FileContents('https://chromium.googlesource.com/repo',
                                   'commit_hash', 'path')

  def testNotFound(self, mock_fetch):
    mock_fetch.side_effect = gitiles_service.NotFoundError()
    with self.assertRaises(gitiles_service.NotFoundError):
      gitiles_service.FileContents('https://chromium.googlesource.com/repo',
                                   'commit_hash', 'path')

def _SetFetchReturnValues(mock_fetch, *return_values):
  mock_fetch.side_effect = tuple(
      _MockifyReturnValue(return_value) for return_value in return_values)

def _MockifyReturnValue(return_value):
  return mock.MagicMock(content=")]}'\n" + json.dumps(return_value),
                        status_code=200)


text:
package org.apache.camel.opentracing.decorators;

public class CometdsSpanDecorator extends CometdSpanDecorator {

    @Override
    public String getComponent() {
        return "cometds";
    }

}


text:
@interface BZObjectStoreClazzNSDecimalNumber : BZObjectStoreClazz

@end


text:
<?php

/**
 * Wee tax resource model
 *
 * @category    Mage
 * @package     Mage_Weee
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Weee_Model_Resource_Tax extends Mage_Core_Model_Resource_Db_Abstract
{
    /**
     * Resource initialization
     *
     */
    protected function _construct()
    {
        $this->_init('weee/tax', 'value_id');
    }

    /**
     * Fetch one
     *
     * @param Varien_Db_Select|string $select
     * @return string
     */
    public function fetchOne($select)
    {
        return $this->_getReadAdapter()->fetchOne($select);
    }

    /**
     * Fetch column
     *
     * @param Varien_Db_Select|string $select
     * @return array
     */
    public function fetchCol($select)
    {
        return $this->_getReadAdapter()->fetchCol($select);
    }

    /**
     * Update discount percents
     *
     * @return Mage_Weee_Model_Resource_Tax
     */
    public function updateDiscountPercents()
    {
        return $this->_updateDiscountPercents();
    }

    /**
     * Update products discount persent
     *
     * @param mixed $condition
     * @return Mage_Weee_Model_Resource_Tax
     */
    public function updateProductsDiscountPercent($condition)
    {
        return $this->_updateDiscountPercents($condition);
    }

    /**
     * Update tax percents for WEEE based on products condition
     *
     * @param mixed $productCondition
     * @return Mage_Weee_Model_Resource_Tax
     */
    protected function _updateDiscountPercents($productCondition = null)
    {
        $now     = Varien_Date::toTimestamp(Varien_Date::now());
        $adapter = $this->_getWriteAdapter();

        $select  = $this->_getReadAdapter()->select();
        $select->from(array('data' => $this->getTable('catalogrule/rule_product')));

        $deleteCondition = '';
        if ($productCondition) {
            if ($productCondition instanceof Mage_Catalog_Model_Product) {
                $select->where('product_id = ?', (int)$productCondition->getId());
                $deleteCondition = $adapter->quoteInto('entity_id=?', (int)$productCondition->getId());
            } elseif ($productCondition instanceof Mage_Catalog_Model_Product_Condition_Interface) {
                $productCondition = $productCondition->getIdsSelect($adapter)->__toString();
                $select->where("product_id IN ({$productCondition})");
                $deleteCondition = "entity_id IN ({$productCondition})";
            } else {
                $select->where('product_id = ?', (int)$productCondition);
                $deleteCondition = $adapter->quoteInto('entity_id = ?', (int)$productCondition);
            }
        } else {
            $select->where('(from_time <= ? OR from_time = 0)', $now)
                   ->where('(to_time >= ? OR to_time = 0)', $now);
        }
        $adapter->delete($this->getTable('weee/discount'), $deleteCondition);

        $select->order(array('data.website_id', 'data.customer_group_id', 'data.product_id', 'data.sort_order'));

        $data = $this->_getReadAdapter()->query($select);

        $productData = array();
        $stops       = array();
        $prevKey     = false;
        while ($row = $data->fetch()) {
            $key = "{$row['product_id']}-{$row['website_id']}-{$row['customer_group_id']}";
            if (isset($stops[$key]) && $stops[$key]) {
                continue;
            }

            if ($prevKey && ($prevKey != $key)) {
                foreach ($productData as $product) {
                    $adapter->insert($this->getTable('weee/discount'), $product);
                }
                $productData = array();
            }
            if ($row['action_operator'] == 'by_percent') {
                if (isset($productData[$key])) {
                    $productData[$key]['value'] -= $productData[$key]['value']/100*$row['action_amount'];
                } else {
                    $productData[$key] = array(
                        'entity_id'         => $row['product_id'],
                        'customer_group_id' => $row['customer_group_id'],
                        'website_id'        => $row['website_id'],
                        'value'             => 100-max(0, min(100, $row['action_amount'])),
                    );
                }
            }

            if ($row['action_stop']) {
                $stops[$key] = true;
            }
            $prevKey = $key;
        }
        foreach ($productData as $product) {
            $adapter->insert($this->getTable('weee/discount'), $product);
        }

        return $this;
    }

    /**
     * Retrieve product discount percent
     *
     * @param int $productId
     * @param int $websiteId
     * @param int $customerGroupId
     * @return string
     */
    public function getProductDiscountPercent($productId, $websiteId, $customerGroupId)
    {
        $select = $this->_getReadAdapter()->select();
        $select->from($this->getTable('weee/discount'), 'value')
            ->where('website_id = ?', (int)$websiteId)
            ->where('entity_id = ?', (int)$productId)
            ->where('customer_group_id = ?', (int)$customerGroupId);

        return $this->_getReadAdapter()->fetchOne($select);
    }
}


text:
title: Lecture 2
date: 06-1-2015
------------------------------------------

## Misc Notes
- Lab for next 2 weeks at 1PM

## Lecture Notes
- Range = Single number = difference between the largest and smallest values
- Standard error of the mean = $\frac{\sigma}{\sqrt{n}}$
- Standard error is a sample statistic
- Standard error of the mean, is the sampling error of the sample-mean statistics
You essentially use it as a measure of the deviance of the sample mean from the
true population mean

### Box Plot

- Box represents first and third quantile of the data
- A horizontal line inside the box marks the second quantile

## Quantiles and Quartiles
- Quartiles are numbers dividing the dataset into 4-equal sized datasets
- Quartile is a type of quantile.
- Quantile = Values taken at regular intervals from the inverse of a CDF. A q-quantile involves
dividing data into q-equal sized datasets.
- Only 1 2-quantile = median
- 3-quantiles =  tertiles
- 4-quantile= quartile
- Standardising: $X' = \frac{X-\mu}{\sigma}$
- More samples are good, but also need to consider cost etc

## Sampling from population
- Precision and accuracy of estimator depends on the sample size(makes sense)
-
## Sampling from population
- Precision and accuracy of estimator depends on the sample size(makes sense
## Sampling from population
- Precision and accuracy of estimator depends on the sample size(makes sense

## Power transformation
- $x' = x^p$ for $x'$ to be normally distributed
- Box-Cox transform is a method to determine optimal p

## CLT

- Means of samples from normally distributed samples are themselves normal(Proved too many times)

## CI

- CI: True value of a parameter lies within certain bounds
- $\alpha$: Priobability of rejecting null hypothesis where the null hypothesis implies no difference
when the null is true, thus making a wrong decision
- $1-\alpha$: Probabilty of rejecting the nul hypothesis when the null is true.

- Cases differ when the population variance aree knwn or unknown


text: Visual Studio Code


text:
function [distance, intersection] = DistanceEllipse(points, ellipse, plotme)
%DistanceEllipse  distance from points to ellipse.
%
% inputs
%   points   the polar coordinates of the poitns [x, y].
%   ellipse  ellipse parameters; [cx, cy, ax, ay, rx]
%   plotme   if true it plots the poitns and the ellipse.
%
% outputs
%   distance      the distance from the point to the ellipse.
%   intersection  the intersection points on ellipse surface.
%

if nargin < 3
  plotme = 0;
end

cx = ellipse(1);
cy = ellipse(2);
ax = ellipse(3);
ay = ellipse(4) + 1e-10; % to avoid division by 0
rx = ellipse(5);

[rows, ~] = size(points);

s = sin(rx);
c = cos(rx);
rot = [c, -s; s, c];
TransferedPoint = [points(:, 1) - cx, points(:, 2) - cy] * rot;

px = TransferedPoint(:, 1) + 1e-10; % to avoid division by 0
py = TransferedPoint(:, 2);

% calculate the intersection points on the surface
x1 = 1 ./ sqrt(1 ./ (ax .^ 2) + (py ./ px ./ ay) .^ 2);
x2 = -x1;
y1 = py ./ px .* x1;
y2 = -y1;

% calculating the distance to the point
d1 = sqrt((px - x1) .^ 2 + (py - y1) .^ 2);
d2 = sqrt((px - x2) .^ 2 + (py - y2) .^ 2);
distance = min(d1, d2);

% closest points in the ellipse
intersection = [x1, y1] .* [(d1 <= d2), (d1 <= d2)] + [x2, y2] .* [(d1 >= d2), (d1 >= d2)];

% transferring it back with the rotation and translation
% intersection = TransformPoint3(intersection, rot');
intersection = intersection * rot';
intersection = intersection + repmat([cx, cy], [rows, 1]);

if plotme
  figure;
  DrawEllipse(ellipse, 'color', 'g', 'linestyle', '-');
  hold on;

  % plotting the centre
  plot(cx, cy, '*m');

  % plotting the intesection point
  plot(intersection(:, 1), intersection(:, 2), '*r');

  % plotting all the original points
  plot(points(:, 1), points(:, 2), '*b');

  % plotting a line between the centre and the points
  for i = 1:rows
    plot([cx, points(i, 1)], [cy, points(i, 2)], 'black');
  end
  hold off;
end

end


text:
module TestApplicationHelper
  extend self

  class TestApplication
    def call(env)
      code   = 200
      body   = [ "test body" ]
      header = { "Content-Type"           => "text/html;charset=utf-8",
                 "Content-Length"         => "9",
                 "X-XSS-Protection"       => "1; mode=block",
                 "X-Content-Type-Options" => "nosniff",
                 "X-Frame-Options"        => "SAMEORIGIN" }
      [ code, header, body ]
    end
  end
end


text:
namespace elsa {
	namespace vm {
		class GC;

		class StackFrame {
			friend class GC;

		public:
			StackFrame(const FunctionInfo* function, std::size_t ret_addr, StackFrame* parent);
			~StackFrame();

			void push(Object o);
			Object pop();
			Object dump_top() const;
			bool has_stack_entries() const;
			Object load_local(std::size_t i) const;
			Object load_arg(std::size_t i) const;
			void store_local(std::size_t i, Object local);
			void store_arg(std::size_t i, Object arg);
			std::size_t get_ret_addr() const;
			StackFrame* get_parent() const;
			const FunctionInfo* get_function_info() const;

		private:
			std::vector<Object> eval_stack_;
			Object* locals_;
			std::size_t locals_size_;
			std::size_t ret_addr_;
			const FunctionInfo* function_;
			StackFrame* parent_;
		};

	}
}


text:
package com.jetbrains.python.spellchecker;

import com.intellij.spellchecker.BundledDictionaryProvider;

/**
 * @author yole
 */
public class PythonBundledDictionaryProvider implements BundledDictionaryProvider {
  @Override
  public String[] getBundledDictionaries() {
    return new String[] {
      "python.dic",        // autogenerated from python stdlib
      "pythonExtras.dic",  // manually added
      "django.dic"
    };
  }
}


text:
namespace base {
template <typename T>
struct DefaultSingletonTraits;
}

namespace content {
class BrowserContext;
}

namespace user_prefs {
class PrefRegistrySyncable;
}

class TriggeredProfileResetter;

class TriggeredProfileResetterFactory
    : public BrowserContextKeyedServiceFactory {
 public:
  static TriggeredProfileResetter* GetForBrowserContext(
      content::BrowserContext* context);
  static TriggeredProfileResetterFactory* GetInstance();

  TriggeredProfileResetterFactory(const TriggeredProfileResetterFactory&) =
      delete;
  TriggeredProfileResetterFactory& operator=(
      const TriggeredProfileResetterFactory&) = delete;

 private:
  friend struct base::DefaultSingletonTraits<TriggeredProfileResetterFactory>;
  friend class TriggeredProfileResetterTest;

  TriggeredProfileResetterFactory();
  ~TriggeredProfileResetterFactory() override;

  // BrowserContextKeyedServiceFactory:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;
  void RegisterProfilePrefs(
      user_prefs::PrefRegistrySyncable* registry) override;
  bool ServiceIsCreatedWithBrowserContext() const override;
};

#endif  // CHROME_BROWSER_PROFILE_RESETTER_TRIGGERED_PROFILE_RESETTER_FACTORY_H_


text:
<?php
	session_start();
	include('connect.php');

    //Destroys the session
    $_SESSION = array();
    session_unset();

    header('location: ../login.php');

?>