text:
<?php

namespace Drupal\views_ui\Tests;

use Drupal\views\Entity\View;

/**
 * Tests exposed forms UI functionality.
 *
 * @group views_ui
 */
class ExposedFormUITest extends UITestBase {

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = ['test_exposed_admin_ui'];

  /**
   * {@inheritdoc}
   */
  public static $modules = ['node', 'views_ui', 'block', 'taxonomy', 'field_ui', 'datetime'];

  /**
   * Array of error message strings raised by the grouped form.
   *
   * @var array
   *
   * @see FilterPluginBase::buildGroupValidate
   */
  protected $groupFormUiErrors = [];

  protected function setUp() {
    parent::setUp();

    $this->drupalCreateContentType(['type' => 'article']);
    $this->drupalCreateContentType(['type' => 'page']);

    // Create some random nodes.
    for ($i = 0; $i < 5; $i++) {
      $this->drupalCreateNode();
    }

    // Error strings used in the grouped filter form validation.
    $this->groupFormUiErrors['missing_value'] = t('A value is required if the label for this item is defined.');
    $this->groupFormUiErrors['missing_title'] = t('A label is required if the value for this item is defined.');
    $this->groupFormUiErrors['missing_title_empty_operator'] = t('A label is required for the specified operator.');
  }

  /**
   * Tests the admin interface of exposed filter and sort items.
   */
  public function testExposedAdminUi() {
    $edit = [];

    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type');
    // Be sure that the button is called exposed.
    $this->helperButtonHasLabel('edit-options-expose-button-button', t('Expose filter'));

    // The first time the filter UI is displayed, the operator and the
    // value forms should be shown.
    $this->assertFieldById('edit-options-operator-in', '', 'Operator In exists');
    $this->assertFieldById('edit-options-operator-not-in', '', 'Operator Not In exists');
    $this->assertFieldById('edit-options-value-page', '', 'Checkbox for Page exists');
    $this->assertFieldById('edit-options-value-article', '', 'Checkbox for Article exists');

    // Click the Expose filter button.
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type', $edit, t('Expose filter'));
    // Check the label of the expose button.
    $this->helperButtonHasLabel('edit-options-expose-button-button', t('Hide filter'));

    // After exposing the filter, Operator and Value should be still here.
    $this->assertFieldById('edit-options-operator-in', '', 'Operator In exists');
    $this->assertFieldById('edit-options-operator-not-in', '', 'Operator Not In exists');
    $this->assertFieldById('edit-options-value-page', '', 'Checkbox for Page exists');
    $this->assertFieldById('edit-options-value-article', '', 'Checkbox for Article exists');

    // Check the validations of the filter handler.
    $edit = [];
    $edit['options[expose][identifier]'] = '';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertText(t('The identifier is required if the filter is exposed.'));

    $edit = [];
    $edit['options[expose][identifier]'] = 'value';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertText(t('This identifier is not allowed.'));

    // Now check the sort criteria.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/sort/created');
    $this->helperButtonHasLabel('edit-options-expose-button-button', t('Expose sort'));
    $this->assertNoFieldById('edit-options-expose-label', '', 'Make sure no label field is shown');

    // Un-expose the filter.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type');
    $this->drupalPostForm(NULL, [], t('Hide filter'));

    // After Un-exposing the filter, Operator and Value should be shown again.
    $this->assertFieldById('edit-options-operator-in', '', 'Operator In exists after hide filter');
    $this->assertFieldById('edit-options-operator-not-in', '', 'Operator Not In exists after hide filter');
    $this->assertFieldById('edit-options-value-page', '', 'Checkbox for Page exists after hide filter');
    $this->assertFieldById('edit-options-value-article', '', 'Checkbox for Article exists after hide filter');

    // Click the Expose sort button.
    $edit = [];
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/sort/created', $edit, t('Expose sort'));
    // Check the label of the expose button.
    $this->helperButtonHasLabel('edit-options-expose-button-button', t('Hide sort'));
    $this->assertFieldById('edit-options-expose-label', '', 'Make sure a label field is shown');

    // Test adding a new exposed sort criteria.
    $view_id = $this->randomView()['id'];
    $this->drupalGet("admin/structure/views/nojs/add-handler/$view_id/default/sort");
    $this->drupalPostForm(NULL, ['name[node_field_data.created]' => 1], t('Add and configure @handler', ['@handler' => t('sort criteria')]));
    $this->assertFieldByXPath('//input[@name="options[order]" and @checked="checked"]', 'ASC', 'The default order is set.');
    // Change the order and expose the sort.
    $this->drupalPostForm(NULL, ['options[order]' => 'DESC'], t('Apply'));
    $this->drupalPostForm("admin/structure/views/nojs/handler/$view_id/default/sort/created", [], t('Expose sort'));
    $this->assertFieldByXPath('//input[@name="options[order]" and @checked="checked"]', 'DESC');
    $this->assertFieldByName('options[expose][label]', 'Authored on', 'The default label is set.');
    // Change the label and save the view.
    $edit = ['options[expose][label]' => $this->randomString()];
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->drupalPostForm(NULL, [], t('Save'));
    // Check that the values were saved.
    $display = View::load($view_id)->getDisplay('default');
    $this->assertTrue($display['display_options']['sorts']['created']['exposed']);
    $this->assertEqual($display['display_options']['sorts']['created']['expose'], ['label' => $edit['options[expose][label]']]);
    $this->assertEqual($display['display_options']['sorts']['created']['order'], 'DESC');
  }

  /**
   * Tests the admin interface of exposed grouped filters.
   */
  public function testGroupedFilterAdminUi() {
    $edit = [];

    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type');

    // Click the Expose filter button.
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type', $edit, t('Expose filter'));
    // Check the label of the grouped filters button.
    $this->helperButtonHasLabel('edit-options-group-button-button', t('Grouped filters'));

    // Click the Grouped Filters button.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type');
    $this->drupalPostForm(NULL, [], t('Grouped filters'));

    // After click on 'Grouped Filters', the standard operator and value should
    // not be displayed.
    $this->assertNoFieldById('edit-options-operator-in', '', 'Operator In not exists');
    $this->assertNoFieldById('edit-options-operator-not-in', '', 'Operator Not In not exists');
    $this->assertNoFieldById('edit-options-value-page', '', 'Checkbox for Page not exists');
    $this->assertNoFieldById('edit-options-value-article', '', 'Checkbox for Article not exists');

    // Check that after click on 'Grouped Filters', a new button is shown to
    // add more items to the list.
    $this->helperButtonHasLabel('edit-options-group-info-add-group', t('Add another item'));

    // Validate a single entry for a grouped filter.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type');
    $edit = [];
    $edit["options[group_info][group_items][1][title]"] = 'Is Article';
    $edit["options[group_info][group_items][1][value][article]"] = 'article';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertUrl('admin/structure/views/view/test_exposed_admin_ui/edit/default');
    $this->assertNoGroupedFilterErrors();

    // Validate multiple entries for grouped filters.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type');
    $edit = [];
    $edit["options[group_info][group_items][1][title]"] = 'Is Article';
    $edit["options[group_info][group_items][1][value][article]"] = 'article';
    $edit["options[group_info][group_items][2][title]"] = 'Is Page';
    $edit["options[group_info][group_items][2][value][page]"] = 'page';
    $edit["options[group_info][group_items][3][title]"] = 'Is Page and Article';
    $edit["options[group_info][group_items][3][value][article]"] = 'article';
    $edit["options[group_info][group_items][3][value][page]"] = 'page';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertUrl('admin/structure/views/view/test_exposed_admin_ui/edit/default', [], 'Correct validation of the node type filter.');
    $this->assertNoGroupedFilterErrors();

    // Validate an "is empty" filter -- title without value is valid.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/body_value');
    $edit = [];
    $edit["options[group_info][group_items][1][title]"] = 'No body';
    $edit["options[group_info][group_items][1][operator]"] = 'empty';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertUrl('admin/structure/views/view/test_exposed_admin_ui/edit/default', [], 'The "empty" operator validates correctly.');
    $this->assertNoGroupedFilterErrors();

    // Ensure the string "0" can be used as a value for numeric filters.
    $this->drupalPostForm('admin/structure/views/nojs/add-handler/test_exposed_admin_ui/default/filter', ['name[node_field_data.nid]' => TRUE], t('Add and configure @handler', ['@handler' => t('filter criteria')]));
    $this->drupalPostForm(NULL, [], t('Expose filter'));
    $this->drupalPostForm(NULL, [], t('Grouped filters'));
    $edit = [];
    $edit['options[group_info][group_items][1][title]'] = 'Testing zero';
    $edit['options[group_info][group_items][1][operator]'] = '>';
    $edit['options[group_info][group_items][1][value][value]'] = '0';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertUrl('admin/structure/views/view/test_exposed_admin_ui/edit/default', [], 'A string "0" is a valid value.');
    $this->assertNoGroupedFilterErrors();

    // Ensure "between" filters validate correctly.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/nid');
    $edit['options[group_info][group_items][1][title]'] = 'ID between test';
    $edit['options[group_info][group_items][1][operator]'] = 'between';
    $edit['options[group_info][group_items][1][value][min]'] = '0';
    $edit['options[group_info][group_items][1][value][max]'] = '10';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertUrl('admin/structure/views/view/test_exposed_admin_ui/edit/default', [], 'The "between" filter validates correctly.');
    $this->assertNoGroupedFilterErrors();
  }

  public function testGroupedFilterAdminUiErrors() {
    // Select the empty operator without a title specified.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/body_value');
    $edit = [];
    $edit["options[group_info][group_items][1][title]"] = '';
    $edit["options[group_info][group_items][1][operator]"] = 'empty';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertText($this->groupFormUiErrors['missing_title_empty_operator']);

    // Specify a title without a value.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type');
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type', [], t('Expose filter'));
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type', [], t('Grouped filters'));
    $edit = [];
    $edit["options[group_info][group_items][1][title]"] = 'Is Article';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertText($this->groupFormUiErrors['missing_value']);

    // Specify a value without a title.
    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type');
    $edit = [];
    $edit["options[group_info][group_items][1][title]"] = '';
    $edit["options[group_info][group_items][1][value][article]"] = 'article';
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    $this->assertText($this->groupFormUiErrors['missing_title']);
  }

  /**
   * Asserts that there are no Grouped Filters errors.
   *
   * @param string $message
   *   The assert message.
   * @param string $group
   *   The assertion group.
   *
   * @return bool
   *   Result of the assertion.
   */
  protected function assertNoGroupedFilterErrors($message = '', $group = 'Other') {
    foreach ($this->groupFormUiErrors as $error) {
      $err_message = $message;
      if (empty($err_message)) {
        $err_message = "Verify that '$error' is not in the HTML output.";
      }
      if (empty($message)) {
        return $this->assertNoRaw($error, $err_message, $group);
      }
    }
    return TRUE;
  }

  /**
  * Tests the configuration of grouped exposed filters.
  */
  public function testExposedGroupedFilter() {
    // Click the Expose filter button.
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type', [], t('Expose filter'));
    // Select 'Grouped filters' radio button.
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/type', [], t('Grouped filters'));
    // Add 3 groupings.
    $edit = [
      'options[group_button][radios][radios]' => 1,
      'options[group_info][group_items][1][title]' => '1st',
      'options[group_info][group_items][1][value][all]' => 'all',
      'options[group_info][group_items][2][title]' => '2nd',
      'options[group_info][group_items][2][value][article]' => 'article',
      'options[group_info][group_items][3][title]' => '3rd',
      'options[group_info][group_items][3][value][page]' => 'page',
    ];
    // Apply the filter settings.
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    // Check that the view is saved without errors.
    $this->drupalPostForm(NULL, [], t('Save'));
    $this->assertResponse(200);

    // Click the Expose filter button.
    $this->drupalPostForm('admin/structure/views/nojs/add-handler/test_exposed_admin_ui/default/filter', ['name[node_field_data.status]' => 1], t('Add and configure filter criteria'));
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/status', [], t('Expose filter'));
    // Select 'Grouped filters' radio button.
    $this->drupalPostForm('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/status', [], t('Grouped filters'));
    // Add 3 groupings.
    $edit = [
      'options[group_button][radios][radios]' => 1,
      'options[group_info][group_items][1][title]' => 'Any',
      'options[group_info][group_items][1][value]' => 'All',
      'options[group_info][group_items][2][title]' => 'Published',
      'options[group_info][group_items][2][value]' => 1,
      'options[group_info][group_items][3][title]' => 'Unpublished',
      'options[group_info][group_items][3][value]' => 0,
    ];
    // Apply the filter settings.
    $this->drupalPostForm(NULL, $edit, t('Apply'));
    // Check that the view is saved without errors.
    $this->drupalPostForm(NULL, [], t('Save'));
    $this->assertResponse(200);

    $this->drupalGet('admin/structure/views/nojs/handler/test_exposed_admin_ui/default/filter/status');
    // Assert the same settings defined before still are there.
    $this->assertFieldChecked('edit-options-group-info-group-items-1-value-all');
    $this->assertFieldChecked('edit-options-group-info-group-items-2-value-1');
    $this->assertFieldChecked('edit-options-group-info-group-items-3-value-0');
  }

}


text:
import collections
import math
import numpy as np
import pandas as pd
import scipy.optimize

from threeML.io.progress_bar import progress_bar
from threeML.exceptions.custom_exceptions import custom_warnings
from threeML.utils.differentiation import get_hessian, ParameterOnBoundary

# Set the warnings to be issued always for this module

custom_warnings.simplefilter("always", RuntimeWarning)

# Special constants
FIT_FAILED = 1e12

# Define a bunch of custom exceptions relevant for what is being accomplished here

class CannotComputeCovariance(RuntimeWarning):
    pass

class CannotComputeErrors(RuntimeWarning):
    pass

class ParameterIsNotFree(Exception):
    pass

class FitFailed(Exception):
    pass

class MinimizerNotAvailable(Exception):
    pass

class BetterMinimumDuringProfiling(RuntimeWarning):
    pass

# This will contain the available minimizers

_minimizers = {}

def get_minimizer(minimizer_type):
    """
    Return the requested minimizer *class* (not instance)

    :param minimizer_type: MINUIT, ROOT, PYOPT...
    :return: the class (i.e., the type) for the requested minimizer
    """

    try:

        return _minimizers[minimizer_type.upper()]

    except KeyError:

        raise MinimizerNotAvailable("Minimizer %s is not available on your system" % minimizer_type)

class FunctionWrapper(object):

    def __init__(self, function, all_parameters, fixed_parameters):
        """

        :param function:
        :param all_parameters:
        :param fixed_parameters: list of fixed parameters
        """
        self._function = function

        self._all_parameters = all_parameters

        self._fixed_parameters_values = np.zeros(len(fixed_parameters))
        self._fixed_parameters_names = fixed_parameters

        self._indexes_of_fixed_par = np.zeros(len(self._all_parameters), bool)

        for i, parameter_name in enumerate(self._fixed_parameters_names):

            this_index = self._all_parameters.keys().index(parameter_name)

            self._indexes_of_fixed_par[this_index] = True

        self._all_values = np.zeros(len(self._all_parameters))

    def set_fixed_values(self, new_fixed_values):

        # Note that this will receive the fixed values in internal reference (after the transformations, if any)

        # A use [:] so there is an implicit check on the right size of new_fixed_values

        self._fixed_parameters_values[:] = new_fixed_values

    def __call__(self, *trial_values):

        # Note that this function will receive the trial values in internal reference (after the transformations,
        # if any)

        self._all_values[self._indexes_of_fixed_par] = self._fixed_parameters_values
        self._all_values[~self._indexes_of_fixed_par] = trial_values

        return self._function(*self._all_values)

class ProfileLikelihood(object):

    def __init__(self, minimizer_instance, fixed_parameters):

        self._fixed_parameters = fixed_parameters

        assert len(self._fixed_parameters) <= 2, "Can handle only one or two fixed parameters"

        # Get some info from the original minimizer

        self._function = minimizer_instance.function

        # Note that here we have to use the original parameters (not the internal parameters)

        self._all_parameters = minimizer_instance.parameters

        # Create a copy of the dictionary of parameters

        free_parameters = collections.OrderedDict(self._all_parameters)

        # Remove the fixed ones

        for parameter_name in fixed_parameters:

            free_parameters.pop(parameter_name)

        # Now compute how many free parameters we have

        self._n_free_parameters = len(free_parameters)

        if self._n_free_parameters > 0:

            self._wrapper = FunctionWrapper(self._function,
                                            self._all_parameters,
                                            self._fixed_parameters)

            # Create a copy of the optimizer with the new parameters (i.e., one or two
            # parameters fixed to their current values)

            self._optimizer = type(minimizer_instance)(self._wrapper, free_parameters, verbosity=0)

            if minimizer_instance.algorithm_name is not None:

                self._optimizer.set_algorithm(minimizer_instance.algorithm_name)

        else:

            # Special case when there are no free parameters after fixing the requested ones
            # There is no profiling necessary here

            self._wrapper = None
            self._optimizer = None

    def _transform_steps(self, parameter_name, steps):
        """
        If the parameter has a transformation, use it for the steps and return the transformed steps

        :return: transformed steps
        """

        if self._all_parameters[parameter_name].has_transformation():

            new_steps = self._all_parameters[parameter_name].transformation.forward(steps)

            return new_steps

        else:

            # Nothing to do

            return steps

    def step(self, steps1, steps2=None):

        if steps2 is not None:

            assert len(self._fixed_parameters) == 2, "Cannot step in 2d if you fix only one parameter"

            # Find out if the user is giving flipped steps (i.e. param_1 is after param_2 in the
            # parameters dictionary)

            param_1_name = self._fixed_parameters[0]
            param_1_idx = self._all_parameters.keys().index(param_1_name)

            param_2_name = self._fixed_parameters[1]
            param_2_idx = self._all_parameters.keys().index(param_2_name)

            # Fix steps if needed
            steps1 = self._transform_steps(param_1_name, steps1)

            if steps2 is not None:

                steps2 = self._transform_steps(param_2_name, steps2)

            if param_1_idx > param_2_idx:

                # Switch steps

                swap = steps1
                steps1 = steps2
                steps2 = swap

                results = self._step2d(steps1, steps2).T

            else:

                results = self._step2d(steps1, steps2)

            return results

        else:

            assert len(self._fixed_parameters) == 1, "You cannot step in 1d if you fix 2 parameters"

            return self._step1d(steps1)

    def __call__(self, values):

        self._wrapper.set_fixed_values(values)

        _, this_log_like = self._optimizer.minimize(compute_covar=False)

        return this_log_like

    def _step1d(self, steps1):

        log_likes = np.zeros_like(steps1)

        with progress_bar(len(steps1)) as p:

            for i, step in enumerate(steps1):

                if self._n_free_parameters > 0:

                    # Profile out the free parameters

                    self._wrapper.set_fixed_values(step)

                    _, this_log_like = self._optimizer.minimize(compute_covar=False)

                else:

                    # No free parameters, just compute the likelihood

                    this_log_like = self._function(step)

                log_likes[i] = this_log_like

                p.increase()

        return log_likes

    def _step2d(self, steps1, steps2):

        log_likes = np.zeros((len(steps1), len(steps2)))

        with progress_bar(len(steps1) * len(steps2)) as p:

            for i, step1 in enumerate(steps1):

                for j,step2 in enumerate(steps2):

                    if self._n_free_parameters > 0:

                        # Profile out the free parameters

                        self._wrapper.set_fixed_values([step1, step2])

                        try:

                            _, this_log_like = self._optimizer.minimize(compute_covar=False)

                        except FitFailed:

                            # If the user is stepping too far it might be that the fit fails. It is usually not a
                            # problem

                            this_log_like = np.nan

                    else:

                        # No free parameters, just compute the likelihood

                        this_log_like = self._function(step1, step2)

                    log_likes[i,j] = this_log_like

                    p.increase()

        return log_likes

# This classes are used directly by the user to have better control on the minimizers.
# They are actually factories

class _Minimization(object):

    def __init__(self, minimizer_type):

        self._minimizer_type = get_minimizer(minimizer_type=minimizer_type)

        self._algorithm = None
        self._setup_dict = {}

    def setup(self, **setup_dict):

        valid_setup_keys = self._minimizer_type.valid_setup_keys

        # Check that the setup has been specified well
        for key in setup_dict.keys():

            assert key in valid_setup_keys, "%s is not a valid setup parameter for this minimizer" % key

        self._setup_dict = setup_dict

    def set_algorithm(self, algorithm):

        # Note that algorithm might be None

        self._algorithm = algorithm

class LocalMinimization(_Minimization):

    def __init__(self, minimizer_type):

        super(LocalMinimization, self).__init__(minimizer_type)

        assert issubclass(self._minimizer_type,
                          LocalMinimizer), "Minimizer %s is not a local minimizer" % minimizer_type

    def get_instance(self, *args, **kwargs):

        instance = self._minimizer_type(*args, **kwargs)

        if self._algorithm is not None:

            instance.set_algorithm(self._algorithm)

        # Set up the minimizer
        instance._setup(self._setup_dict)

        return instance

class GlobalMinimization(_Minimization):

    def __init__(self, minimizer_type):

        super(GlobalMinimization, self).__init__(minimizer_type)

        assert issubclass(self._minimizer_type,
                          GlobalMinimizer), "Minimizer %s is not a local minimizer" % minimizer_type

        self._2nd_minimization = None

    def setup(self, **setup_dict):

        assert 'second_minimization' in setup_dict, "You have to provide a secondary minimizer during setup, " \
                                                    "using the second_minimization keyword"

        self._2nd_minimization = setup_dict['second_minimization']

        super(GlobalMinimization, self).setup(**setup_dict)

    def get_second_minimization_instance(self, *args, **kwargs):

        return self._2nd_minimization.get_instance(*args, **kwargs)

    def get_instance(self, *args, **kwargs):

        instance = self._minimizer_type(*args, **kwargs)

        if self._algorithm is not None:

            instance.set_algorithm(self._algorithm)

        # Set up the minimizer
        instance._setup(self._setup_dict)

        return instance

class Minimizer(object):

    def __init__(self, function, parameters, verbosity=1, setup_dict=None):
        """

        :param function: function to be minimized
        :param parameters: ordered dictionary of the FREE parameters in the fit. The order must be the same as
               in the calling sequence of the function to be minimized.
        :param verbosity: control the verbosity of the output
        :param type: type of the optimizer (use the enums LOCAL_OPTIMIZER or GLOBAL_OPTIMIZER)
        :return:
        """

        self._function = function
        self._external_parameters = parameters
        self._internal_parameters = self._update_internal_parameter_dictionary()
        self._Npar = len(self.parameters.keys())
        self._verbosity = verbosity

        self._setup(setup_dict)

        self._fit_results = None
        self._covariance_matrix = None
        self._correlation_matrix = None

        self._algorithm_name = None
        self._m_log_like_minimum = None

        self._optimizer_type = str(type)

    def _update_internal_parameter_dictionary(self):
        """
        Returns a dictionary parameter_name -> (current value, delta, minimum, maximum) in the internal frame
        (if the parameter has a transformation set).

        This should be used by the implementation of the minimizers to get the parameters to optimize.

        :return: dictionary
        """

        # Prepare the dictionary for the parameters which will be used by iminuit

        internal_parameter_dictionary = collections.OrderedDict()

        # NOTE: we use the internal_ versions of value, min_value and max_value because they don't have
        # units, and they are transformed to make the fit easier (for example in log scale)

        # NOTE as well that as in the entire class here, the .parameters dictionary only contains free parameters,
        # as only free parameters are passed to the constructor of the minimizer

        for k, par in self.parameters.items():

            current_name = par.path

            current_value = par._get_internal_value()
            current_delta = par._get_internal_delta()
            current_min = par._get_internal_min_value()
            current_max = par._get_internal_max_value()

            # Now fix sensible values for parameters deltas

            if current_min is None and current_max is None:

                # No boundaries, use 2% of value as initial delta

                if abs(current_delta) < abs(current_value) * 0.02 or not np.isfinite(current_delta):

                    current_delta = abs(current_value) * 0.02

            elif current_min is not None:

                if current_max is not None:

                    # Bounded in both directions. Use 20% of the value

                    current_delta = abs(current_value) * 0.02

                    # Make sure we do not violate the boundaries
                    current_delta = min(current_delta,
                                        abs(current_value - current_delta) / 10.0,
                                        abs(current_value + current_delta) / 10.0)

                else:

                    # Bounded only in the negative direction. Make sure we are not at the boundary
                    if np.isclose(current_value, current_min, abs(current_value) / 20):

                        custom_warnings.warn("The current value of parameter %s is very close to "
                                             "its lower bound when starting the fit. Fixing it" % par.name)

                        current_value = current_value + 0.1 * abs(current_value)

                        current_delta = 0.05 * abs(current_value)

                    else:

                        current_delta = min(current_delta, abs(current_value - current_min) / 10.0)

            else:

                if current_max is not None:

                    # Bounded only in the positive direction
                    # Bounded only in the negative direction. Make sure we are not at the boundary
                    if np.isclose(current_value, current_max, abs(current_value) / 20):

                        custom_warnings.warn("The current value of parameter %s is very close to "
                                             "its upper bound when starting the fit. Fixing it" % par.name)

                        current_value = current_value - 0.04 * abs(current_value)

                        current_delta = 0.02 * abs(current_value)

                    else:

                        current_delta = min(current_delta, abs(current_max - current_value) / 2.0)

            # Sometimes, if the value was 0, the delta could be 0 as well which would crash
            # certain algorithms
            if current_value == 0:

                current_delta = 0.1

            internal_parameter_dictionary[current_name] = (current_value,
                                                           current_delta,
                                                           current_min,
                                                           current_max)

        return internal_parameter_dictionary

    @property
    def function(self):

        return self._function

    @property
    def parameters(self):

        return self._external_parameters

    @property
    def Npar(self):

        return self._Npar

    @property
    def verbosity(self):

        return self._verbosity

    def _setup(self, setup_dict):

        raise NotImplementedError("You have to implement this.")

    @property
    def algorithm_name(self):

        return self._algorithm_name

    def minimize(self, compute_covar=True):
        """
        Minimize objective function. This call _minimize, which is implemented by each subclass.

        :param compute_covar:
        :return: best fit values (in external reference) and minimum of the objective function
        """

        # Gather the best fit values from the minimizer and the covariance matrix (if provided)

        try:

            internal_best_fit_values, function_minimum = self._minimize()

        except FitFailed:

            raise

        # Check that all values are finite

        # Check that the best_fit_values are finite
        if not np.all(np.isfinite(internal_best_fit_values)):

            raise FitFailed("_Minimization apparently succeeded, "
                            "but best fit values are not all finite: %s" % (internal_best_fit_values))

        # Now set the internal values of the parameters to their best fit values and collect the
        # values in external reference
        external_best_fit_values = []

        for i, parameter in enumerate(self.parameters.values()):

            parameter._set_internal_value(internal_best_fit_values[i])

            external_best_fit_values.append(parameter.value)

        # Now compute the covariance matrix, if requested

        if compute_covar:

            covariance = self._compute_covariance_matrix(internal_best_fit_values)

        else:

            covariance = None

        # Finally store everything

        self._store_fit_results(internal_best_fit_values, function_minimum, covariance)

        return external_best_fit_values, function_minimum

    def _minimize(self):

        # This should return the list of best fit parameters and the minimum of the function

        raise NotImplemented("This is the method of the base class. Must be implemented by the actual minimizer")

    def set_algorithm(self, algorithm):

        raise NotImplementedError("Must be implemented by the actual minimizer if it provides more than one algorithm")

    def _store_fit_results(self, best_fit_values, m_log_like_minimum, covariance_matrix=None):

        self._m_log_like_minimum = m_log_like_minimum

        # Create a pandas DataFrame with the fit results

        values = collections.OrderedDict()
        errors = collections.OrderedDict()

        for i in range(self.Npar):

            name = self.parameters.keys()[i]

            value = best_fit_values[i]

            # Set the parameter to the best fit value (sometimes the optimization happen in a different thread/node,
            # so we need to make sure that the parameter has the best fit value)
            self.parameters.values()[i]._set_internal_value(value)

            if covariance_matrix is not None:

                element = covariance_matrix[i,i]

                if element > 0:

                    error = math.sqrt(covariance_matrix[i, i])

                else:

                    custom_warnings.warn("Negative element on diagonal of covariance matrix", CannotComputeErrors)

                    error = np.nan

            else:

                error = np.nan

            values[name] = value
            errors[name] = error

        data = collections.OrderedDict()
        data['value'] = pd.Series(values)
        data['error'] = pd.Series(errors)

        self._fit_results = pd.DataFrame(data)
        self._covariance_matrix = covariance_matrix

        # Compute correlation matrix

        self._correlation_matrix = np.zeros_like(self._covariance_matrix)

        if covariance_matrix is not None:

            for i in range(self.Npar):

                variance_i = self._covariance_matrix[i,i]

                for j in range(self.Npar):

                    variance_j = self._covariance_matrix[j,j]

                    if variance_i * variance_j > 0:

                        self._correlation_matrix[i,j] = self._covariance_matrix[i,j] / (math.sqrt(variance_i * variance_j))

                    else:

                        # We already issued a warning about this, so let's quietly fail

                        self._correlation_matrix[i, j] = np.nan

    @property
    def fit_results(self):

        return self._fit_results

    @property
    def covariance_matrix(self):

        return self._covariance_matrix

    @property
    def correlation_matrix(self):

        return self._correlation_matrix

    def restore_best_fit(self):
        """
        Reset all the parameters to their best fit value (from the last run fit)

        :return: none
        """

        best_fit_values = self._fit_results['value'].values

        for parameter_name, best_fit_value in zip(self.parameters.keys(), best_fit_values):

            self.parameters[parameter_name]._set_internal_value(best_fit_value)

        # Regenerate the internal parameter dictionary with the new values
        self._internal_parameters = self._update_internal_parameter_dictionary()

    def _compute_covariance_matrix(self, best_fit_values):
        """
        This function compute the approximate covariance matrix as the inverse of the Hessian matrix,
        which is the matrix of second derivatives of the likelihood function with respect to
        the parameters.

        The sqrt of the diagonal of the result is an accurate estimate of the errors only if the
        log.likelihood is parabolic in the neighborhood of the minimum.

        Derivatives are computed numerically.

        :return: the covariance matrix
        """

        minima = map(lambda parameter:parameter.min_value, self.parameters.values())
        maxima = map(lambda parameter: parameter.max_value, self.parameters.values())

        # Check whether some of the minima or of the maxima are None. If they are, set them
        # to a value 1000 times smaller or larger respectively than the best fit.
        # An error of 3 orders of magnitude is not interesting in general, and this is the only
        # way to be able to compute a derivative numerically

        for i in range(len(minima)):

            if minima[i] is None:

                minima[i] = best_fit_values[i] / 1000.0

            if maxima[i] is None:

                maxima[i] = best_fit_values[i] * 1000.0

        # Transform them in np.array

        minima = np.array(minima)
        maxima = np.array(maxima)

        try:

            hessian_matrix = get_hessian(self.function, best_fit_values, minima, maxima)

        except ParameterOnBoundary:

            custom_warnings.warn("One or more of the parameters are at their boundaries. Cannot compute covariance and"
                                 " errors", CannotComputeCovariance)

            n_dim = len(best_fit_values)

            return np.zeros((n_dim,n_dim)) * np.nan

        # Invert it to get the covariance matrix

        try:

            covariance_matrix = np.linalg.inv(hessian_matrix)

        except:

            custom_warnings.warn("Cannot invert Hessian matrix, looks like the matrix is singular")

            n_dim = len(best_fit_values)

            return np.zeros((n_dim, n_dim)) * np.nan

        # Now check that the covariance matrix is semi-positive definite (it must be unless
        # there have been numerical problems, which can happen when some parameter is unconstrained)

        # The fastest way is to try and compute the Cholesky decomposition, which
        # works only if the matrix is positive definite

        try:

            _ = np.linalg.cholesky(covariance_matrix)

        except:

            custom_warnings.warn("Covariance matrix is NOT semi-positive definite. Cannot estimate errors. This can "
                                 "happen for many reasons, the most common being one or more unconstrained parameters",
                                 CannotComputeCovariance)

        return covariance_matrix

    def _get_one_error(self, parameter_name, target_delta_log_like, sign=-1):
        """
        A generic procedure to numerically compute the error for the parameters. You can override this if the
        minimizer provides its own method to compute the error of one parameter. If it provides a method to compute
        all errors are once, override the _get_errors method instead.

        :param parameter_name:
        :param target_delta_log_like:
        :param sign:
        :return:
        """

        # Since the procedure might find a better minimum, we can repeat it
        # up to a maximum of 10 times

        repeats = 0

        while repeats < 10:

            # Let's start optimistic...

            repeat = False

            repeats += 1

            # Restore best fit (which also updates the internal parameter dictionary)

            self.restore_best_fit()

            current_value, current_delta, current_min, current_max = self._internal_parameters[parameter_name]

            best_fit_value = current_value

            if sign == -1:

                extreme_allowed = current_min

            else:

                extreme_allowed = current_max

            # If the parameter has no boundary in the direction we are sampling, put a hard limit on
            # 10 times the current value (to avoid looping forever)

            if extreme_allowed is None:

                extreme_allowed = best_fit_value + sign * 10 * abs(best_fit_value)

            # We need to look for a value for the parameter where the difference between the minimum of the
            # log-likelihood and the likelihood for that value differs by more than target_delta_log_likelihood.
            # This is needed by the root-finding procedure, which needs to know an interval where the biased likelihood
            # function (see below) changes sign

            trials = best_fit_value + sign * np.linspace(0.1, 0.9, 9) * abs(best_fit_value)

            trials = np.append(trials, extreme_allowed)

            # Make sure we don't go below the allowed minimum or above the allowed maximum

            if sign == -1:

                np.clip(trials, extreme_allowed, np.inf, trials)

            else:

                np.clip(trials, -np.inf, extreme_allowed, trials)

            # There might be more than one value which was below the minimum (or above the maximum), so let's
            # take only unique elements

            trials = np.unique(trials)

            trials.sort()

            if sign == -1:

                trials = trials[::-1]

            # At this point we have a certain number of unique trials which always
            # contain the allowed minimum (or maximum)

            minimum_bound = None
            maximum_bound = None

            # Instance the profile likelihood function
            pl = ProfileLikelihood(self, [parameter_name])

            for i, trial in enumerate(trials):

                this_log_like = pl([trial])

                delta = this_log_like - self._m_log_like_minimum

                if delta < -0.1:

                    custom_warnings.warn("Found a better minimum (%.2f) for %s = %s during error "
                                         "computation." % (this_log_like, parameter_name, trial),
                                         BetterMinimumDuringProfiling)

                    xs = map(lambda x:x.value, self.parameters.values())

                    self._store_fit_results(xs, this_log_like, None)

                    repeat = True

                    break

                if delta > target_delta_log_like:

                    bound1 = trial

                    if i > 0:

                        bound2 = trials[i-1]

                    else:

                        bound2 = best_fit_value

                    minimum_bound = min(bound1, bound2)
                    maximum_bound = max(bound1, bound2)

                    repeat = False

                    break

            if repeat:

                # We found a better minimum, restart from scratch

                custom_warnings.warn("Restarting search...", RuntimeWarning)

                continue

            if minimum_bound is None:

                # Cannot find error in this direction (it's probably outside the allowed boundaries)
                custom_warnings.warn("Cannot find boundary for parameter %s" % parameter_name, CannotComputeErrors)

                error = np.nan
                break

            else:

                # Define the "biased likelihood", since brenq only finds zeros of function

                biased_likelihood = lambda x: pl(x) - self._m_log_like_minimum - target_delta_log_like

                try:

                    precise_bound = scipy.optimize.brentq(biased_likelihood,
                                                          minimum_bound,
                                                          maximum_bound,
                                                          xtol=1e-5, maxiter=1000)  #type: float
                except:

                    custom_warnings.warn("Cannot find boundary for parameter %s" % parameter_name, CannotComputeErrors)

                    error = np.nan
                    break

                error = precise_bound - best_fit_value

                break

        return error

    def get_errors(self):
        """
        Compute asymmetric errors using the profile likelihood method (slow, but accurate).

        :return: a dictionary with asymmetric errors for each parameter
        """

        # Restore best fit so error computation starts from there

        self.restore_best_fit()

        # Get errors

        errors_dict = self._get_errors()

        # Transform in external reference if needed

        best_fit_values = self._fit_results['value']

        for par_name, (negative_error, positive_error) in errors_dict.items():

            parameter = self.parameters[par_name]

            if parameter.has_transformation():

                _, negative_error_external = parameter.internal_to_external_delta(best_fit_values[parameter.path],
                                                                                negative_error)

                _, positive_error_external = parameter.internal_to_external_delta(best_fit_values[parameter.path],
                                                                                positive_error)

                errors_dict[par_name] = (negative_error_external, positive_error_external)

            else:

                # No need to transform
                pass

        return errors_dict

    def _get_errors(self):
        """
        Override this method if the minimizer provide a function to get all errors at once. If instead it provides
        a method to get one error at the time, override the _get_one_error method

        :return: a ordered dictionary parameter_path -> (negative_error, positive_error)
        """

        # TODO: options for other significance levels

        target_delta_log_like = 0.5

        errors = collections.OrderedDict()

        with progress_bar(2 * len(self.parameters)) as p:

            for parameter_name in self.parameters:

                negative_error = self._get_one_error(parameter_name, target_delta_log_like, -1)

                p.increase()

                positive_error = self._get_one_error(parameter_name, target_delta_log_like, +1)

                p.increase()

                errors[parameter_name] = (negative_error, positive_error)

        return errors

    def contours(self, param_1, param_1_minimum, param_1_maximum, param_1_n_steps,
                         param_2=None, param_2_minimum=None, param_2_maximum=None, param_2_n_steps=None,
                         progress=True, **options):

            """
            Generate confidence contours for the given parameters by stepping for the given number of steps between
            the given boundaries. Call it specifying only source_1, param_1, param_1_minimum and param_1_maximum to
            generate the profile of the likelihood for parameter 1. Specify all parameters to obtain instead a 2d
            contour of param_1 vs param_2

            :param param_1: name of the first parameter
            :param param_1_minimum: lower bound for the range for the first parameter
            :param param_1_maximum: upper bound for the range for the first parameter
            :param param_1_n_steps: number of steps for the first parameter
            :param param_2: name of the second parameter
            :param param_2_minimum: lower bound for the range for the second parameter
            :param param_2_maximum: upper bound for the range for the second parameter
            :param param_2_n_steps: number of steps for the second parameter
            :param progress: (True or False) whether to display progress or not
            :param log: by default the steps are taken linearly. With this optional parameter you can provide a tuple of
            booleans which specify whether the steps are to be taken logarithmically. For example,
            'log=(True,False)' specify that the steps for the first parameter are to be taken logarithmically, while they
            are linear for the second parameter. If you are generating the profile for only one parameter, you can specify
             'log=(True,)' or 'log=(False,)' (optional)
            :param: parallel: whether to use or not parallel computation (default:False)
            :return: a : an array corresponding to the steps for the first parameter
                     b : an array corresponding to the steps for the second parameter (or None if stepping only in one
                     direction)
                     contour : a matrix of size param_1_steps x param_2_steps containing the value of the function at the
                     corresponding points in the grid. If param_2_steps is None (only one parameter), then this reduces to
                     an array of size param_1_steps.
            """

            # Figure out if we are making a 1d or a 2d contour

            if param_2 is None:

                n_dimensions = 1
                fixed_parameters = [param_1]

            else:

                n_dimensions = 2
                fixed_parameters = [param_1, param_2]

            # Check the options

            p1log = False
            p2log = False

            if 'log' in options.keys():

                assert len(options['log']) == n_dimensions, ("When specifying the 'log' option you have to provide a " +
                                                             "boolean for each dimension you are stepping on.")

                p1log = bool(options['log'][0])

                if param_2 is not None:

                    p2log = bool(options['log'][1])

            # Generate the steps

            if p1log:

                param_1_steps = np.logspace(math.log10(param_1_minimum), math.log10(param_1_maximum),
                                            param_1_n_steps)

            else:

                param_1_steps = np.linspace(param_1_minimum, param_1_maximum,
                                            param_1_n_steps)

            if n_dimensions == 2:

                if p2log:

                    param_2_steps = np.logspace(math.log10(param_2_minimum), math.log10(param_2_maximum),
                                                param_2_n_steps)

                else:

                    param_2_steps = np.linspace(param_2_minimum, param_2_maximum,
                                                param_2_n_steps)

            else:

                # Only one parameter to step through
                # Put param_2_steps as nan so that the worker can realize that it does not have
                # to step through it

                param_2_steps = np.array([np.nan])

            # Define the worker which will compute the value of the function at a given point in the grid

            # Restore best fit

            if self.fit_results is not None:

                self.restore_best_fit()

            else:

                custom_warnings.warn("No best fit to restore before contours computation. "
                                     "Perform the fit before running contours to remove this warnings.")

            pr = ProfileLikelihood(self, fixed_parameters)

            if n_dimensions == 1:

                results = pr.step(param_1_steps)

            else:

                results = pr.step(param_1_steps, param_2_steps)

            # Return results

            return param_1_steps, param_2_steps, np.array(results).reshape((param_1_steps.shape[0],
                                                                            param_2_steps.shape[0]))

class LocalMinimizer(Minimizer):

    pass

class GlobalMinimizer(Minimizer):

    pass

# Check which minimizers are available

try:

    from threeML.minimizer.minuit_minimizer import MinuitMinimizer

except ImportError:

    custom_warnings.warn("Minuit minimizer not available", ImportWarning)

else:

    _minimizers["MINUIT"] = MinuitMinimizer

try:

    from threeML.minimizer.ROOT_minimizer import ROOTMinimizer

except ImportError:

    custom_warnings.warn("ROOT minimizer not available", ImportWarning)

else:

    _minimizers["ROOT"] = ROOTMinimizer

try:

    from threeML.minimizer.pyOpt_minimizer import PyOptMinimizer, _pyopt_algorithms

except ImportError:

    custom_warnings.warn("pyOpt minimizer not available", ImportWarning)

else:

    _minimizers["PYOPT"] = PyOptMinimizer

try:

    from threeML.minimizer.multinest_minimizer import MultinestMinimizer

except ImportError:

    custom_warnings.warn("Multinest minimizer not available", ImportWarning)

else:

    _minimizers["MULTINEST"] = MultinestMinimizer

try:

    from threeML.minimizer.pagmo_minimizer import PAGMOMinimizer

except ImportError:

    custom_warnings.warn("PyGMO is not available", ImportWarning)

else:

    _minimizers["PAGMO"] = PAGMOMinimizer

# Check that we have at least one minimizer available

if len(_minimizers) == 0:

    raise SystemError("You do not have any minimizer available! You need to install at least iminuit.")

# Add the GRID minimizer here since it needs at least one other minimizer

from threeML.minimizer.grid_minimizer import GridMinimizer
_minimizers["GRID"] = GridMinimizer

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Norw. Jl Bot. 20: 1 (1973)

#### Original name
Tyromyces graminicola Murrill, 1915

### Remarks
null


text:
package bolt_test

import (
	"context"
	"testing"

	platform "github.com/influxdata/influxdb"
	"github.com/influxdata/influxdb/kit/prom"
	"github.com/influxdata/influxdb/kit/prom/promtest"
)

func TestInitialMetrics(t *testing.T) {
	client, teardown, err := NewTestClient()
	if err != nil {
		t.Fatalf("unable to setup bolt client: %v", err)
	}
	defer teardown()

	reg := prom.NewRegistry()
	reg.MustRegister(client)

	mfs, err := reg.Gather()
	if err != nil {
		t.Fatal(err)
	}

	metrics := map[string]int{
		"influxdb_organizations_total": 0,
		"influxdb_buckets_total":       0,
		"influxdb_users_total":         0,
		"influxdb_tokens_total":        0,
		"influxdb_dashboards_total":    0,
		"boltdb_reads_total":           0,
	}
	for name, count := range metrics {
		c := promtest.MustFindMetric(t, mfs, name, nil)
		if got := c.GetCounter().GetValue(); int(got) != count {
			t.Errorf("expected %s counter to be %d, got %v", name, count, got)
		}
	}
}

func TestMetrics_Onboarding(t *testing.T) {
	client, teardown, err := NewTestClient()
	if err != nil {
		t.Fatalf("unable to setup bolt client: %v", err)
	}
	defer teardown()

	reg := prom.NewRegistry()
	reg.MustRegister(client)

	ctx := context.Background()
	if _, _ = client.Generate(ctx,
		&platform.OnboardingRequest{
			User:     "u1",
			Password: "password1",
			Org:      "o1",
			Bucket:   "b1",
		}); err != nil {
		t.Fatalf("unable to setup onboarding: %v", err)
	}

	_ = client.CreateDashboard(ctx, &platform.Dashboard{
		OrganizationID: platform.ID(1),
	})

	mfs, err := reg.Gather()
	if err != nil {
		t.Fatal(err)
	}

	metrics := map[string]int{
		"influxdb_organizations_total": 1,
		"influxdb_buckets_total":       1,
		"influxdb_users_total":         1,
		"influxdb_tokens_total":        1,
		"influxdb_dashboards_total":    1,
		"boltdb_reads_total":           1,
	}

	for name, count := range metrics {
		c := promtest.MustFindMetric(t, mfs, name, nil)
		if got := c.GetCounter().GetValue(); int(got) != count {
			t.Errorf("expected %s counter to be %d, got %v", name, count, got)
		}
	}
}


text:
<?php

namespace PhpStormPlugin\units\tests;

use \atoum;

class TestWrongNamespace extends atoum
{

}


text:
#ifndef FLOWLAYOUT_H
#define FLOWLAYOUT_H

#include <QLayout>
#include <QRect>
#include <QStyle>
class FlowLayout : public QLayout
{
public:
    explicit FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1);
    explicit FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1);
    ~FlowLayout();

    void addItem(QLayoutItem *item) Q_DECL_OVERRIDE;
    int horizontalSpacing() const;
    int verticalSpacing() const;
    Qt::Orientations expandingDirections() const Q_DECL_OVERRIDE;
    bool hasHeightForWidth() const Q_DECL_OVERRIDE;
    int heightForWidth(int) const Q_DECL_OVERRIDE;
    int count() const Q_DECL_OVERRIDE;
    QLayoutItem *itemAt(int index) const Q_DECL_OVERRIDE;
    QSize minimumSize() const Q_DECL_OVERRIDE;
    void setGeometry(const QRect &rect) Q_DECL_OVERRIDE;
    QSize sizeHint() const Q_DECL_OVERRIDE;
    QLayoutItem *takeAt(int index) Q_DECL_OVERRIDE;

private:
    int doLayout(const QRect &rect, bool testOnly) const;
    int smartSpacing(QStyle::PixelMetric pm) const;

    QList<QLayoutItem *> itemList;
    int m_hSpace;
    int m_vSpace;
};

#endif // FLOWLAYOUT_H


text:
## Overview

bwstreams is a Python 2 Google App Engine app that tracks Brood War streams from [AfreecaTV](http://afreecatv.com). See it live at https://bwstreams.appspot.com.

## Running the development server

1. Install the [Google Cloud SDK](https://cloud.google.com/appengine/docs/standard/python/download)
2. Open Google Cloud SDK Shell
3. Downgrade gcloud version (later versions are broken!): gcloud components update --version 359.0.0
4. Run dev_appserver.bat (or run the command ``dev_appserver.py app.yaml`` using Python 2)

### Useful Google Cloud Commands
- gcloud app versions list
- gcloud app versions delete
- gcloud meta list-files-for-upload
- gcloud app deploy

## Adding streams

Visit http://localhost:8080/admin/initialise_database to initialise a new database from a [preset list](afreeca_database.json), .

Use the admin control panel http://localhost:8080/admin.html to add, edit or remove streams.

## Triggering an update

The app refreshes stream information [every minute](cron.yaml). Visit http://localhost:8080/admin/update_database to manually trigger a refresh.

## Stream information (JSON)

All the stream information can be found at http://localhost:8080/streams.json.

## Summary of links

| Description               | Local Dev Link                                    | Hosted Link                                               |
| --                        | --                                                | --                                                        |
| Main page                 | http://localhost:8080                             | https://bwstreams.appspot.com                             |
| Stream list (barebones)   | http://localhost:8080/afreeca_database.json       | https://bwstreams.appspot.com/afreeca_database.json       |
| Initialise database       | http://localhost:8080/admin/initialise_database   | https://bwstreams.appspot.com/admin/initialise_database   |
| Admin control panel       | http://localhost:8080/admin.html                  | https://bwstreams.appspot.com/admin.html                  |
| Trigger update            | http://localhost:8080/admin/update_database       | https://bwstreams.appspot.com/admin/update_database       |
| Stream information        | http://localhost:8080/streams.json                | https://bwstreams.appspot.com/streams.json                |


text:
package com.bitdecay.game.system;

import com.bitdecay.game.component.FollowOtherPositionComponent;
import com.bitdecay.game.component.PositionComponent;
import com.bitdecay.game.gameobject.MyGameObject;
import com.bitdecay.game.room.AbstractRoom;
import com.bitdecay.game.system.abstracted.AbstractForEachUpdatableSystem;

/**
 * Created by Monday on 4/23/2017.
 */
public class FollowPositionSystem extends AbstractForEachUpdatableSystem {
    public FollowPositionSystem(AbstractRoom room) {
        super(room);
    }

    @Override
    protected void forEach(float delta, MyGameObject gob) {
        gob.forEachComponentDo(FollowOtherPositionComponent.class, follow -> { gob.forEachComponentDo(PositionComponent.class, pos -> {
            pos.set(follow.pos.toVector2());
        });});
    }

    @Override
    protected boolean validateGob(MyGameObject gob) {
        return gob.hasComponents(
                PositionComponent.class,
                FollowOtherPositionComponent.class);
    }
}


text:
foo = function() {}

blah();

foo(function blah(){console.log(true)})

function blah(){console.log(false)}


text:
/* UI Bootstrap */

/* carousel */
.carousel-container {
  height: 400px;
}
.carousel, .item {
  height:100%;
}
.carousel-inner{
  height:100%;
}
.carousel-inner .fill{
  width:100%;
  height:100%;
  background-position:center;
  background-size:cover;
}

/* typeahead */
.typeahead-demo .custom-popup-wrapper {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1000;
  display: none;
  background-color: #f9f9f9;
}
.typeahead-demo .custom-popup-wrapper > .message {
  padding: 10px 20px;
  border-bottom: 1px solid #ddd;
  color: #868686;
}
.typeahead-demo .custom-popup-wrapper > .dropdown-menu {
  position: static;
  float: none;
  display: block;
  min-width: 160px;
  background-color: transparent;
  border: none;
  border-radius: 0;
  box-shadow: none;
}


text:
Deface::Override.new(virtual_path: "spree/admin/shared/_configuration_menu",
                     name: "print_invoice_admin_configurations_menu",
                     insert_bottom: "[data-hook='admin_configurations_sidebar_menu'], #admin_configurations_sidebar_menu[data-hook]",
                     text: "<%= configurations_sidebar_menu_item Spree.t(:settings, scope: :print_invoice), edit_admin_print_invoice_settings_path %>",
                     disabled: false)


text:
using System.Collections.Generic;
using Mail2Bug.Email.EWS;
using Mail2Bug.ExceptionClasses;
using Mail2Bug.Helpers;
using Microsoft.Exchange.WebServices.Data;

namespace Mail2Bug.Email
{
    /// <summary>
    ///  The goal of the MailboxManagerFactory is to separate concerns from the Mail2BugEngine - this way it does not need
    /// to be aware of the specific implementation of the EMail layer, as long as it supports the IMailboxManager interface
    /// </summary>
    class MailboxManagerFactory
    {
        public MailboxManagerFactory(EWSConnectionManger connectionManger)
        {
            _connectionManger = connectionManger;
        }

        public IMailboxManager CreateMailboxManager(Config.EmailSettings emailSettings)
        {
            var credentials = new EWSConnectionManger.Credentials
            {
                EmailAddress = emailSettings.EWSMailboxAddress,
                UserName = emailSettings.EWSUsername,
                Password = DPAPIHelper.ReadDataFromFile(emailSettings.EWSPasswordFile)
            };

            var exchangeService = _connectionManger.GetConnection(credentials, emailSettings.UseConversationGuidOnly);
            var postProcessor = GetPostProcesor(emailSettings, exchangeService.Service);

            switch (emailSettings.ServiceType)
            {
                case Config.EmailSettings.MailboxServiceType.EWSByFolder:
                    return new FolderMailboxManager(
                        exchangeService.Service,
                        emailSettings.IncomingFolder,
                        postProcessor);

                case Config.EmailSettings.MailboxServiceType.EWSByRecipients:

                    return new RecipientsMailboxManager(
                        exchangeService.Router,
                        ParseDelimitedList(emailSettings.Recipients, ';'),
                        postProcessor);

                default:
                    throw new BadConfigException(
                        "EmailSettings.ServiceType",
                        string.Format("Invalid mailbox service type defined in config ({0})", emailSettings.ServiceType));
            }
        }

        private static IMessagePostProcessor GetPostProcesor(Config.EmailSettings emailSettings, ExchangeService service)
        {
            if (string.IsNullOrEmpty(emailSettings.CompletedFolder) || string.IsNullOrEmpty(emailSettings.ErrorFolder))
            {
                return new DeleterMessagePostProcessor();
            }

            return new ArchiverMessagePostProcessor(emailSettings.CompletedFolder, emailSettings.ErrorFolder, service);
        }

        private static IEnumerable<string> ParseDelimitedList(string text, char delimiter)
        {
            if (string.IsNullOrEmpty(text))
            {
                return new string[0];
            }

            return text.Split(delimiter);
        }

        // Enable connection caching for performance improvement when hosting multiple instances
        private readonly EWSConnectionManger _connectionManger;
    }
}