text:
using LinqInfer.Maths;
using LinqInfer.Maths.Graphs;

namespace LinqInfer.Learning.Classification.NeuralNetworks
{
    public interface INetworkClassifier<TClass, TInput> :
        IDynamicClassifier<TClass, TInput>,
        IHasNetworkTopology,
        IHasSerialisableTransformation
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Chapter 41. Boost.TypeErasure</title>
<link rel="stylesheet" href="../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="libraries.html" title="Part I. The Boost C++ Libraries (BoostBook Subset)">
<link rel="prev" href="thread/compliance.html" title="Conformance and Extension">
<link rel="next" href="boost_typeerasure/reading.html" title="How to read this documentation">

Home
Libraries
People
FAQ
More

Chapter 41. Boost.TypeErasure

Steven Watanabe

Copyright © 2011-2013 Steven Watanabe

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

Table of Contents

Introduction

How to read this documentation

Basic Usage

Composing Concepts

Functions with Multiple Arguments

Concepts in Depth

Defining Custom Concepts

Overloading

Concept Maps

Associated Types

Using Any

Construction

Conversions

References

Syntax Limitations

Examples

A polymorphic
      range formatter

A type-safe printf

Boost.Function
      with multiple signatures

Concept Definitions

Predefined Concepts

Reference

Header <boost/type_erasure/any.hpp>

Header <boost/type_erasure/any_cast.hpp>

Header <boost/type_erasure/binding.hpp>

Header <boost/type_erasure/binding_of.hpp>

Header <boost/type_erasure/builtin.hpp>

Header <boost/type_erasure/call.hpp>

Header <boost/type_erasure/callable.hpp>

Header <boost/type_erasure/check_match.hpp>

Header <boost/type_erasure/concept_interface.hpp>

Header <boost/type_erasure/concept_of.hpp>

Header <boost/type_erasure/config.hpp>

Header <boost/type_erasure/constructible.hpp>

Header <boost/type_erasure/deduced.hpp>

Header <boost/type_erasure/derived.hpp>

Header <boost/type_erasure/dynamic_any_cast.hpp>

Header <boost/type_erasure/dynamic_binding.hpp>

Header <boost/type_erasure/exception.hpp>

Header <boost/type_erasure/free.hpp>

Header <boost/type_erasure/is_empty.hpp>

Header <boost/type_erasure/is_placeholder.hpp>

Header <boost/type_erasure/is_subconcept.hpp>

Header <boost/type_erasure/iterator.hpp>

Header <boost/type_erasure/member.hpp>

Header <boost/type_erasure/operators.hpp>

Header <boost/type_erasure/param.hpp>

Header <boost/type_erasure/placeholder.hpp>

Header <boost/type_erasure/placeholder_of.hpp>

Header <boost/type_erasure/rebind_any.hpp>

Header <boost/type_erasure/register_binding.hpp>

Header <boost/type_erasure/relaxed.hpp>

Header <boost/type_erasure/require_match.hpp>

Header <boost/type_erasure/same_type.hpp>

Header <boost/type_erasure/static_binding.hpp>

Header <boost/type_erasure/tuple.hpp>

Header <boost/type_erasure/typeid_of.hpp>

Rationale

Why
      do I have to specify the presence of a destructor explicitly?

Why
      non-member functions?

Why are the
      placeholders called _a, _b and not _1
      _2

Why not use boost::ref
      for references?

Future Work

Acknowledgements

Related Work

Introduction

      The Boost.TypeErasure library provides runtime polymorphism in C++ that is
      more flexible than that provided by the core language.

      C++ has two distinct kinds of polymorphism, virtual functions and templates,
      each of which has its own advantages and disadvantages.

          Virtual functions are not resolved until runtime, while templates are always
          resolved at compile time. If your types can vary at runtime (for example,
          if they depend on user input), then static polymorphism with templates
          doesn't help much.

          Virtual functions can be used with separate compilation. The body of a
          template has to be available in every translation unit in which it is used,
          slowing down compiles and increasing rebuilds.

          Virtual functions automatically make the requirements on the arguments
          explicit. Templates are only checked when they're instantiated, requiring
          extra work in testing, assertions, and documentation.

          The compiler creates a new copy of each function template every time it
          is instantiated. This allows better optimization, because the compiler
          knows everything statically, but it also causes a significant increase
          of binary sizes.

          Templates support Value semantics. Objects that "behave like an int"
          and are not shared are easier to reason about. To use virtual functions,
          on the other hand, you have to use (smart) pointers or references.

          Template libraries can allow third-party types to be adapted non-intrusively
          for seamless interoperability. With virtual functions, you have to create
          a wrapper that inherits from the base class.

          Templates can handle constraints involving multiple types. For example,
          std::for_each takes an iterator range and a function that can be called
          on the elements of the range. Virtual functions aren't really able to express
          such constraints.

      The Boost.TypeErasure library combines the superior abstraction capabilities
      of templates, with the runtime flexibility of virtual functions.

      Boost includes several special cases of this kind of polymorphism:

          boost::any for CopyConstructible types.

          boost::function for objects that can be called
          like functions.

          Boost.Range provides any_iterator.

      Boost.TypeErasure generalizes this to support arbitrary requirements and provides
      a predefined set of common concepts

Last revised: August 05, 2021 at 09:53:07 GMT


text:
import notification from '..';

const delay = timeout => new Promise(resolve => setTimeout(resolve, timeout));

describe('notification', () => {
  afterEach(() => {
    notification.destroy();
  });

  it('should be able to hide manually', async () => {
    notification.open({
      message: 'Notification Title',
      duration: 0,
      key: '1',
    });
    notification.open({
      message: 'Notification Title',
      duration: 0,
      key: '2',
    });
    expect(document.querySelectorAll('.ant-notification-notice').length).toBe(2);
    notification.close('1');
    await delay(100);
    expect(document.querySelectorAll('.ant-notification-notice').length).toBe(1);
    notification.close('2');
    await delay(100);
    expect(document.querySelectorAll('.ant-notification-notice').length).toBe(0);
  });

  it('should be able to destroy globally', () => {
    notification.open({
      message: 'Notification Title',
      duration: 0,
    });
    notification.open({
      message: 'Notification Title',
      duration: 0,
    });
    expect(document.querySelectorAll('.ant-notification').length).toBe(1);
    expect(document.querySelectorAll('.ant-notification-notice').length).toBe(2);
    notification.destroy();
    expect(document.querySelectorAll('.ant-notification').length).toBe(0);
    expect(document.querySelectorAll('.ant-notification-notice').length).toBe(0);
  });
});


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.assign = exports.CACHE_KEY = exports.KNOWN_SHELLS = undefined;
exports.identifyEnvironment = identifyEnvironment;
exports.identifyEnvironmentAsync = identifyEnvironmentAsync;
exports.parse = parse;
exports.applySugar = applySugar;
exports.getCommand = getCommand;

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _lodash = require('lodash.uniq');

var _lodash2 = _interopRequireDefault(_lodash);

var _child_process = require('child_process');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SPAWN_TIMEOUT = 4000;

var DEFAULT_PATHS = ['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin'];
var KNOWN_SHELLS = exports.KNOWN_SHELLS = ['zsh', 'bash', 'fish'];
var CACHE_KEY = exports.CACHE_KEY = '__STEELBRAIN_CONSISTENT_ENV_V1';
var assign = exports.assign = Object.assign || function (target, source) {
  for (var key in source) {
    if ({}.hasOwnProperty.call(source, key)) {
      target[key] = source[key];
    }
  }
  return target;
};

function identifyEnvironment() {
  var _getCommand = getCommand(),
      command = _getCommand.command,
      parameters = _getCommand.parameters,
      options = _getCommand.options;

  options.timeout = SPAWN_TIMEOUT;
  return (0, _child_process.spawnSync)(command, parameters, options).stdout.toString().split('\0');
}

function identifyEnvironmentAsync() {
  return new Promise(function (resolve, reject) {
    var _getCommand2 = getCommand(),
        command = _getCommand2.command,
        parameters = _getCommand2.parameters,
        options = _getCommand2.options;

    var childProcess = (0, _child_process.spawn)(command, parameters, options);
    var stdout = [];
    var timer = setTimeout(function () {
      childProcess.kill();
      reject(new Error('Process execution timed out'));
    }, SPAWN_TIMEOUT);
    childProcess.stdout.on('data', function (chunk) {
      stdout.push(chunk);
    });
    childProcess.on('close', function () {
      clearTimeout(timer);
      resolve(stdout.join('').split('\0'));
    });
    childProcess.on('error', function (error) {
      reject(error);
    });
  });
}

function parse(rawEnvironment) {
  var environment = {};
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = rawEnvironment[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var chunk = _step.value;

      var index = chunk.indexOf('=');
      if (index !== -1) {
        var key = chunk.slice(0, index);
        var value = chunk.slice(index + 1);
        environment[key] = value;
      }
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return environment;
}

function applySugar(environment) {
  var path = process.env.PATH ? process.env.PATH.split(':') : [];
  if (environment.PATH) {
    var _iteratorNormalCompletion2 = true;
    var _didIteratorError2 = false;
    var _iteratorError2 = undefined;

    try {
      for (var _iterator2 = environment.PATH.split(':')[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
        var chunk = _step2.value;

        if (chunk && path.indexOf(chunk) === -1) {
          path.push(chunk);
        }
      }
    } catch (err) {
      _didIteratorError2 = true;
      _iteratorError2 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion2 && _iterator2.return) {
          _iterator2.return();
        }
      } finally {
        if (_didIteratorError2) {
          throw _iteratorError2;
        }
      }
    }
  }
  var _iteratorNormalCompletion3 = true;
  var _didIteratorError3 = false;
  var _iteratorError3 = undefined;

  try {
    for (var _iterator3 = DEFAULT_PATHS[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
      var entry = _step3.value;

      if (path.indexOf(entry) === -1) {
        path = [entry].concat(path);
      }
    }
  } catch (err) {
    _didIteratorError3 = true;
    _iteratorError3 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion3 && _iterator3.return) {
        _iterator3.return();
      }
    } finally {
      if (_didIteratorError3) {
        throw _iteratorError3;
      }
    }
  }

  if (!environment.USER) {
    if (process.env.USER) {
      environment.USER = process.env.USER;
    } else if (environment.HOME) {
      environment.USER = _path2.default.basename(environment.HOME);
    }
  }

  environment.PATH = (0, _lodash2.default)(path).join(':');
  environment.PWD = process.cwd();
  environment.OLDPWD = environment.PWD;
  return environment;
}

function getCommand() {
  // Print the environment separated by \0
  var pyScript = 'import os;print(\\"\\0\\".join(map(\\"=\\".join, dict(os.environ).items()))+\\"\\0\\")';
  var shScript = 'python -c "' + pyScript + '"||' + 'python3 -c "' + pyScript + '"||' +
  // If python is not available, fallback to a POSIX compatible
  // way of retrieving the environment separated by \0.
  'env|' +
  // Find all names of potential environment variables.
  // This also returns variable assignments that are in the value
  // of another environment variable.
  'sed -n -e "s/^\\([A-Za-z_][A-Za-z0-9_]*\\)=.*/\\1/p"|' + 'while read name;' + 'do ' +
  // Check if the variable name is defined in the shell, thus
  // weeding out names that are not real environment variables.
  '[ "$name" != "_" -a -n "$(eval "printf \\"%s\\" \\"\\${$name+x}\\"")" ]&&' + // eslint-disable-line no-template-curly-in-string
  // Retrieve the value with an indirect variable reference.
  // This method has the drawback, that we have to ignore all
  // environment variables, whose names are not valid identifier.
  // As POSIX compatible environment variable names are valid
  // identifiers, this shouldn't cause problems.
  // The shell defines some variables on its own (like RANDOM).
  // Environment variables with the same name will be overwritten.
  'value="$(eval "printf \\"%s\\" \\"\\${$name}\\"")"&&' + // eslint-disable-line no-template-curly-in-string
  // Output the environment variable separated by \0.
  'printf "%s=%s\\0" "$name" "$value";' + 'done;' + 'exit;';
  // Wrap the script with sh for incompatible shells.
  var wrappedShScript = 'sh -c \'' + shScript + '\';exit;';
  var command = process.env.SHELL || 'sh';
  var options = { encoding: 'utf8' };
  var parameters = ['-c', wrappedShScript];

  var shell = _path2.default.basename(command);
  if (shell === 'bash') {
    parameters = ['-c', 'source ~/.bashrc;source ~/.bash_profile;' + shScript];
  } else if (shell === 'zsh') {
    parameters = ['-c', 'source ~/.zshrc;' + shScript];
  } else if (shell === 'fish') {
    parameters = ['-c', 'source ~/.config/fish/config.fish;' + wrappedShScript];
  } else if (shell === 'sh' || shell === 'ksh') {
    parameters = ['-c', shScript];
  }

  return { command: command, parameters: parameters, options: options };
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--

    Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved.

    This program and the accompanying materials are made available under the
    terms of the Eclipse Distribution License v. 1.0, which is available at
    http://www.eclipse.org/org/documents/edl-v10.php.

    SPDX-License-Identifier: BSD-3-Clause

-->

<bindings wsdlLocation="http://localhost:8080/jaxrpc-fromwsdl_handler_simple_rpclit/hello?wsdl"
    xmlns="http://java.sun.com/xml/ns/jaxws">

  <bindings node="ns1:definitions" xmlns:ns1="http://schemas.xmlsoap.org/wsdl/">
    <package name="fromwsdl.handler_simple_rpclit.client"/>
  </bindings>

  <!--bindings node="ns1:definitions/ns1:types/xs:schema[@targetNamespace='urn:test:types']"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:ns1="http://schemas.xmlsoap.org/wsdl/">
    <ns2:schemaBindings xmlns:ns2="http://java.sun.com/xml/ns/jaxb">
      <ns2:package name="fromwsdl.handler_simple_rpclit.client"/>
    </ns2:schemaBindings>
  </bindings-->

  <bindings xmlns:jws="http://java.sun.com/xml/ns/javaee">
    <jws:handler-chains>

      <jws:handler-chain>
        <jws:protocol-bindings>##SOAP11_HTTP</jws:protocol-bindings>
        <jws:handler>
          <jws:handler-class>fromwsdl.handler_simple_rpclit.common.SOAPTestHandler</jws:handler-class>
        </jws:handler>
      </jws:handler-chain>

      <jws:handler-chain>
        <jws:protocol-bindings>##SOAP12_HTTP</jws:protocol-bindings>
        <jws:handler>
          <jws:handler-class>fromwsdl.handler_simple_rpclit.client.Port12Handler</jws:handler-class>
        </jws:handler>
      </jws:handler-chain>

    </jws:handler-chains>
  </bindings>

</bindings>


text:
package com.github.mlk.guice.examples.robot;

interface Driveline {
}


text:
package io.flowing.retail.payment.resthacks;

import static org.springframework.web.bind.annotation.RequestMethod.PUT;

import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Step1: Simply call REST Service
 */
@RestController
public class PaymentRestHacksControllerV1 {

  @Autowired
  private RestTemplate rest;
  private String stripeChargeUrl = "http://localhost:8099/charge";

  @RequestMapping(path = "/payment/v1", method = PUT)
  public String retrievePayment(String retrievePaymentPayload, HttpServletResponse response) throws Exception {
    String traceId = UUID.randomUUID().toString();
    String customerId = "0815"; // get somehow from retrievePaymentPayload
    long amount = 15; // get somehow from retrievePaymentPayload

    System.out.println("PUT payment received");

    chargeCreditCard(customerId, amount);
    return "{\"status\":\"completed\", \"traceId\": \"" + traceId + "\"}";
  }

  public String chargeCreditCard(String customerId, long remainingAmount) {
    CreateChargeRequest request = new CreateChargeRequest();
    request.amount = remainingAmount;

    CreateChargeResponse response = rest.postForObject( //
            stripeChargeUrl, //
            request, //
            CreateChargeResponse.class);

    return response.transactionId;
  }

  public static class CreateChargeRequest {
    public long amount;
  }

  public static class CreateChargeResponse {
    public String transactionId;
  }

}


text:
from math import *

octree_node_size = 112

def recurse(depth):
	if depth == 0:
		return 1
	else:
		return pow(8, depth) + recurse(depth - 1)

def octree_size(depth):
	return recurse(depth) * octree_node_size

print("Size %d" % (octree_size(3)))


text:
DOKKU_ROOT=${DOKKU_ROOT:=~dokku}
DOCKER_BIN=${DOCKER_BIN:="docker"}
DOKKU_LIB_ROOT=${DOKKU_LIB_PATH:="/var/lib/dokku"}
PLUGIN_PATH=${PLUGIN_PATH:="$DOKKU_LIB_ROOT/plugins"}
PLUGIN_AVAILABLE_PATH=${PLUGIN_AVAILABLE_PATH:="$PLUGIN_PATH/available"}
PLUGIN_ENABLED_PATH=${PLUGIN_ENABLED_PATH:="$PLUGIN_PATH/enabled"}
PLUGIN_CORE_PATH=${PLUGIN_CORE_PATH:="$DOKKU_LIB_ROOT/core-plugins"}
PLUGIN_CORE_AVAILABLE_PATH=${PLUGIN_CORE_AVAILABLE_PATH:="$PLUGIN_CORE_PATH/available"}
CUSTOM_TEMPLATE_SSL_DOMAIN=customssltemplate.dokku.me
UUID=$(uuidgen)
TEST_APP="rdmtestapp-${UUID}"
TEST_NETWORK="test-network-${UUID}"
SKIPPED_TEST_ERR_MSG="previous test failed! skipping remaining tests..."

# global setup() and teardown()
# skips remaining tests on first failure
global_setup() {
  [[ ! -f "${BATS_PARENT_TMPNAME}.skip" ]] || skip "$SKIPPED_TEST_ERR_MSG"

  free -m
  cleanup_apps
  cleanup_containers
}

global_teardown() {
  [[ -n "$BATS_TEST_COMPLETED" ]] || touch "${BATS_PARENT_TMPNAME}.skip"
  cleanup_apps
  cleanup_containers
}

cleanup_apps() {
  rm -rf $DOKKU_ROOT/*/nginx.conf

  apps=$(dokku --quiet apps:list)
  if [[ -n "${apps}" ]]; then
    dokku --quiet apps:list | xargs -n1 dokku --force apps:destroy
  fi
}

cleanup_containers() {
  containers=$(docker container ls --quiet)
  if [[ -n "$containers" ]]; then
    docker container ls --quiet | xargs -n1 docker container rm -f || true
  fi
}

# test functions
flunk() {
  {
    if [[ "$#" -eq 0 ]]; then
      cat -
    else
      echo "$*"
    fi
  }
  return 1
}

# ShellCheck doesn't know about $status from Bats
# shellcheck disable=SC2154
# shellcheck disable=SC2120
assert_success() {
  if [[ "$status" -ne 0 ]]; then
    flunk "command failed with exit status $status"
  elif [[ "$#" -gt 0 ]]; then
    assert_output "$1"
  fi
}

# ShellCheck doesn't know about $status from Bats
# shellcheck disable=SC2154
# shellcheck disable=SC2120
assert_failure() {
  if [[ "$status" -eq 0 ]]; then
    flunk "expected failed exit status"
  elif [[ "$#" -gt 0 ]]; then
    assert_output "$1"
  fi
}

assert_equal() {
  if [[ "$1" != "$2" ]]; then
    {
      echo "expected: $1"
      echo "actual:   $2"
    } | flunk
  fi
}

assert_not_equal() {
  if [[ "$1" == "$2" ]]; then
    {
      echo "unexpected: $1"
      echo "actual:     $2"
    } | flunk
  fi
}

# ShellCheck doesn't know about $output from Bats
# shellcheck disable=SC2154
assert_output() {
  local expected
  if [[ $# -eq 0 ]]; then
    expected="$(cat -)"
  else
    expected="$1"
  fi
  assert_equal "$expected" "$output"
}

# ShellCheck doesn't know about $output from Bats
# shellcheck disable=SC2154
assert_not_output() {
  local expected
  if [[ $# -eq 0 ]]; then
    unexpected="$(cat -)"
  else
    unexpected="$1"
  fi
  assert_not_equal "$unexpected" "$output"
}

# ShellCheck doesn't know about $output from Bats
# shellcheck disable=SC2154
assert_output_exists() {
  [[ -n "$output" ]] || flunk "expected output, found none"
}

# ShellCheck doesn't know about $output from Bats
# shellcheck disable=SC2154
assert_output_not_exists() {
  [[ -z "$output" ]] || flunk "expected no output, found some"
}

# ShellCheck doesn't know about $output from Bats
# shellcheck disable=SC2154
assert_output_contains() {
  local input="$output"
  local expected="$1"
  local count="${2:-1}"
  local found=0
  until [ "${input/$expected/}" = "$input" ]; do
    input="${input/$expected/}"
    found=$((found + 1))
  done
  assert_equal "$count" "$found"
}

# ShellCheck doesn't know about $lines from Bats
# shellcheck disable=SC2154
assert_line() {
  if [[ "$1" -ge 0 ]] 2>/dev/null; then
    assert_equal "$2" "${lines[$1]}"
  else
    local line
    for line in "${lines[@]}"; do
      [[ "$line" == "$1" ]] && return 0
    done
    flunk "expected line \`$1'"
  fi
}

# ShellCheck doesn't know about $lines from Bats
# shellcheck disable=SC2154
assert_line_count() {
  declare EXPECTED="$1"
  local num_lines="${#lines[@]}"
  assert_equal "$EXPECTED" "$num_lines"
}

refute_line() {
  if [[ "$1" -ge 0 ]] 2>/dev/null; then
    local num_lines="${#lines[@]}"
    if [[ "$1" -lt "$num_lines" ]]; then
      flunk "output has $num_lines lines"
    fi
  else
    local line
    for line in "${lines[@]}"; do
      if [[ "$line" == "$1" ]]; then
        flunk "expected to not find line \`$line'"
      fi
    done
  fi
}

assert() {
  if ! "$*"; then
    flunk "failed: $*"
  fi
}

assert_exit_status() {
  assert_equal "$status" "$1"
}

# dokku functions
create_app() {
  local APP="$1"
  local TEST_APP=${APP:=$TEST_APP}
  dokku apps:create "$TEST_APP"
}

create_key() {
  ssh-keygen -P "" -f /tmp/testkey &>/dev/null
}

destroy_app() {
  local RC="$1"
  local RC=${RC:=0}
  local APP="$2"
  local TEST_APP=${APP:=$TEST_APP}
  dokku --force apps:destroy "$TEST_APP"
  return "$RC"
}

destroy_key() {
  rm -f /tmp/testkey* &>/dev/null || true
}

add_domain() {
  dokku domains:add "$TEST_APP" "$1"
}

# shellcheck disable=SC2119
check_urls() {
  local PATTERN="$1"
  run /bin/bash -c "dokku --quiet urls $TEST_APP | grep -E \"${PATTERN}\""
  echo "output: $output"
  echo "status: $status"
  assert_success
}

assert_http_success() {
  local url=$1
  run curl -kSso /dev/null -w "%{http_code}" "${url}"
  echo "output: $output"
  echo "status: $status"
  assert_output "200"
}

assert_ssl_domain() {
  local domain=$1
  assert_app_domain "${domain}"
  assert_http_redirect "http://${domain}" "https://${domain}:443/"
  assert_http_success "https://${domain}"
}

assert_nonssl_domain() {
  local domain=$1
  assert_app_domain "${domain}"
  assert_http_success "http://${domain}"
}

assert_app_domain() {
  local domain=$1
  run /bin/bash -c "dokku domains:report $TEST_APP --domains-app-vhosts | tr \" \" \"\n\" | grep -xF ${domain}"
  echo "app domains: $(dokku domains:report "$TEST_APP" --domains-app-vhosts)"
  echo "output: $output"
  echo "status: $status"
  assert_output "${domain}"
}

assert_http_redirect() {
  local from=$1
  local to=$2
  run curl -kSso /dev/null -w "%{redirect_url}" "${from}"
  echo "output: $output"
  echo "status: $status"
  assert_output "${to}"
}

assert_external_port() {
  local CID="$1"
  local EXTERNAL_PORT_COUNT
  EXTERNAL_PORT_COUNT="$(docker port "$CID" | wc -l)"
  run /bin/bash -c "[[ $EXTERNAL_PORT_COUNT -gt 0 ]]"
  assert_success
}

assert_not_external_port() {
  local CID="$1"
  local EXTERNAL_PORT_COUNT
  EXTERNAL_PORT_COUNT="$(docker port "$CID" | wc -l)"
  run /bin/bash -c "[[ $EXTERNAL_PORT_COUNT -gt 0 ]]"
  assert_failure
}

assert_url() {
  url="$1"
  run /bin/bash -c "dokku url $TEST_APP"
  echo "output: $output"
  echo "status: $status"
  echo "url: ${url}"
  assert_output "${url}"
}

assert_urls() {
  # shellcheck disable=SC2124
  urls="$@"
  run /bin/bash -c "dokku urls $TEST_APP | xargs"
  echo "output: $output"
  echo "status: $status"
  echo "urls:" "$urls"
  assert_output "$urls"
}

deploy_app() {
  declare APP_TYPE="$1" GIT_REMOTE="$2" CUSTOM_TEMPLATE="$3" CUSTOM_PATH="$4"
  local APP_TYPE=${APP_TYPE:="python"}
  local GIT_REMOTE=${GIT_REMOTE:="dokku@dokku.me:$TEST_APP"}
  local GIT_REMOTE_BRANCH=${GIT_REMOTE_BRANCH:="master"}
  local TMP=${CUSTOM_TMP:=$(mktemp -d "/tmp/dokku.me.XXXXX")}

  rmdir "$TMP" && cp -r "${BATS_TEST_DIRNAME}/../../tests/apps/$APP_TYPE" "$TMP"

  # shellcheck disable=SC2086
  [[ -n "$CUSTOM_TEMPLATE" ]] && $CUSTOM_TEMPLATE $TEST_APP $TMP/$CUSTOM_PATH

  pushd "$TMP" &>/dev/null || exit 1
  [[ -z "$CUSTOM_TMP" ]] && trap 'popd &>/dev/null || true; rm -rf "$TMP"' RETURN INT TERM

  git init
  git config user.email "robot@example.com"
  git config user.name "Test Robot"
  echo "setting up remote: $GIT_REMOTE"
  git remote add target "$GIT_REMOTE"

  [[ -f gitignore ]] && mv gitignore .gitignore
  git add .
  git commit -m 'initial commit'
  git push target "master:${GIT_REMOTE_BRANCH}" || destroy_app $?
}

setup_client_repo() {
  local TMP
  TMP=$(mktemp -d "/tmp/dokku.me.XXXXX")
  rmdir "$TMP" && cp -r "${BATS_TEST_DIRNAME}/../../tests/apps/nodejs-express" "$TMP"
  cd "$TMP" || exit 1
  git init
  git config user.email "robot@example.com"
  git config user.name "Test Robot"

  [[ -f gitignore ]] && mv gitignore .gitignore
  git add .
  git commit -m 'initial commit'
}

setup_test_tls() {
  local TLS_TYPE="$1"
  local TLS="/home/dokku/$TEST_APP/tls"
  mkdir -p "$TLS"

  case "$TLS_TYPE" in
    wildcard)
      local TLS_ARCHIVE=server_ssl_wildcard.tar
      ;;
    sans)
      local TLS_ARCHIVE=server_ssl_sans.tar
      ;;
    *)
      local TLS_ARCHIVE=server_ssl.tar
      ;;
  esac
  tar xf "$BATS_TEST_DIRNAME/$TLS_ARCHIVE" -C "$TLS"
  sudo chown -R dokku:dokku "${TLS}/.."
}

custom_ssl_nginx_template() {
  local APP="$1"
  local APP_REPO_DIR="$2"
  [[ -z "$APP" ]] && local APP="$TEST_APP"
  mkdir -p "$APP_REPO_DIR"

  echo "injecting custom_ssl_nginx_template -> $APP_REPO_DIR/nginx.conf.sigil"
  cat <<EOF >"$APP_REPO_DIR/nginx.conf.sigil"
{{ range \$port_map := .PROXY_PORT_MAP | split " " }}
{{ \$port_map_list := \$port_map | split ":" }}
{{ \$scheme := index \$port_map_list 0 }}
{{ \$listen_port := index \$port_map_list 1 }}
{{ \$upstream_port := index \$port_map_list 2 }}
{{ if eq \$scheme "http" }}
server {
  listen      [::]:{{ \$listen_port }};
  listen      {{ \$listen_port }};
  server_name {{ $.NOSSL_SERVER_NAME }} $CUSTOM_TEMPLATE_SSL_DOMAIN;
  return 301 https://\$host:{{ $.PROXY_SSL_PORT }}\$request_uri;
}
{{ else if eq \$scheme "https"}}
server {
  listen      [::]:{{ $.PROXY_SSL_PORT }} ssl spdy;
  listen      {{ $.PROXY_SSL_PORT }} ssl spdy;
  {{ if $.SSL_SERVER_NAME }}server_name {{ $.SSL_SERVER_NAME }} $CUSTOM_TEMPLATE_SSL_DOMAIN; {{ end }}
  {{ if $.NOSSL_SERVER_NAME }}server_name {{ $.NOSSL_SERVER_NAME }} $CUSTOM_TEMPLATE_SSL_DOMAIN; {{ end }}
  ssl_certificate     {{ $.APP_SSL_PATH }}/server.crt;
  ssl_certificate_key {{ $.APP_SSL_PATH }}/server.key;

  keepalive_timeout   70;
  add_header          Alternate-Protocol  {{ \$listen_port }}:npn-spdy/2;
  location    / {
    proxy_pass  http://{{ $.APP }}-{{ \$upstream_port }};
    proxy_http_version 1.1;
    proxy_set_header Upgrade \$http_upgrade;
    proxy_set_header Connection \$http_connection;
    proxy_set_header Host \$http_host;
    proxy_set_header X-Forwarded-Proto \$scheme;
    proxy_set_header X-Forwarded-For \$remote_addr;
    proxy_set_header X-Forwarded-Port \$server_port;
    proxy_set_header X-Request-Start \$msec;
  }
  include {{ $.DOKKU_ROOT }}/{{ $.APP }}/nginx.conf.d/*.conf;
}
{{ end }}{{ end }}

{{ if $.DOKKU_APP_WEB_LISTENERS }}
{{ range \$upstream_port := $.PROXY_UPSTREAM_PORTS | split " " }}
upstream {{ $.APP }}-{{ \$upstream_port }} {
{{ range \$listeners := $.DOKKU_APP_WEB_LISTENERS | split " " }}
{{ \$listener_list := \$listeners | split ":" }}
{{ \$listener_ip := index \$listener_list 0 }}
  server {{ \$listener_ip }}:{{ \$upstream_port }};{{ end }}
}
{{ end }}{{ end }}
EOF
  cat "$APP_REPO_DIR/nginx.conf.sigil"
}

custom_nginx_template() {
  local APP="$1"
  local APP_REPO_DIR="$2"
  [[ -z "$APP" ]] && local APP="$TEST_APP"
  mkdir -p "$APP_REPO_DIR"

  echo "injecting custom_nginx_template -> $APP_REPO_DIR/nginx.conf.sigil"
  cat <<EOF >"$APP_REPO_DIR/nginx.conf.sigil"
{{ range \$port_map := .PROXY_PORT_MAP | split " " }}
{{ \$port_map_list := \$port_map | split ":" }}
{{ \$scheme := index \$port_map_list 0 }}
{{ \$listen_port := index \$port_map_list 1 }}
{{ \$upstream_port := index \$port_map_list 2 }}

server {
  listen      [::]:{{ \$listen_port }};
  listen      {{ \$listen_port }};
  server_name {{ $.NOSSL_SERVER_NAME }} customtemplate.dokku.me;

  location    / {
    proxy_pass  http://{{ $.APP }}-{{ \$upstream_port }};
    proxy_http_version 1.1;
    proxy_set_header Upgrade \$http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host \$http_host;
    proxy_set_header X-Forwarded-Proto \$scheme;
    proxy_set_header X-Forwarded-For \$remote_addr;
    proxy_set_header X-Forwarded-Port \$server_port;
    proxy_set_header X-Request-Start \$msec;
  }
  include {{ $.DOKKU_ROOT }}/{{ $.APP }}/nginx.conf.d/*.conf;
}
{{ end }}

{{ if $.DOKKU_APP_WEB_LISTENERS }}
{{ range \$upstream_port := $.PROXY_UPSTREAM_PORTS | split " " }}
upstream {{ $.APP }}-{{ \$upstream_port }} {
{{ range \$listeners := $.DOKKU_APP_WEB_LISTENERS | split " " }}
{{ \$listener_list := \$listeners | split ":" }}
{{ \$listener_ip := index \$listener_list 0 }}
  server {{ \$listener_ip }}:{{ \$upstream_port }};{{ end }}
}
{{ end }}{{ end }}
{{ if $.DOKKU_APP_WORKER_LISTENERS }}
{{ range \$upstream_port := $.PROXY_UPSTREAM_PORTS | split " " }}
upstream {{ $.APP }}-worker-{{ \$upstream_port }} {
{{ range \$listeners := $.DOKKU_APP_WORKER_LISTENERS | split " " }}
  server {{ \$listeners }};{{ end }}
}
{{ end }}{{ end }}

EOF
  cat "$APP_REPO_DIR/nginx.conf.sigil"
}

bad_custom_nginx_template() {
  local APP="$1"
  local APP_REPO_DIR="$2"
  [[ -z "$APP" ]] && local APP="$TEST_APP"
  echo "injecting bad_custom_nginx_template -> $APP_REPO_DIR/nginx.conf.sigil"
  cat <<EOF >"$APP_REPO_DIR/nginx.conf.sigil"
some lame nginx config
EOF
}

template_checks_file() {
  local APP="$1"
  local APP_REPO_DIR="$2"
  [[ -z "$APP" ]] && local APP="$TEST_APP"
  echo "injecting templated CHECKS file -> $APP_REPO_DIR/CHECKS"
  cat <<EOF >"$APP_REPO_DIR/CHECKS"
WAIT=2 # wait 2 seconds
TIMEOUT=5 # set timeout to 5 seconds
ATTEMPTS=2 # try 2 times

{{ var "HEALTHCHECK_ENDPOINT" }} {{ var "HEALTHCHECK_ENDPOINT" }}
EOF
}

add_release_command() {
  local APP="$1"
  local APP_REPO_DIR="$2"
  [[ -z "$APP" ]] && local APP="$TEST_APP"
  echo "release: touch /app/release.test" >>"$APP_REPO_DIR/Procfile"
}

add_postdeploy_command() {
  local APP="$1"
  local APP_REPO_DIR="$2"
  [[ -z "$APP" ]] && local APP="$TEST_APP"
  touch "$APP_REPO_DIR/app.json"
  contents=$(jq '.scripts.postdeploy = "touch /app/heroku-postdeploy.test"' "$APP_REPO_DIR/app.json")
  echo "${contents}" >"$APP_REPO_DIR/app.json"
}

add_requirements_txt() {
  local APP="$1"
  local APP_REPO_DIR="$2"
  [[ -z "$APP" ]] && local APP="$TEST_APP"
  echo "flask" >>"$APP_REPO_DIR/requirements.txt"
}

build_nginx_config() {
  # simulate nginx post-deploy
  dokku domains:setup "$TEST_APP"
  dokku proxy:build-config "$TEST_APP"
}

create_network() {
  local NETWORK_NAME="$1:=$TEST_NETWORK"

  NETWORK=$(docker network ls -q -f name="$NETWORK_NAME")
  [[ -z "$NETWORK" ]] && docker network create "$NETWORK_NAME"
}

attach_network() {
  local NETWORK_NAME="$1:=$TEST_NETWORK"

  NETWORK=$(docker network ls -q -f name="$NETWORK_NAME")
  [[ -n "$NETWORK" ]] && docker network connect "$NETWORK_NAME" "${TEST_APP}.web.1"
}

create_attach_network() {
  local NETWORK_NAME="$1:=$TEST_NETWORK"

  create_network "$NETWORK_NAME"
  attach_network "$NETWORK_NAME"
}

delete_network() {
  local NETWORK_NAME="$1:=$TEST_NETWORK"

  NETWORK=$(docker network ls -q -f name="$NETWORK_NAME")
  [[ -n "$NETWORK" ]] && docker network rm "$NETWORK_NAME"
}

detach_network() {
  local NETWORK_NAME="$1:=$TEST_NETWORK"

  NETWORK=$(docker network ls -q -f name="$NETWORK_NAME")
  [[ -z "$NETWORK" ]] && docker network disconnect "$NETWORK_NAME" "${TEST_APP}.web.1"
}

detach_delete_network() {
  local NETWORK_NAME="$1:=$TEST_NETWORK"

  detach_network "$NETWORK_NAME"
  delete_network "$NETWORK_NAME"
}


text:
from scrapy.item import Item, Field

class ProductionhubItem(Item):
    # define the fields for your item here like:
    # name = Field()
    pass


text:
package org.simpleflatmapper.reflect.test;

import org.junit.Test;
import org.simpleflatmapper.reflect.*;
import org.simpleflatmapper.reflect.asm.AsmFactory;
import org.simpleflatmapper.reflect.impl.BuilderInstantiator;
import org.simpleflatmapper.reflect.getter.ConstantGetter;
import org.simpleflatmapper.reflect.getter.ConstantIntGetter;
import org.simpleflatmapper.reflect.impl.BuilderInstantiatorDefinitionFactory;
import org.simpleflatmapper.reflect.instantiator.ExecutableInstantiatorDefinition;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.simpleflatmapper.reflect.test.Utils.TEST_ASM_FACTORY_PROVIDER;

public class BuilderInstantiatorDefinitionFactoryTest {

    @Test
    public void testBuilderFromMethod() throws Exception {
        final List<InstantiatorDefinition> instantiatorDefinitions = BuilderInstantiatorDefinitionFactory.extractDefinitions(ClassBuilderWithMethod.class);

        assertEquals(1, instantiatorDefinitions.size());

        BuilderInstantiatorDefinition b = (BuilderInstantiatorDefinition) instantiatorDefinitions.get(0);

        assertEquals(ClassBuilderWithMethod.Builder.class.getName(), b.getName());

        // builder instantiator
        final ExecutableInstantiatorDefinition builderInstantiator = (ExecutableInstantiatorDefinition) b.getBuilderInstantiator();
        assertEquals(ClassBuilderWithMethod.class.getMethod("builder"), builderInstantiator.getExecutable());
        assertEquals(0, builderInstantiator.getParameters().length);

        final Parameter[] parameters = b.getParameters();

        assertEquals(3, parameters.length);

        Arrays.sort(parameters, new Comparator<Parameter>() {
            @Override
            public int compare(Parameter o1, Parameter o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        assertEquals("name", parameters[1].getName());
        assertEquals("id", parameters[0].getName());

        Map<Parameter, Getter<? super Void, ?>> params = new HashMap<Parameter, Getter<? super Void, ?>>();

        params.put(parameters[1], new ConstantGetter<Void, Object>("myname"));
        params.put(parameters[0], new ConstantIntGetter<Void>(3));

        final InstantiatorFactory instantiatorFactory = new InstantiatorFactory(TEST_ASM_FACTORY_PROVIDER, true);
        final Instantiator<Void, ClassBuilderWithMethod> instantiator = instantiatorFactory
                .<Void, ClassBuilderWithMethod>getInstantiator(b, Void.class, params, true, true);
        final ClassBuilderWithMethod o = instantiator
                .newInstance(null);
        assertFalse((instantiator instanceof BuilderInstantiator));

        assertEquals("myname", o.getName());
        assertEquals(3, o.getId());
    }

    @Test
    public void testBuilderFromMethodNoAsm() throws Exception {
        final List<InstantiatorDefinition> instantiatorDefinitions = BuilderInstantiatorDefinitionFactory.extractDefinitions(ClassBuilderWithMethod.class);

        assertEquals(1, instantiatorDefinitions.size());

        BuilderInstantiatorDefinition b = (BuilderInstantiatorDefinition) instantiatorDefinitions.get(0);

        final Parameter[] parameters = b.getParameters();

        Arrays.sort(parameters, new Comparator<Parameter>() {
            @Override
            public int compare(Parameter o1, Parameter o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Map<Parameter, Getter<? super Void, ?>> params = new HashMap<Parameter, Getter<? super Void, ?>>();

        params.put(parameters[1], new ConstantGetter<Void, Object>("myname"));
        params.put(parameters[0], new ConstantIntGetter<Void>(3));

        final InstantiatorFactory instantiatorFactory = new InstantiatorFactory(null);
        final Instantiator<Void, ClassBuilderWithMethod> instantiator = instantiatorFactory
                .<Void, ClassBuilderWithMethod>getInstantiator(b, Void.class, params, true, true);
        final ClassBuilderWithMethod o = instantiator
                .newInstance(null);

        assertEquals("myname", o.getName());
        assertEquals(3, o.getId());
    }

    @Test
    public void testBuilderFromMethodNullHandling() throws Exception {
        final List<InstantiatorDefinition> instantiatorDefinitions = BuilderInstantiatorDefinitionFactory.extractDefinitions(ClassBuilderWithMethod.class);

        assertEquals(1, instantiatorDefinitions.size());

        BuilderInstantiatorDefinition b = (BuilderInstantiatorDefinition) instantiatorDefinitions.get(0);

        final Parameter[] parameters = b.getParameters();

        Arrays.sort(parameters, new Comparator<Parameter>() {
            @Override
            public int compare(Parameter o1, Parameter o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Map<Parameter, Getter<? super Void, ?>> params = new HashMap<Parameter, Getter<? super Void, ?>>();

        params.put(parameters[1], new ConstantGetter<Void, Object>(null));
        params.put(parameters[0], new ConstantGetter<Void, Integer>(null));

        final InstantiatorFactory instantiatorFactory = new InstantiatorFactory(null);
        final Instantiator<Void, ClassBuilderWithMethod> instantiator = instantiatorFactory
                .<Void, ClassBuilderWithMethod>getInstantiator(b, Void.class, params, true, true);
        final ClassBuilderWithMethod o = instantiator
                .newInstance(null);

        assertEquals(null, o.getName());
        assertEquals(0, o.getId());
    }
    @Test
    public void testBuilderFromMethodNullHandlingNoAsm() throws Exception {
        final List<InstantiatorDefinition> instantiatorDefinitions = BuilderInstantiatorDefinitionFactory.extractDefinitions(ClassBuilderWithMethod.class);

        assertEquals(1, instantiatorDefinitions.size());

        BuilderInstantiatorDefinition b = (BuilderInstantiatorDefinition) instantiatorDefinitions.get(0);

        final Parameter[] parameters = b.getParameters();

        Arrays.sort(parameters, new Comparator<Parameter>() {
            @Override
            public int compare(Parameter o1, Parameter o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Map<Parameter, Getter<? super Void, ?>> params = new HashMap<Parameter, Getter<? super Void, ?>>();

        params.put(parameters[1], new ConstantGetter<Void, Object>(null));
        params.put(parameters[0], new ConstantGetter<Void, Integer>(null));

        final InstantiatorFactory instantiatorFactory = new InstantiatorFactory(null);
        final Instantiator<Void, ClassBuilderWithMethod> instantiator = instantiatorFactory
                .<Void, ClassBuilderWithMethod>getInstantiator(b, Void.class, params, false, true);
        final ClassBuilderWithMethod o = instantiator
                .newInstance(null);

        assertEquals(null, o.getName());
        assertEquals(0, o.getId());
    }

    @Test
    public void testBuilderFromMethodAsmBoxing() throws Exception {
        final List<InstantiatorDefinition> instantiatorDefinitions = BuilderInstantiatorDefinitionFactory.extractDefinitions(ClassBuilderWithMethod.class);

        assertEquals(1, instantiatorDefinitions.size());

        BuilderInstantiatorDefinition b = (BuilderInstantiatorDefinition) instantiatorDefinitions.get(0);

        final Parameter[] parameters = b.getParameters();

        Arrays.sort(parameters, new Comparator<Parameter>() {
            @Override
            public int compare(Parameter o1, Parameter o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Map<Parameter, Getter<? super Void, ?>> params = new HashMap<Parameter, Getter<? super Void, ?>>();

        params.put(parameters[1], new ConstantGetter<Void, Object>("myname"));
        params.put(parameters[0], new ConstantGetter<Void, Integer>(3));

        final InstantiatorFactory instantiatorFactory = new InstantiatorFactory(TEST_ASM_FACTORY_PROVIDER, true);
        final Instantiator<Void, ClassBuilderWithMethod> instantiator = instantiatorFactory
                .<Void, ClassBuilderWithMethod>getInstantiator(b, Void.class, params, true, true);
        final ClassBuilderWithMethod o = instantiator
                .newInstance(null);

        assertFalse((instantiator instanceof BuilderInstantiator));
        assertEquals("myname", o.getName());
        assertEquals(3, o.getId());
    }

    @Test
    public void testBuilderFromMethodVoid() throws Exception {
        final List<InstantiatorDefinition> instantiatorDefinitions = BuilderInstantiatorDefinitionFactory.extractDefinitions(ClassBuilderWithMethod.class);

        assertEquals(1, instantiatorDefinitions.size());

        BuilderInstantiatorDefinition b = (BuilderInstantiatorDefinition) instantiatorDefinitions.get(0);

        final Parameter[] parameters = b.getParameters();

        Arrays.sort(parameters, new Comparator<Parameter>() {
            @Override
            public int compare(Parameter o1, Parameter o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Map<Parameter, Getter<? super Void, ?>> params = new HashMap<Parameter, Getter<? super Void, ?>>();

        params.put(parameters[2], new ConstantGetter<Void, Object>("zrux"));
        params.put(parameters[0], new ConstantGetter<Void, Integer>(3));

        final InstantiatorFactory instantiatorFactory = new InstantiatorFactory(TEST_ASM_FACTORY_PROVIDER, true);
        final Instantiator<Void, ClassBuilderWithMethod> instantiator = instantiatorFactory
                .<Void, ClassBuilderWithMethod>getInstantiator(b, Void.class, params, true, true);
        final ClassBuilderWithMethod o = instantiator
                .newInstance(null);

        assertFalse((instantiator instanceof BuilderInstantiator));
        assertEquals(3, o.getId());
        assertEquals("zrux", o.getZrux());
    }

    @Test
    public void testBuilderFromMethodVoidNoAsm() throws Exception {
        final List<InstantiatorDefinition> instantiatorDefinitions = BuilderInstantiatorDefinitionFactory.extractDefinitions(ClassBuilderWithMethod.class);

        assertEquals(1, instantiatorDefinitions.size());

        BuilderInstantiatorDefinition b = (BuilderInstantiatorDefinition) instantiatorDefinitions.get(0);

        final Parameter[] parameters = b.getParameters();

        Arrays.sort(parameters, new Comparator<Parameter>() {
            @Override
            public int compare(Parameter o1, Parameter o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Map<Parameter, Getter<? super Void, ?>> params = new HashMap<Parameter, Getter<? super Void, ?>>();

        params.put(parameters[2], new ConstantGetter<Void, Object>("zrux"));
        params.put(parameters[0], new ConstantGetter<Void, Integer>(3));

        final InstantiatorFactory instantiatorFactory = new InstantiatorFactory(null, true);
        final Instantiator<Void, ClassBuilderWithMethod> instantiator = instantiatorFactory
                .<Void, ClassBuilderWithMethod>getInstantiator(b, Void.class, params, false, true);
        final ClassBuilderWithMethod o = instantiator
                .newInstance(null);

        assertTrue((instantiator instanceof BuilderInstantiator));
        assertEquals(3, o.getId());
        assertEquals("zrux", o.getZrux());
    }

    @Test
    public void testBuilderFromMethodVoidNullHandling() throws Exception {
        final List<InstantiatorDefinition> instantiatorDefinitions = BuilderInstantiatorDefinitionFactory.extractDefinitions(ClassBuilderWithMethod.class);

        assertEquals(1, instantiatorDefinitions.size());

        BuilderInstantiatorDefinition b = (BuilderInstantiatorDefinition) instantiatorDefinitions.get(0);

        final Parameter[] parameters = b.getParameters();

        Arrays.sort(parameters, new Comparator<Parameter>() {
            @Override
            public int compare(Parameter o1, Parameter o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Map<Parameter, Getter<? super Void, ?>> params = new HashMap<Parameter, Getter<? super Void, ?>>();

        params.put(parameters[2], new ConstantGetter<Void, Object>(null));
        params.put(parameters[0], new ConstantGetter<Void, Integer>(null));

        final InstantiatorFactory instantiatorFactory = new InstantiatorFactory(TEST_ASM_FACTORY_PROVIDER, true);
        final Instantiator<Void, ClassBuilderWithMethod> instantiator = instantiatorFactory
                .<Void, ClassBuilderWithMethod>getInstantiator(b, Void.class, params, true, true);
        final ClassBuilderWithMethod o = instantiator
                .newInstance(null);

        assertFalse((instantiator instanceof BuilderInstantiator));
        assertEquals(0, o.getId());
        assertEquals(null, o.getZrux());
    }

    @Test
    public void testBuilderFromMethodVoidNoAsmNullHandling() throws Exception {
        final List<InstantiatorDefinition> instantiatorDefinitions = BuilderInstantiatorDefinitionFactory.extractDefinitions(ClassBuilderWithMethod.class);

        assertEquals(1, instantiatorDefinitions.size());

        BuilderInstantiatorDefinition b = (BuilderInstantiatorDefinition) instantiatorDefinitions.get(0);

        final Parameter[] parameters = b.getParameters();

        Arrays.sort(parameters, new Comparator<Parameter>() {
            @Override
            public int compare(Parameter o1, Parameter o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Map<Parameter, Getter<? super Void, ?>> params = new HashMap<Parameter, Getter<? super Void, ?>>();

        params.put(parameters[2], new ConstantGetter<Void, Object>(null));
        params.put(parameters[0], new ConstantGetter<Void, Integer>(null));

        final InstantiatorFactory instantiatorFactory = new InstantiatorFactory(null, true);
        final Instantiator<Void, ClassBuilderWithMethod> instantiator = instantiatorFactory
                .<Void, ClassBuilderWithMethod>getInstantiator(b, Void.class, params, false, true);
        final ClassBuilderWithMethod o = instantiator
                .newInstance(null);

        assertTrue((instantiator instanceof BuilderInstantiator));
        assertEquals(0, o.getId());
        assertEquals(null, o.getZrux());
    }

    public static abstract class ClassBuilderWithMethod {

        public abstract String getName();
        public abstract int getId();
        public abstract String getZrux();

        public static Builder builder() {
            return new Builder();
        }

        public static class Builder {
            private final String name;
            private final int id;
            private String zrux;

            private Builder() {
                name = null;
                id = 0;
                zrux = null;
            }

            public Builder(String name, int id, String zrux) {
                this.name = name;
                this.id = id;
                this.zrux = zrux;
            }

            public Builder id(int id) {
                return new Builder(name, id, zrux);
            }

            public Builder name(String name) {
                return new Builder(name, id, zrux);
            }

            public void zrux(String zrux) {
                this.zrux = zrux;
            }

            public ClassBuilderWithMethod build() {
                return new ClassBuilderWithMethodImpl(name, id, zrux);
            }
        }

        private static class ClassBuilderWithMethodImpl extends ClassBuilderWithMethod {
            private final String name;
            private final String zrux;
            private final int id;

            private ClassBuilderWithMethodImpl(String name, int id, String zrux) {
                this.name = name;
                this.id = id;
                this.zrux = zrux;
            }

            @Override
            public String getName() {
                return name;
            }

            @Override
            public int getId() {
                return id;
            }

            @Override
            public String getZrux() {
                return zrux;
            }
        }

    }
}


text:
package info.xiaomo.server.event;

public interface IEventListener {

    /**
     * 更新
     *
     * @param type  type
     * @param param param
     */
    void update(EventType type, Object param);

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GRA.Controllers.ViewModel.MissionControl.PerformerScheduling;
using GRA.Controllers.ViewModel.Shared;
using GRA.Domain.Model;
using GRA.Domain.Model.Filters;
using GRA.Domain.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;

namespace GRA.Controllers.MissionControl
{
    [Area("MissionControl")]
    [Authorize(Policy = Policy.ViewPerformerDetails)]
    public class PerformerSchedulingController : Base.MCController
    {
        private const int KitsPerPage = 15;
        private const int PerformersPerPage = 15;
        private const int ProgramsPerPage = 15;

        private static readonly DateTime DefaultPerformerScheduleEndTime
            = DateTime.Parse("8:00 PM");

        private static readonly DateTime DefaultPerformerScheduleStartTime
                    = DateTime.Parse("8:00 AM");

        private readonly ILogger<PerformerSchedulingController> _logger;
        private readonly PerformerSchedulingService _performerSchedulingService;

        public PerformerSchedulingController(ILogger<PerformerSchedulingController> logger,
            ServiceFacade.Controller context,
            PerformerSchedulingService performerSchedulingService)
            : base(context)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _performerSchedulingService = performerSchedulingService
                ?? throw new ArgumentNullException(nameof(performerSchedulingService));
            PageTitle = "Performer Scheduling";
        }

        [Authorize(Policy = Policy.SchedulePerformers)]
        public async Task<JsonResult> CheckProgramTimeAvailability(int programId,
            DateTime dateTime,
            bool backToBack)
        {
            try
            {
                var result = await _performerSchedulingService
                    .ValidateScheduleTimeAsync(programId, dateTime, backToBack);

                if (!string.IsNullOrWhiteSpace(result))
                {
                    return Json(new
                    {
                        success = true,
                        message = result
                    });
                }
            }
            catch (GraException gex)
            {
                return Json(new
                {
                    success = false,
                    message = gex.Message
                });
            }

            return Json(new
            {
                success = true
            });
        }

        [Authorize(Policy = Policy.SchedulePerformers)]
        public async Task<JsonResult> GetKitAvailableAgeGroups(int branchId, int kitId)
        {
            PsKit kit;
            try
            {
                kit = await _performerSchedulingService.GetKitByIdAsync(kitId,
                    includeAgeGroups: true);
            }
            catch (GraException gex)
            {
                return Json(new
                {
                    success = false,
                    message = gex.Message
                });
            }

            var settings = await _performerSchedulingService.GetSettingsAsync();

            var branchSelections = await _performerSchedulingService
                .GetSelectionsByBranchIdAsync(branchId);
            if (branchSelections.Count >= settings.SelectionsPerBranch)
            {
                return Json(new
                {
                    success = false,
                    message = $"Branch has already made its {settings.SelectionsPerBranch} selections."
                });
            }

            var availableAgeGroups = kit.AgeGroups.Select(_ => _.Id.ToString())
                .Except(branchSelections.Select(_ => _.AgeGroupId.ToString()))
                .ToList();
            if (availableAgeGroups.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    message = "Branch already has selections for all of this kits age groups."
                });
            }

            return Json(new
            {
                success = true,
                data = availableAgeGroups
            });
        }

        [Authorize(Policy = Policy.SchedulePerformers)]
        public async Task<IActionResult> GetPerformerDaySchedule(int performerId, DateTime date)
        {
            var performerSchedule = await _performerSchedulingService
                .GetPerformerDateScheduleAsync(performerId, date.Date);

            var branchSelections = (await _performerSchedulingService
                .GetPerformerBranchSelectionsAsync(performerId, date)).ToList();

            var viewModel = new DayScheduleViewModel
            {
                BranchSelections = branchSelections
            };
            var startTime = performerSchedule?.StartTime ?? DefaultPerformerScheduleStartTime;
            var endTime = performerSchedule?.EndTime ?? DefaultPerformerScheduleEndTime;

            var earliestSelection = branchSelections
                .OrderBy(_ => _.ScheduleStartTime)
                .FirstOrDefault();
            var latestSelection = branchSelections
                .OrderByDescending(_ => _.ScheduleStartTime)
                .FirstOrDefault();

            if (earliestSelection == null
                || startTime.TimeOfDay < earliestSelection.ScheduleStartTime.TimeOfDay)
            {
                viewModel.StartTime = startTime.ToShortTimeString();
            }
            if (latestSelection == null
                || endTime.TimeOfDay > latestSelection.ScheduleStartTime
                    .AddMinutes(latestSelection.ScheduleDuration).TimeOfDay)
            {
                viewModel.EndTime = endTime.ToShortTimeString();
            }

            return PartialView("_DaySchedulePartial", viewModel);
        }

        [Authorize(Policy = Policy.SchedulePerformers)]
        public async Task<JsonResult> GetProgramAvailableAgeGroups(int branchId, int programId)
        {
            PsProgram program;
            try
            {
                program = await _performerSchedulingService.GetProgramByIdAsync(programId,
                    includeAgeGroups: true,
                    onlyApproved: true);
            }
            catch (GraException gex)
            {
                return Json(new
                {
                    success = false,
                    message = gex.Message
                });
            }

            var settings = await _performerSchedulingService.GetSettingsAsync();

            var branchSelections = await _performerSchedulingService
                .GetSelectionsByBranchIdAsync(branchId);
            if (branchSelections.Count >= settings.SelectionsPerBranch)
            {
                return Json(new
                {
                    success = false,
                    message = $"Branch has already made its {settings.SelectionsPerBranch} selections."
                });
            }

            var availableAgeGroups = program.AgeGroups
                .Select(_ => _.Id.ToString())
                .Except(branchSelections.Select(_ => _.AgeGroupId.ToString()))
                .ToList();
            if (availableAgeGroups.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    message = "Branch already has selections for all of this programs age groups."
                });
            }

            return Json(new
            {
                success = true,
                data = availableAgeGroups
            });
        }

        public async Task<IActionResult> Index()
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage == PsSchedulingStage.Unavailable)
            {
                ShowAlertDanger("Performer scheduling is not set up.");
                return RedirectToAction(nameof(HomeController.Index), "Home");
            }

            var systemId = GetId(ClaimType.SystemId);

            var viewModel = new ScheduleOverviewViewModel
            {
                Settings = settings,
                SchedulingStage = schedulingStage,
                AgeGroups = await _performerSchedulingService.GetAgeGroupsAsync(),
                CanSchedule = UserHasPermission(Permission.SchedulePerformers)
            };

            if (schedulingStage >= PsSchedulingStage.SchedulingOpen)
            {
                var system = await _performerSchedulingService
                    .GetSystemWithoutExcludedBranchesAsync(systemId);
                viewModel.SystemName = system.Name;

                var branches = system.Branches;
                foreach (var branch in branches)
                {
                    branch.Selections = await _performerSchedulingService
                        .GetSelectionsByBranchIdAsync(branch.Id);
                }

                viewModel.Branches = branches;
            }

            if (schedulingStage >= PsSchedulingStage.SchedulePosted)
            {
                var branches = await _performerSchedulingService
                    .GetNonExcludedSystemBranchesAsync(systemId, true);
                viewModel.BranchList = new SelectList(branches, "Id", "Name");
            }

            return View(viewModel);
        }

        public async Task<IActionResult> Kit(int id)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulingPreview)
            {
                return RedirectToAction(nameof(Index));
            }

            PsKit kit;
            try
            {
                kit = await _performerSchedulingService
                    .GetKitByIdAsync(id, includeAgeGroups: true, includeImages: true);
            }
            catch (GraException gex)
            {
                ShowAlertDanger("Unable to view kit: ", gex);
                return RedirectToAction(nameof(Kits));
            }

            var viewModel = new KitViewModel
            {
                Kit = kit,
                SchedulingOpen = schedulingStage == PsSchedulingStage.SchedulingOpen,
                CanSchedule = UserHasPermission(Permission.SchedulePerformers)
            };

            if (kit.Images.Count > 0)
            {
                viewModel.ImagePath = _pathResolver.ResolveContentPath(
                    kit.Images[0].Filename);
            }

            if (!string.IsNullOrWhiteSpace(kit.Website)
                && Uri.TryCreate(kit.Website, UriKind.Absolute, out Uri absoluteUri))
            {
                viewModel.Uri = absoluteUri;
            }

            if (viewModel.SchedulingOpen)
            {
                viewModel.AgeGroupList = new SelectList(kit.AgeGroups, "Id", "Name");

                var system = await _performerSchedulingService
                    .GetSystemWithoutExcludedBranchesAsync(GetId(ClaimType.SystemId));

                var branches = new List<Branch>();
                foreach (var branch in system.Branches)
                {
                    var branchSelections = await _performerSchedulingService
                            .GetSelectionsByBranchIdAsync(branch.Id);

                    if (branchSelections.Count >= settings.SelectionsPerBranch)
                    {
                        continue;
                    }
                    else
                    {
                        var selectedAgeGroups = branchSelections.Select(_ => _.AgeGroupId);
                        var availableAgeGroups = kit.AgeGroups
                            .Any(_ => !selectedAgeGroups.Contains(_.Id));

                        if (!availableAgeGroups)
                        {
                            continue;
                        }
                    }
                    branches.Add(branch);
                }
                viewModel.BranchList = new SelectList(branches, "Id", "Name");
            }

            var kitIndexList = await _performerSchedulingService.GetKitIndexListAsync();
            var index = kitIndexList.IndexOf(id);
            viewModel.ReturnPage = (index / KitsPerPage) + 1;
            if (index != 0)
            {
                viewModel.PrevKit = kitIndexList[index - 1];
            }
            if (kitIndexList.Count != index + 1)
            {
                viewModel.NextKit = kitIndexList[index + 1];
            }

            return View(viewModel);
        }

        public async Task<IActionResult> KitImages(int id)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulingPreview)
            {
                return RedirectToAction(nameof(Index));
            }

            PsKit kit;
            try
            {
                kit = await _performerSchedulingService.GetKitByIdAsync(id, includeImages: true);
            }
            catch (GraException gex)
            {
                ShowAlertDanger("Unable to view kit images: ", gex);
                return RedirectToAction(nameof(Kits));
            }

            kit.Images.ForEach(_ => _.Filename = _pathResolver
               .ResolveContentPath(_.Filename));

            return View(kit);
        }

        public async Task<IActionResult> Kits(int page = 1)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulingPreview)
            {
                return RedirectToAction(nameof(Index));
            }

            var filter = new BaseFilter(page, KitsPerPage);

            var kitList = await _performerSchedulingService.GetPaginatedKitListAsync(filter);

            var paginateModel = new PaginateViewModel
            {
                ItemCount = kitList.Count,
                CurrentPage = page,
                ItemsPerPage = filter.Take.Value
            };
            if (paginateModel.PastMaxPage)
            {
                return RedirectToRoute(
                    new
                    {
                        page = paginateModel.LastPage ?? 1
                    });
            }

            var viewModel = new KitListViewModel
            {
                Kits = kitList.Data,
                PaginateModel = paginateModel
            };

            return View(viewModel);
        }

        public async Task<IActionResult> Performer(int id)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulingPreview)
            {
                return RedirectToAction(nameof(Index));
            }

            var performer = new PsPerformer();
            try
            {
                performer = await _performerSchedulingService.GetPerformerByIdAsync(id,
                    includeImages: true,
                    includePrograms: true,
                    includeSchedule: true,
                    onlyApproved: true);
            }
            catch (GraException gex)
            {
                ShowAlertDanger("Unable to view performer: ", gex);
                return RedirectToAction(nameof(Performers));
            }

            var system = await _performerSchedulingService
                .GetSystemWithoutExcludedBranchesAsync(GetId(ClaimType.SystemId));

            var viewModel = new PerformerViewModel
            {
                AgeGroups = await _performerSchedulingService
                    .GetPerformerAgeGroupsAsync(performer.Id),
                BlackoutDates = await _performerSchedulingService.GetBlackoutDatesAsync(),
                Performer = performer,
                Settings = settings,
                System = system
            };

            if (!performer.AllBranches)
            {
                viewModel.BranchAvailability = await _performerSchedulingService
                    .GetPerformerBranchIdsAsync(performer.Id, system.Id);
            }

            if (performer.Images.Count > 0)
            {
                viewModel.ImagePath = _pathResolver.ResolveContentPath(
                    performer.Images[0].Filename);
            }

            if (!string.IsNullOrWhiteSpace(performer.Website)
                && Uri.TryCreate(performer.Website, UriKind.Absolute, out Uri absoluteUri))
            {
                viewModel.Uri = absoluteUri;
            }

            var performerIndexList = await _performerSchedulingService
                .GetPerformerIndexListAsync(true);
            var index = performerIndexList.IndexOf(id);
            viewModel.ReturnPage = (index / PerformersPerPage) + 1;
            if (index != 0)
            {
                viewModel.PrevPerformer = performerIndexList[index - 1];
            }
            if (performerIndexList.Count != index + 1)
            {
                viewModel.NextPerformer = performerIndexList[index + 1];
            }

            return View(viewModel);
        }

        public async Task<IActionResult> PerformerImages(int id)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulingPreview)
            {
                return RedirectToAction(nameof(Index));
            }

            PsPerformer performer;
            try
            {
                performer = await _performerSchedulingService.GetPerformerByIdAsync(id,
                    includeImages: true,
                    onlyApproved: true);
            }
            catch (GraException gex)
            {
                ShowAlertDanger("Unable to view performer images: ", gex);
                return RedirectToAction(nameof(Performers));
            }

            performer.Images.ForEach(_ => _.Filename = _pathResolver
                .ResolveContentPath(_.Filename));

            return View(performer);
        }

        public async Task<IActionResult> Performers(int page = 1)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulingPreview)
            {
                return RedirectToAction(nameof(Index));
            }

            var filter = new PerformerSchedulingFilter(page, PerformersPerPage)
            {
                IsApproved = true
            };

            var performerList
                = await _performerSchedulingService.GetPaginatedPerformerListAsync(filter);

            var paginateModel = new PaginateViewModel
            {
                ItemCount = performerList.Count,
                CurrentPage = page,
                ItemsPerPage = filter.Take.Value
            };
            if (paginateModel.PastMaxPage)
            {
                return RedirectToRoute(
                    new
                    {
                        page = paginateModel.LastPage ?? 1
                    });
            }

            var systemId = GetId(ClaimType.SystemId);
            foreach (var performer in performerList.Data)
            {
                performer.AvailableInSystem = await _performerSchedulingService
                    .GetPerformerSystemAvailabilityAsync(performer.Id, systemId);
                performer.ProgramCount = await _performerSchedulingService
                    .GetPerformerProgramCountAsync(performer.Id);
            }

            var viewModel = new PerformerListViewModel
            {
                Performers = performerList.Data,
                PaginateModel = paginateModel
            };

            return View(viewModel);
        }

        public async Task<IActionResult> Program(int id, bool? list = null, int? ageGroup = null)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulingPreview)
            {
                return RedirectToAction(nameof(Index));
            }

            PsProgram program;
            try
            {
                program = await _performerSchedulingService.GetProgramByIdAsync(id,
                    includeAgeGroups: true,
                    includeImages: true,
                    onlyApproved: true);
            }
            catch (GraException gex)
            {
                ShowAlertDanger("Unable to view program: ", gex);
                return RedirectToAction(nameof(Programs));
            }

            var selectedAgeGroup = program.AgeGroups.FirstOrDefault(_ => _.Id == ageGroup);

            var performer = await _performerSchedulingService.GetPerformerByIdAsync(
                program.PerformerId);
            var system = await _performerSchedulingService
                .GetSystemWithoutExcludedBranchesAsync(GetId(ClaimType.SystemId));

            var viewModel = new ProgramViewModel
            {
                AgeGroup = selectedAgeGroup,
                AllBranches = performer.AllBranches,
                List = list == true,
                Program = program,
                SchedulingOpen = schedulingStage == PsSchedulingStage.SchedulingOpen,
                System = system,
                CanSchedule = UserHasPermission(Permission.SchedulePerformers)
            };

            if (!performer.AllBranches)
            {
                viewModel.BranchAvailability = await _performerSchedulingService
                    .GetPerformerBranchIdsAsync(performer.Id, system.Id);
            }

            if (program.Images?.Count > 0)
            {
                viewModel.Image = _pathResolver.ResolveContentPath(
                    program.Images[0].Filename);
            }

            if (viewModel.SchedulingOpen)
            {
                viewModel.AgeGroupList = new SelectList(program.AgeGroups, "Id", "Name");
                var branches = new List<Branch>();
                foreach (var branch in system.Branches)
                {
                    if (!performer.AllBranches
                        && !viewModel.BranchAvailability.Contains(branch.Id))
                    {
                        continue;
                    }
                    else
                    {
                        var branchSelections = await _performerSchedulingService
                            .GetSelectionsByBranchIdAsync(branch.Id);

                        if (branchSelections.Count >= settings.SelectionsPerBranch)
                        {
                            continue;
                        }
                        else
                        {
                            var selectedAgeGroups = branchSelections.Select(_ => _.AgeGroupId);
                            var availableAgeGroups = program.AgeGroups
                                .Any(_ => !selectedAgeGroups.Contains(_.Id));

                            if (!availableAgeGroups)
                            {
                                continue;
                            }
                        }
                    }
                    branches.Add(branch);
                }
                viewModel.BranchList = new SelectList(branches, "Id", "Name");
            }

            if (viewModel.List)
            {
                var programIndexList = await _performerSchedulingService.GetProgramIndexListAsync(
                    ageGroupId: selectedAgeGroup?.Id,
                    onlyApproved: true);

                var index = programIndexList.IndexOf(id);
                viewModel.ReturnPage = (index / ProgramsPerPage) + 1;
                if (index != 0)
                {
                    viewModel.PrevProgram = programIndexList[index - 1];
                }
                if (programIndexList.Count != index + 1)
                {
                    viewModel.NextProgram = programIndexList[index + 1];
                }
            }

            return View(viewModel);
        }

        public async Task<IActionResult> ProgramImages(int id, bool? list = null,
            int? ageGroup = null)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulingPreview)
            {
                return RedirectToAction(nameof(Index));
            }

            PsProgram program;
            try
            {
                program = await _performerSchedulingService
                    .GetProgramByIdAsync(id, includeImages: true, onlyApproved: true);
            }
            catch (GraException gex)
            {
                ShowAlertDanger("Unable to view program images: ", gex);
                return RedirectToAction(nameof(Programs));
            }

            program.Images.ForEach(_ => _.Filename = _pathResolver
                .ResolveContentPath(_.Filename));

            var viewModel = new ProgramImagesViewModel
            {
                Program = program
            };

            if (list == true)
            {
                viewModel.List = list;
                viewModel.AgeGroup = ageGroup;
            }

            return View(viewModel);
        }

        public async Task<IActionResult> Programs(int page = 1, int? ageGroup = null)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulingPreview)
            {
                return RedirectToAction(nameof(Index));
            }

            var filter = new PerformerSchedulingFilter(page, ProgramsPerPage)
            {
                AgeGroupId = ageGroup,
                IsApproved = true
            };

            var programList
                = await _performerSchedulingService.GetPaginatedProgramListAsync(filter);

            var paginateModel = new PaginateViewModel
            {
                ItemCount = programList.Count,
                CurrentPage = page,
                ItemsPerPage = filter.Take.Value
            };
            if (paginateModel.PastMaxPage)
            {
                return RedirectToRoute(
                    new
                    {
                        page = paginateModel.LastPage ?? 1
                    });
            }

            var systemId = GetId(ClaimType.SystemId);
            foreach (var program in programList.Data)
            {
                program.AvailableInSystem = await _performerSchedulingService
                    .GetPerformerSystemAvailabilityAsync(program.PerformerId, systemId);
            }

            var viewModel = new ProgramListViewModel
            {
                Programs = programList.Data,
                PaginateModel = paginateModel,
                AgeGroups = await _performerSchedulingService.GetAgeGroupsAsync(),
                AgeGroupId = ageGroup
            };

            return View(viewModel);
        }

        public async Task<IActionResult> Schedule(int id)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage < PsSchedulingStage.SchedulePosted)
            {
                return RedirectToAction(nameof(Index));
            }

            var branch = await _performerSchedulingService.GetNonExcludedBranch(id);

            if (branch == null)
            {
                return RedirectToAction(nameof(Index));
            }

            branch.Selections = await _performerSchedulingService
                .GetSelectionsByBranchIdAsync(branch.Id);

            var viewModel = new ScheduleViewModel
            {
                Settings = settings,
                Branch = branch
            };

            return View(viewModel);
        }

        [HttpPost]
        [Authorize(Policy = Policy.SchedulePerformers)]
        public async Task<JsonResult> ScheduleProgram(PsBranchSelection branchSelection)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage != PsSchedulingStage.SchedulingOpen)
            {
                return Json(new
                {
                    success = false,
                    message = "Program selection is not currently open."
                });
            }

            try
            {
                var addedBranchSelection = await _performerSchedulingService
                    .AddBranchProgramSelectionAsync(branchSelection);

                _logger.LogInformation("Program selection: {BranchSelectionId} added by user {UserId}",
                    addedBranchSelection.Id,
                    GetId(ClaimType.UserId));
            }
            catch (GraException gex)
            {
                return Json(new
                {
                    success = false,
                    message = gex.Message
                });
            }

            ShowAlertSuccess("Program selection added!");
            return Json(new
            {
                success = true
            });
        }

        [HttpPost]
        [Authorize(Policy = Policy.SchedulePerformers)]
        public async Task<IActionResult> SelectKit(PsBranchSelection branchSelection)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage != PsSchedulingStage.SchedulingOpen)
            {
                return RedirectToAction(nameof(Index));
            }

            PsBranchSelection addedBranchSelection = null;

            try
            {
                addedBranchSelection = await _performerSchedulingService
                    .AddBranchKitSelectionAsync(branchSelection);

                _logger.LogInformation("Kit selection: {BranchSelectionId} added by user {UserId}",
                    addedBranchSelection.Id,
                    GetId(ClaimType.UserId));

                ShowAlertSuccess("Kit selection added!");
            }
            catch (GraException gex)
            {
                ShowAlertDanger($"Unable to select kit: ", gex);
            }

            if (branchSelection?.KitId != null)
            {
                return RedirectToAction(nameof(Kit), new { id = branchSelection.KitId });
            }
            else
            {
                return RedirectToAction(nameof(Kits));
            }
        }

        [HttpPost]
        [Authorize(Policy = Policy.SchedulePerformers)]
        public async Task<IActionResult> SelectProgram(ProgramViewModel model)
        {
            var settings = await _performerSchedulingService.GetSettingsAsync();
            var schedulingStage = _performerSchedulingService.GetSchedulingStage(settings);
            if (schedulingStage != PsSchedulingStage.SchedulingOpen)
            {
                return RedirectToAction(nameof(Index));
            }

            PsProgram program;
            try
            {
                program = await _performerSchedulingService.GetProgramByIdAsync(
                    model.BranchSelection.ProgramId.Value, onlyApproved: true);
            }
            catch (GraException gex)
            {
                ShowAlertDanger("Unable to select program: ", gex);
                return RedirectToAction(nameof(Programs));
            }

            var ageAlreadySelected = await _performerSchedulingService
                .BranchAgeGroupAlreadySelectedAsync(model.BranchSelection.AgeGroupId,
                    model.BranchSelection.BranchId);

            if (ageAlreadySelected)
            {
                ShowAlertDanger("Branch already has a selection for that age group.");
                return RedirectToAction(nameof(Program), new { id = program.Id });
            }

            var programAvailableAtBranch = await _performerSchedulingService
                .ProgramAvailableAtBranchAsync(model.BranchSelection.ProgramId.Value,
                    model.BranchSelection.BranchId);

            if (!programAvailableAtBranch)
            {
                ShowAlertDanger("The performer does not performer at that branch.");
                return RedirectToAction(nameof(Program), new { id = program.Id });
            }

            PsAgeGroup ageGroup;

            try
            {
                ageGroup = await _performerSchedulingService
                    .GetAgeGroupByIdAsync(model.BranchSelection.AgeGroupId);
            }
            catch (GraException gex)
            {
                ShowAlertDanger("Unable to select age group: ", gex.Message);
                return RedirectToAction(nameof(Program), new { id = program.Id });
            }

            var viewModel = new SelectProgramViewModel
            {
                BranchSelection = model.BranchSelection,
                BlackoutDates = await _performerSchedulingService.GetBlackoutDatesAsync(),
                ScheduleDates = await _performerSchedulingService.GetPerformerScheduleAsync(
                    program.PerformerId),
                BookedDates = (await _performerSchedulingService
                    .GetPerformerBranchSelectionsAsync(program.PerformerId))
                    .Select(_ => _.RequestedStartTime),
                Settings = settings
            };

            if (await _performerSchedulingService.BranchAgeGroupHasBackToBackAsync(
                model.BranchSelection.AgeGroupId, model.BranchSelection.BranchId))
            {
                viewModel.BranchSelection.BackToBackProgram = true;
            }

            viewModel.BranchSelection.AgeGroup = ageGroup;
            viewModel.BranchSelection.Branch = await _performerSchedulingService
                .GetNonExcludedBranch(model.BranchSelection.BranchId);
            viewModel.BranchSelection.Program = program;

            return View(viewModel);
        }
    }
}


text:
Risk Groups

Assign your Slaves to groups which share a common risk of failure, e.g. a shared power supply.

MAMID spreads Replica Set members over Slaves in different Risk Groups to minimize downtime & maximize availability.

Slaves not assigned to a Risk Group will be used for Replica Sets regardless of their physical interdependencies with remaining Replica Set members.

<form ng-submit="createRiskGroup()">

Create a new Risk Group

                        <input type="text" ng-model="new_riskgroup.name" placeholder="New Risk Group Name"
                               class="form-control">
                        <button class="btn btn-success"
                                                              type="submit">Create</button>

</form>

            <input placeholder="Filter Slaves" ng-model="search" type="text" class="form-control">

                    Unassigned Slaves
                 {{unassigned_slaves.length}}

                    {{slave.hostname}}
                    Assign to
                            <select ng-model="slave.riskgroup" ng-change="assignToRiskGroup(slave)">
                                <option value="" selected>Select group..</option>
                                <option ng-repeat="riskgroup in riskgroups"
                                        value="{{riskgroup.id}}">{{riskgroup.name}}</option>
                            </select>

            <button class="btn btn-danger" ng-disabled="!isDeletable(riskgroup)"
                                             data-toggle="modal" data-target="#confirm_remove{{riskgroup.id}}"></button>

                    {{riskgroup.name}}
                 {{riskgroup.slaves.length}}

                    {{slave.hostname}}
                    Assign to
                        <select ng-model="slave.riskgroup" ng-change="assignToRiskGroup(slave, riskgroup)">
                            <option value="" selected>Select group..</option>
                            <option value="0">Remove from risk group</option>
                            <option ng-repeat="riskgroup_sel in riskgroups" value="{{riskgroup_sel.id}}"
                                    ng-if="riskgroup_sel.id!=riskgroup.id">{{riskgroup_sel.name}}</option>
                            </select>

                <button type="button" class="close" data-dismiss="modal" aria-label="Cancel">×</button>

Confirm Risk Group Removal

                You are about to remove the risk group {{riskgroup.name}}.

                <button type="button" ng-click="removeRiskGroup(riskgroup)" class="btn btn-danger">Remove Risk Group
                </button>
                <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>


text:
.jumbotron{
  float: none;
  margin-right: auto;
  margin-left: auto;
  width: 80%;
  padding: 5%;
  text-align:justify;
  background-color: rgb(52, 52, 52);
  border-radius: 5%;
}
.columns {
    float: none;
    margin-right: auto;
    margin-left: auto;
    width: 90%;
    padding: 5%;
}
/* Style the list */
.price {
    list-style-type: none;
    border: none;
    margin: 0;
    padding: 0;
    -webkit-transition: 0.3s;
    transition: 0.3s;
    background-color: rgb(27, 60, 76);
}
/* Pricing header */
.price .header {
    background-color: rgb(19, 41, 57);
    color: white;
    font-size: 25px;
}
/* List items */
.price li {
    border-bottom: none;
    padding: 20px;
    text-align: center;
}
/* Change the width of the three columns to 100%
(to stack horizontally on small screens) */
@media only screen and (max-width: 600px) {
    .columns {
        width: 100%;
    }
}
.columns table{
  font-size: 20px;
  margin-left: auto;
  margin-right: auto;
}

#myScrollBtn {
  display: none;
  position: fixed;
  bottom: 20px;
  top: 90%;
  right: 30px;
  z-index: 100;
  border: none;
  outline: none;
  background-color: green;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 10px;
}

#myScrollBtn:hover {
  background-color: #555;
}

/*#myGoBacklcd{
  position: relative;
  top:20%;
  left:-44%;
  border: none;
  outline: none;
  background-color: green;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 10px;
  font-weight: bold;
}*/
#myGoBacklBtn{
  position: relative;
  top:20%;
  left:-42%;
  border: none;
  outline: none;
  background-color: green;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 10px;
  font-weight: bold;
}


text:
- aproximação
- afastamento
- criação de grupo com uma unica pessoa (Group created)
- criação de grupo com mais de uma pessoa (Group updated)
- join de uma ou mais pessoas em um grupo já existente
- left de uma ou mais pessoas em um grupo já existente

## Visualização:
- grouping, pela cor (view de imagem e de mundo)
- tracking, pelos pontos (view de mundo)

## Vídeos testados:
- BR-01
- BR-07
- UKN-01
- UKN-03
- AT-01
- AT-02
- CN-01
- CN-02

Em alguns vídeos percebe-se que as coordenadas de mundo estão um tanto estranhas na visualização!
- BR-07

A camera (imagem e mundo) está num ângulo estranho (mas não compromete a detecção de eventos:
- AT-01

### TooFarDistance:
Distância máxima que define se é necessário verificar evento de aproximação/afastamento
- 400	(BR-01) Um valor exageradamente alto, pessoas que estavam em lados opostos da imagem eram indentificados eventos de aproximação, o que gerava spamming no logging dos eventos.
- 300 	(BR-01) Em comparação com 4 m consideravelmente o número de eventos disparados, mas muitos dos logs exibidos ainda parecem desnecessários.
- 250	(BR-01) Este é um bom valor pois 2,5 m é uma distância interessante de avaliar aproximação ou distanciamento entre pessoas, além de diminuir muito os logs.

### MinimumDistanceChange:
Distancia mínima de variação entre duas pessoas em 3 frames de diferença para verificar evento de aproximação/afastamento
- 5		(BR-01) É um valor muito baixo para uma variação de distância, exibe muitos logs, porém estes condizem com a realidade
- 7		(BR-01) É um valor razoável e permite desconsiderar mudanças mínimas
- 15 	(BR-01) Com poucas pessoas e no início do vídeo geralmente nenhum evento é disparado

### GroupingMaxDistance:
Distância máxima entre duas pessoas que podem serem consideradas um grupo
- 100	(BR-01) Nota-se que há casos em que um par de pessoas estão andando lado a lado e são classificadas como em grupos distintos.
- 120	(UKN-01) Parece um valor razoável os agrupamentos na visualização
- 150	(BR-01) Com esta distância o problema anterior não ocorre mais, mas há casos em que visualizando o vídeo uma pessoa que nem parece estar tão próxima acaba acidentalmente incluída no grupo.
		(BR-07) (UKN-01) No entanto, pessoas que estavam exatamente uma do lado da outra acabavam  sendo consideradas grupos diferentes.


text:
/*=========================================================================

 Portions (c) Copyright Brigham and Women's Hospital (BWH)
 All Rights Reserved.

 See http://www.slicer.org/copyright/copyright.txt for details.

 Program:   Module Description Parser

=========================================================================*/

// CTK includes
#include "ctkBinaryFileDescriptor.h"
#include "ctkPimpl.h"

// BinUtils includes
#include <bfd.h>

// STD includes
#include <cstdlib>
#include <utility>
#include <vector>

//-----------------------------------------------------------------------------
class ctkBinaryFileDescriptorPrivate
{
public:
  // Convenient typedefs
  typedef std::pair<asection*, void* > MemorySectionType;
  typedef std::vector<MemorySectionType> MemorySectionContainer;

  ctkBinaryFileDescriptorPrivate();

  /// Resolves a symbol
  void* resolve(const char * symbol);

  MemorySectionContainer Sections;
  bfd *                  BFD;

  QString FileName;
};

// --------------------------------------------------------------------------
// ctkBinaryFileDescriptorPrivate methods

// --------------------------------------------------------------------------
ctkBinaryFileDescriptorPrivate::ctkBinaryFileDescriptorPrivate()
{
  this->BFD = 0;
}

// --------------------------------------------------------------------------
void* ctkBinaryFileDescriptorPrivate::resolve(const char * symbol)
{
  if (!this->BFD)
    {
    return 0;
    }

  void *addr = 0;

  // Get the symbol table
  long storageNeeded = bfd_get_symtab_upper_bound(this->BFD);
  asymbol ** symbolTable = reinterpret_cast<asymbol **>(malloc(storageNeeded));

  long numberOfSymbols = bfd_canonicalize_symtab(this->BFD, symbolTable);

  // Run through the symbol table, looking for the requested symbol
  for (int i = 0; i < numberOfSymbols; i++)
    {
    if (strcmp(symbol, symbolTable[i]->name) == 0)
      {
      // Found the symbol, get the section pointer
      asection *p = bfd_get_section(symbolTable[i]);

      // Do we have this section already?
      MemorySectionContainer::iterator sit;
      for (sit = this->Sections.begin(); sit != this->Sections.end(); ++sit)
        {
        if ((*sit).first == p)
          {
          break;
          }
        }

      PTR mem;
      if (sit == this->Sections.end())
        {
        // Get the contents of the section
        bfd_size_type sz = bfd_get_section_size (p);
        mem = malloc (sz);
        if (bfd_get_section_contents(this->BFD, p, mem, static_cast<file_ptr>(0), sz))
          {
          this->Sections.push_back( MemorySectionType(p, mem) );
          }
        else
          {
          // Error reading section
          free(mem);
          break;
          }
        }
      else
        {
        // pull the start of the section block from the cache
        mem = const_cast<void*>((*sit).second);
        }

      // determine the address of this section
      addr = reinterpret_cast<char *>(mem)
          + (bfd_asymbol_value(symbolTable[i]) - bfd_asymbol_base(symbolTable[i]));
      break;
      }
    }

  // cleanup. just delete the outer vector for the symbol table
  free(symbolTable);

  return addr;
}

// --------------------------------------------------------------------------
// ctkBinaryFileDescriptor methods

// --------------------------------------------------------------------------
ctkBinaryFileDescriptor::ctkBinaryFileDescriptor(): d_ptr(new ctkBinaryFileDescriptorPrivate)
{
}

// --------------------------------------------------------------------------
ctkBinaryFileDescriptor::ctkBinaryFileDescriptor(const QString& _fileName):
  d_ptr(new ctkBinaryFileDescriptorPrivate)
{
  Q_D(ctkBinaryFileDescriptor);
  d->FileName = _fileName;
}

// --------------------------------------------------------------------------
ctkBinaryFileDescriptor::~ctkBinaryFileDescriptor()
{
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkBinaryFileDescriptor, QString, fileName, FileName);
CTK_SET_CPP(ctkBinaryFileDescriptor, const QString&, setFileName, FileName);

// --------------------------------------------------------------------------
bool ctkBinaryFileDescriptor::isLoaded() const
{
  Q_D(const ctkBinaryFileDescriptor);
  return (d->BFD != 0);
}

// --------------------------------------------------------------------------
bool ctkBinaryFileDescriptor::load()
{
  Q_D(ctkBinaryFileDescriptor);

  bfd_init();
  bfd * abfd = bfd_openr(d->FileName.toLatin1(), NULL);
  if (!abfd)
    {
    return false;
    }

  /* make sure it's an object file */
  if (!bfd_check_format (abfd, bfd_object))
    {
    bfd_close(abfd);
    return false;
    }

  d->BFD = abfd;
  return true;
}

// --------------------------------------------------------------------------
bool ctkBinaryFileDescriptor::unload()
{
  Q_D(ctkBinaryFileDescriptor);

  if (d->BFD)
    {
    bfd_close(d->BFD);
    d->BFD = 0;
    }
  return true;
}

// --------------------------------------------------------------------------
void* ctkBinaryFileDescriptor::resolve(const char * symbol)
{
  Q_D(ctkBinaryFileDescriptor);
  return d->resolve(symbol);
}


text:
using System;
namespace SocialGoal.Model.Models
{
    public class GroupRequest
    {
        public int GroupRequestId { get; set; }

        public int GroupId { get; set; }

        public string UserId { get; set; }

        public virtual Group Group { get; set; }

        public virtual ApplicationUser User { get; set; }

        public bool Accepted { get; set; }
    }
}


text:
/************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/

#pragma once

#include "Core/References.h"

NAMESPACE_GRAPHICS_BEGIN

//-----------------------------------//

NAMESPACE_GRAPHICS_END