text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import numpy as np

from ... import OPT_DEPS

if OPT_DEPS['MATPLOTLIB']:  # pragma: no cover
    import matplotlib.pyplot as plt
    if not OPT_DEPS['WCSAXES']:
        __doctest_skip__ = ['NDPlottingMixin.plot_add_wcs_axes',
                            'NDPlottingMixin.plot_add_wcs_subplot',
                            'NDPlottingMixin.plot_add_wcs_labels']
else:  # pragma: no cover
    __doctest_skip__ = ['*']

__all__ = ['NDPlottingMixin']

class NDPlottingMixin(object):
    """Mixin to allow interaction with matplotlib to create plots and images.

    These are meant for interactive use and only provide a subset of possible
    features.
    """
    def plot_add_wcs_axes(self, *args, **kwargs):
        """Create an `matplotlib.axes.Axes` with ``wcs`` projection.

        .. note::
            `wcsaxes` must be installed and the ``wcs`` of the instance must be
            an `~astropy.wcs.WCS` object (or the equivalent from wcsaxes).

        Parameters
        ----------
        args, kwargs :
            Parameter for :func:`matplotlib.pyplot.axes`. The **projection**
            will be set automatically.

        Returns
        -------
        ax : `matplotlib.axes.Axes`
            The created axes.

        Notes
        -----
        This function adds the saved ``wcs`` as **projection** parameter and
        calls :func:`matplotlib.pyplot.axes`.

        See also
        --------
        plot_add_wcs_subplot

        Examples
        --------

        .. plot::
            :include-source:

            >>> from nddata.nddata import NDData
            >>> import numpy as np
            >>> from nddata.utils.numpyutils import mgrid_for_array
            >>> from astropy.modeling.functional_models import Gaussian2D
            >>> from astropy.wcs import WCS
            >>> # Create some data
            >>> data = Gaussian2D(amplitude=100, x_mean=7, x_stddev=20,
            ...                   y_mean=5, y_stddev=40)
            >>> data = data(*mgrid_for_array(np.empty((100, 100))))
            >>> # Setup some basic wcs
            >>> wcs = WCS(naxis=2)
            >>> wcs.wcs.crpix = [-234, 10]
            >>> wcs.wcs.cdelt = [1, 1]
            >>> wcs.wcs.crval = [0, -45]
            >>> wcs.wcs.ctype = ["RA---AIR", "DEC--AIR"]
            >>> wcs.wcs.cunit = ["deg", "deg"]
            >>> # Create an instance and plot it
            >>> ndd = NDData(data, wcs=wcs)
            >>> ax = ndd.plot_add_wcs_axes()               # adds a plot
            >>> ndd.plot_add_wcs_labels()                  # adds ticks, grid
            >>> im = ndd.plot_imshow()                     # plot the image
            >>> cs = ndd.plot_contour(levels=[10, 20, 50]) # plot contours

        .. note::
            `wcsaxes` doesn't support distortions in the ``wcs``.
        """
        kwargs['projection'] = self.wcs
        return plt.axes(*args, **kwargs)

    def plot_add_wcs_subplot(self, *args, **kwargs):
        """Create an `matplotlib.axes.Axes` as subplot with ``wcs`` projection.

        .. note::
            `wcsaxes` must be installed and the ``wcs`` of the instance must be
            an `~astropy.wcs.WCS` object (or the equivalent from wcsaxes).

        Parameters
        ----------
        args, kwargs :
            Parameter for :func:`matplotlib.pyplot.subplot`. The **projection**
            will be set automatically.

        Returns
        -------
        ax : `matplotlib.axes.Axes`
            The created axes.

        Notes
        -----
        This function adds the saved ``wcs`` as **projection** parameter and
        calls :func:`matplotlib.pyplot.subplot`.

        See also
        --------
        plot_add_wcs_axes

        Examples
        --------

        .. plot::
            :include-source:

            >>> from nddata.nddata import NDData
            >>> import numpy as np
            >>> from nddata.utils.numpyutils import mgrid_for_array
            >>> from astropy.modeling.functional_models import AiryDisk2D
            >>> from astropy.wcs import WCS
            >>> # Create some data
            >>> data = AiryDisk2D(amplitude=1000, x_0=40, y_0=40, radius=20)
            >>> data = data(*mgrid_for_array(np.empty((100, 100))))
            >>> # Setup some basic wcs
            >>> wcs = WCS(naxis=2)
            >>> wcs.wcs.crpix = [-234, 10]
            >>> wcs.wcs.cdelt = [1, 1]
            >>> wcs.wcs.crval = [0, -45]
            >>> wcs.wcs.ctype = ["RA---AIR", "DEC--AIR"]
            >>> wcs.wcs.cunit = ["deg", "deg"]
            >>> ndd = NDData(data, wcs=wcs)
            >>> # Split it into two and plot them in one figure:
            >>> ndd1 = ndd[:, :50]
            >>> ndd2 = ndd[:, 50:]
            >>> # Plot left part
            >>> ax1 = ndd1.plot_add_wcs_subplot(1, 2, 1)
            >>> ndd1.plot_add_wcs_labels()
            >>> im = ndd1.plot_imshow()
            >>> # Plot right part
            >>> ax2 = ndd2.plot_add_wcs_subplot(1, 2, 2)
            >>> ndd2.plot_add_wcs_labels()
            >>> im = ndd2.plot_imshow()

        .. note::
            `wcsaxes` doesn't support distortions in the ``wcs``.
        """
        kwargs['projection'] = self.wcs
        return plt.subplot(*args, **kwargs)

    def plot_add_wcs_labels(self, ax=None):
        """Add labels for the axis and display the grid.

        Parameters
        ----------
        ax : `wcsaxes.WCSAxes` or `None`, optional
            If ``None`` operate on the currently active axes otherwise operate
            on the ``axes`` given.
            Default is ``None``.

        Notes
        -----
        A white ``grid`` is enabled and the axis will be labelled according to
        the ``ctype`` of the saved ``wcs``.

        Examples
        --------

        .. plot::
            :include-source:

            >>> from nddata.nddata import NDData
            >>> import numpy as np
            >>> from nddata.utils.numpyutils import mgrid_for_array
            >>> from astropy.modeling.functional_models import AiryDisk2D
            >>> from astropy.wcs import WCS
            >>> # Create some data
            >>> data = AiryDisk2D(amplitude=1000, x_0=40, y_0=40, radius=20)
            >>> data = data(*mgrid_for_array(np.empty((100, 100))))
            >>> # Setup some basic wcs
            >>> wcs = WCS(naxis=2)
            >>> wcs.wcs.crpix = [-234, 10]
            >>> wcs.wcs.cdelt = [1, 1]
            >>> wcs.wcs.crval = [0, -45]
            >>> wcs.wcs.ctype = ["RA---AIR", "DEC--AIR"]
            >>> wcs.wcs.cunit = ["deg", "deg"]
            >>> ndd = NDData(data, wcs=wcs)
            >>> # Plot it two times without (left) and with (right) labels.
            >>> # Left image
            >>> ax1 = ndd.plot_add_wcs_subplot(1, 2, 1)
            >>> im = ndd.plot_imshow()
            >>> cs = ndd.plot_contour(levels=[10])
            >>> # Right image
            >>> ax2 = ndd.plot_add_wcs_subplot(1, 2, 2)
            >>> ndd.plot_add_wcs_labels()
            >>> im = ndd.plot_imshow()
            >>> cs = ndd.plot_contour(levels=[10])
        """
        if ax is None:
            ax = plt.gca()
        ax.coords.grid(color='white')
        ax.coords[0].set_axislabel(self.wcs.wcs.ctype[0])
        ax.coords[1].set_axislabel(self.wcs.wcs.ctype[1])

    def plot_imshow(self, ax=None, **kwargs):
        """:func:`matplotlib.pyplot.imshow` wrapper.

        Parameters
        ----------
        ax : `matplotlib.axes.Axes` or `None`, optional
            If ``None`` operate on the currently active axes otherwise operate
            on the ``axes`` given.
            Default is ``None``.

        kwargs :
            Parameters passed to :func:`matplotlib.pyplot.imshow`.

        Returns
        -------
        imshow : any type
            Whatever the wrapped ``Matplotlib`` function returns.

        Notes
        -----
        This method wraps :func:`matplotlib.pyplot.imshow` by providing some
        fixed parameters:

        - **data** : ``data`` saved in the instance.

        And some default parameters that can be overridden:

        - **origin** : ``"lower"``
        - **interpolation** : ``"none"``
        - **cmap** : ``matplotlib.pyplot.cm.gray``

        Examples
        --------

        .. plot::
            :include-source:

            >>> from nddata.nddata import NDData
            >>> import numpy as np
            >>> from nddata.utils.numpyutils import mgrid_for_array
            >>> from astropy.modeling.functional_models import AiryDisk2D
            >>> import matplotlib.pyplot as plt
            >>> # Create some data
            >>> data = AiryDisk2D(amplitude=1000, x_0=40, y_0=40, radius=20)
            >>> data = data(*mgrid_for_array(np.empty((100, 100))))
            >>> ndd = NDData(data)
            >>> # Create one ndd without mask and one with mask
            >>> ndd2 = ndd.copy()
            >>> mask = np.zeros((100, 100), dtype=bool)
            >>> mask[30:50, 30:50] = 1
            >>> ndd2.mask = mask
            >>> # Create an image with the unmasked (left) data.
            >>> ax1 = plt.subplot(1, 2, 1)
            >>> im = ndd.plot_imshow()
            >>> # and masked (right) data.
            >>> ax2 = plt.subplot(1, 2, 2)
            >>> im = ndd2.plot_imshow()

        .. note::
            If you have a ``mask`` consider convolving the image before
            plotting it to avoid these blank spaces.
        """
        if ax is None:
            ax = plt.gca()

        # Default set of parameters.
        dkwargs = {'origin': 'lower',
                   'interpolation': 'none',
                   'cmap': plt.cm.gray}
        # Update the default parameters by the explicitly given ones. Note that
        # this way the defaults can be overridden. Do not use:
        # kwargs.update(dkwargs) because that would override explicitly given
        # parameters.
        dkwargs.update(kwargs)

        # imshow doesn't support a grid but it can "handle" (not really but at
        # least it tries to do) masked arrays.
        return ax.imshow(self._plotting_get_masked_data(), **dkwargs)

    def plot_contour(self, ax=None, **kwargs):
        """:func:`matplotlib.pyplot.contour` wrapper.

        Parameters
        ----------
        ax : `matplotlib.axes.Axes` or `None`, optional
            If ``None`` operate on the currently active axes otherwise operate
            on the ``axes`` given.
            Default is ``None``.

        Returns
        -------
        contour : any type
            Whatever the wrapped ``Matplotlib`` function returns.

        Notes
        -----
        This method wraps :func:`matplotlib.pyplot.contour` by providing some
        fixed parameters:

        - **data** : ``data`` saved in the instance.

        And some default parameters that can be overridden:

        - **colors** : ``"white"``
        - **alpha** : ``0.5``

        See also
        --------
        nddata.utils.stats.minmax : To provide ``levels`` based on \
            :func:`numpy.linspace` or :func:`numpy.logspace`.

        Examples
        --------

        .. plot::
            :include-source:

            >>> from nddata.nddata import NDData
            >>> import numpy as np
            >>> from nddata.utils.numpyutils import mgrid_for_array
            >>> from astropy.modeling.functional_models import AiryDisk2D
            >>> import matplotlib.pyplot as plt
            >>> # Create some data
            >>> data = AiryDisk2D(amplitude=1000, x_0=40, y_0=40, radius=20)
            >>> data = data(*mgrid_for_array(np.empty((100, 100))))
            >>> ndd = NDData(data)
            >>> # Create one ndd without mask and one with mask
            >>> ndd2 = ndd.copy()
            >>> mask = np.zeros((100, 100), dtype=bool)
            >>> mask[30:50, 30:50] = 1
            >>> ndd2.mask = mask
            >>> # Create a contour with the unmasked (left) data.
            >>> from nddata.utils.stats import minmax
            >>> min_, max_ = minmax(ndd.data)
            >>> logspace = np.linspace(min_, max_, num=10)
            >>> ax1 = plt.subplot(1, 2, 1)
            >>> im = ndd.plot_contour(levels=logspace, colors='black')
            >>> # and masked (right) data
            >>> ax2 = plt.subplot(1, 2, 2)
            >>> im = ndd2.plot_contour(levels=logspace, colors='black')

        .. note::
            If you have a ``mask`` consider convolving the image before
            plotting it to avoid these blank spaces.
        """
        if ax is None:
            ax = plt.gca()

        dkwargs = {'colors': 'white',
                   'alpha': 0.5}
        dkwargs.update(kwargs)

        # Contour takes the data as grid of x, y and z coordinates.
        return ax.contour(self._plotting_get_masked_data(), **dkwargs)

    def plot_hist(self, ax=None, **kwargs):
        """:func:`matplotlib.pyplot.hist` wrapper.

        .. note::
            The data is always ravelled (flattened to one dimension) before the
            histogram is created.

        Parameters
        ----------
        ax : `matplotlib.axes.Axes` or `None`, optional
            If ``None`` operate on the currently active axes otherwise operate
            on the ``axes`` given.
            Default is ``None``.

        Returns
        -------
        histogram : any type
            Whatever the wrapped ``Matplotlib`` function returns.

        Notes
        -----
        This method wraps :func:`matplotlib.pyplot.hist` by providing some
        fixed parameters:

        - **data** : ``data`` saved in the instance.

        And some default parameters that can be overridden:

        - **facecolor** : ``"black"``
        - **alpha** : ``0.5``

        See also
        --------
        nddata.utils.stats.minmax : To provide ``bins`` based on \
            :func:`numpy.arange`.

        Examples
        --------

        .. plot::
            :include-source:

            >>> from nddata.nddata import NDData
            >>> import numpy as np
            >>> import matplotlib.pyplot as plt
            >>> # Create some data
            >>> data = np.random.normal(10, 2, (200, 200))
            >>> ndd1 = NDData(data)
            >>> # Create one ndd without mask and one with mask
            >>> ndd2 = ndd1.copy()
            >>> ndd2.clip_sigma(sigma=2)
            >>> # Create an image with the unmasked (left) data.
            >>> from nddata.utils.stats import minmax
            >>> min_, max_ = minmax(ndd1.data)
            >>> bins = np.arange(int(min_)-0.5, int(max_)+1.5, 1)
            >>> ax1 = plt.subplot(1, 2, 1)
            >>> im = ndd1.plot_hist(bins=bins)
            >>> # and masked (right) data
            >>> ax2 = plt.subplot(1, 2, 2)
            >>> im = ndd2.plot_hist(bins=bins)
        """
        if ax is None:
            ax = plt.gca()

        dkwargs = {'facecolor': 'black',
                   'alpha': 0.5}
        dkwargs.update(kwargs)

        data = self._plotting_get_masked_data()
        data = data.data[~data.mask]

        # Contour takes the data as grid of x, y and z coordinates.
        return ax.hist(data, **dkwargs)

    def _plotting_get_masked_data(self):
        """Returns a masked array if a mask is present otherwise just returns
        the data.
        """
        return np.ma.array(self.data, mask=self._get_mask_numpylike())


text:
2015 Fall Semester Hadoop and Spark Workshop by [Min Li](http://www.s3lab.ece.ufl.edu/)

The files here are all the code from the Hadoop and Spark workshop held on 11/5/2015.
The data and Hadoop and Spark programs are not included here. They are packaged with the
virtual machine which can be downloaded from
[http://python.acis.ufl.edu/2015-Fal-Hadoop/](http://python.acis.ufl.edu/2015-Fal-Hadoop/)

redpajama_set_name: RedPajamaGithub


text:
package nl.esciencecenter.xenon.adaptors.shared.local;

import org.junit.Test;

public class LocalUtilFixedClientTest {

    @Test
    public void test_move() {

    }
}


text:
/* */
var baseToString = require('../internal/baseToString'),
    escapeRegExpChar = require('../internal/escapeRegExpChar');
var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,
    reHasRegExpChars = RegExp(reRegExpChars.source);
function escapeRegExp(string) {
  string = baseToString(string);
  return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, escapeRegExpChar) : (string || '(?:)');
}
module.exports = escapeRegExp;


text:
/*************************************************************************/
/*  button_array.h                                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#ifndef BUTTON_ARRAY_H
#define BUTTON_ARRAY_H

#include "scene/gui/control.h"

class ButtonArray : public Control {

	OBJ_TYPE(ButtonArray, Control);
public:
	enum Align {
		ALIGN_BEGIN,
		ALIGN_CENTER,
		ALIGN_END,
		ALIGN_FILL,
		ALIGN_EXPAND_FILL
	};
private:

	Orientation orientation;
	Align align;

	struct Button {

		String text;
		Ref<Texture> icon;
		mutable int _ms_cache;
		mutable int _pos_cache;
		mutable int _size_cache;
	};

	int selected;
	int hover;
	double min_button_size;

	Vector<Button> buttons;
protected:

	bool _set(const StringName& p_name, const Variant& p_value);
	bool _get(const StringName& p_name,Variant &r_ret) const;
	void _get_property_list( List<PropertyInfo> *p_list) const;

	void _notification(int p_what);
	static void _bind_methods();

public:

	void _input_event(const InputEvent& p_event);

	void set_align(Align p_align);
	Align get_align() const;

	void add_button(const String& p_button);
	void add_icon_button(const Ref<Texture>& p_icon,const String& p_button="");

	void set_button_text(int p_button, const String& p_text);
	void set_button_icon(int p_button, const Ref<Texture>& p_icon);

	String get_button_text(int p_button) const;
	Ref<Texture> get_button_icon(int p_button) const;

	int get_selected() const;
	int get_hovered() const;
	void set_selected(int p_selected);

	int get_button_count() const;

	void erase_button(int p_button);
	void clear();

	virtual Size2 get_minimum_size() const;

	virtual void get_translatable_strings(List<String> *p_strings) const;

	ButtonArray(Orientation p_orientation=HORIZONTAL);
};

class HButtonArray : public ButtonArray {
	OBJ_TYPE(HButtonArray,ButtonArray);
public:

	HButtonArray() : ButtonArray(HORIZONTAL) {};
};

class VButtonArray : public ButtonArray {
	OBJ_TYPE(VButtonArray,ButtonArray);
public:

	VButtonArray() : ButtonArray(VERTICAL) {};
};

#endif // BUTTON_ARRAY_H


text:
#region Using Directives

using System;
using System.Runtime.InteropServices;

#endregion

namespace GPhoto.Interop
{
    /// <summary>
    /// Represents a class that contains the interop code for the native functions for managing port info lists. Port info lists are lists that
    /// contain port info objects, which themselves represent information about the port (e.g., USB, serial port, IP, etc.) via which devices (cameras
    /// as well as other devices) are connected to the system.
    /// </summary>
    internal static class PortInfoListInterop
    {
        #region Public Static Methods

        /// <summary>
        /// Creates a new list which can later be filled with port infos.
        /// </summary>
        /// <param name="list">A pointer to the port info list that will be allocated.</param>
        /// <returns>Returns a gPhoto2 error code.</returns>
        [DllImport("gphoto2")]
        public static extern ErrorCode gp_port_info_list_new(out IntPtr list);

        /// <summary>
        /// Searches the system for IO-drivers and appends them to the list. You would normally call this function once after
        /// <see cref="gp_port_info_list_new"/> and then use this list in order to supply <see cref="gp_port_set_info"/> with parameters or to do
        /// autodetection.
        /// </summary>
        /// <param name="list">A port info list that was previously created using <see cref="gp_port_info_list_new"/>.</param>
        /// <returns>Returns a gPhoto2 error code.</returns>
        [DllImport("gphoto2")]
        public static extern ErrorCode gp_port_info_list_load(IntPtr list);

        /// <summary>
        /// Frees a port info list structure and its internal data structures.
        /// </summary>
        /// <param name="list">The port info list that is to be freed.</param>
        /// <returns>Returns a gPhoto2 error code.</returns>
        [DllImport("gphoto2")]
        public static extern ErrorCode gp_port_info_list_free(IntPtr list);

        /// <summary>
        /// Retrieves the number of entries in the passed list.
        /// </summary>
        /// <param name="list">The port info list for which the number of entries is to be retrieved.</param>
        /// <returns>Returns the number of entries or a gPhoto2 error code</returns>
        [DllImport("gphoto2")]
        public static extern int gp_port_info_list_count(IntPtr list);

        /// <summary>
        /// Retrieves the port information of specific entry of the port info list.
        /// </summary>
        /// <param name="list">A port info list from which the specified entry is to be retrieved.</param>
        /// <param name="n">The index of the entry that is to be retrieved.</param>
        /// <param name="info">A pointer to a port info, which will receive the port info of the entry.</param>
        /// <returns>Returns a gPhoto2 error code.</returns>
        [DllImport("gphoto2")]
        public static extern ErrorCode gp_port_info_list_get_info(IntPtr list, int n, out IntPtr info);

        #endregion
    }
}


text:
<?php

namespace Drupal\entity_browser\Wizard;

use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\ctools\Wizard\EntityFormWizardBase;
use Drupal\entity_browser\Form\DisplayConfig;
use Drupal\entity_browser\Form\GeneralInfoConfig;
use Drupal\entity_browser\Form\SelectionDisplayConfig;
use Drupal\entity_browser\Form\WidgetsConfig;
use Drupal\entity_browser\Form\WidgetSelectorConfig;
use Drupal\user\SharedTempStoreFactory;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Custom form wizard for entity browser configuration.
 */
class EntityBrowserWizard extends EntityFormWizardBase {

  /**
   * @param \Drupal\user\SharedTempStoreFactory $tempstore
   *   Tempstore Factory for keeping track of values in each step of the
   *   wizard.
   * @param \Drupal\Core\Form\FormBuilderInterface $builder
   *   The Form Builder.
   * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
   *   The class resolver.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   The event dispatcher.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   * @param $tempstore_id
   *   The shared temp store factory collection name.
   * @param null $machine_name
   *   The SharedTempStore key for our current wizard values.
   * @param null $step
   *   The current active step of the wizard.
   */
  public function __construct(SharedTempStoreFactory $tempstore, FormBuilderInterface $builder, ClassResolverInterface $class_resolver, EventDispatcherInterface $event_dispatcher, EntityManagerInterface $entity_manager, RouteMatchInterface $route_match, $tempstore_id, $entity_browser = NULL, $step = 'general') {
    parent::__construct($tempstore, $builder, $class_resolver, $event_dispatcher, $entity_manager, $route_match, $tempstore_id, $entity_browser, $step);
  }

  /**
   * {@inheritdoc}
   */
  public function getNextParameters($cached_values) {
    $parameters = parent::getNextParameters($cached_values);
    $parameters['entity_browser'] = $parameters['machine_name'];
    unset($parameters['machine_name']);
    return $parameters;
  }

  /**
   * {@inheritdoc}
   */
  public function getPreviousParameters($cached_values) {
    $parameters = parent::getPreviousParameters($cached_values);
    $parameters['entity_browser'] = $parameters['machine_name'];
    unset($parameters['machine_name']);
    return $parameters;
  }

  /**
   * {@inheritdoc}
   */
  public function getWizardLabel() {
    return $this->t('Entity browser');
  }

  /**
   * {@inheritdoc}
   */
  public function getMachineLabel() {
    return $this->t('Label');
  }

  /**
   * {@inheritdoc}
   */
  public function getEntityType() {
    return 'entity_browser';
  }

  /**
   * {@inheritdoc}
   */
  public function exists() {
    return 'Drupal\entity_browser\Entity\EntityBrowser::load';
  }

  /**
   * {@inheritdoc}
   */
  public function getOperations($cached_values) {
    return [
      'general' => [
        'title' => $this->t('General information'),
        'form' => GeneralInfoConfig::class,
      ],
      'display' => [
        'title' => $this->t('Display'),
        'form' => DisplayConfig::class,
      ],
      'widget_selector' => [
        'title' => $this->t('Widget selector'),
        'form' => WidgetSelectorConfig::class,
      ],
      'selection_display' => [
        'title' => $this->t('Selection display'),
        'form' => SelectionDisplayConfig::class,
      ],
      'widgets' => [
        'title' => $this->t('Widgets'),
        'form' => WidgetsConfig::class,
      ],
    ];
  }

}


text:
Target derivation
=================

Unpoly often needs to guess a CSS selector that will [match an element](/targeting-fragments). This is called *target derivation*.

In the example below Unpoly derives a target selector for an element that is being reloaded:

```js
let element = document.querySelector('#foo')
up.reload(element) // Derives the target '#foo' from the given element
```

Popular features that must derive targets are `[up-poll]`,  `[up-hungry]`, `[up-viewport]`, [`up.reload(Element)`](/up.reload) and [`up.render(Element)`](/up.render).

To build a good selector, the element needs an **identifying property** that distinguishes it from other elements on the same [layer](/up.layer). The most important properties that Unpoly looks for are the following:

- The element's `[id]` or `[up-id]` attribute
- The tag name of a page-unique element (`<html>`, `<head>`, `<body>`, `<main>`)
- The element's `[name]` attribute
- The element's combined `[class]` names, ignoring `up.fragment.config.badTargetClasses`.

When none of these properties are found, Unpoly will attempt [additional derivation patterns](#derivation-patterns) to come up with a good selector before giving up.

Sometimes you may find that Unpoly cannot derive a good target for an element, or that the derived target matches the wrong element. In such cases consider giving your element an `[id]` property, which is HTML's standard way of identifying an element on the page.

Derivation patterns
-------------------

Unpoly lets you configure patterns for target derivation in `up.fragment.config.targetDerivers`.

By default the following patterns are configured, with decreasing priority. Examples for selectors produced can be found in comments:

```js
up.fragment.config.targetDerivers = [
  '[up-id]',         // [up-id="foo"]
  '[id]',            // #foo
  'html',            // html
  'head',            // head
  'body',            // body
  'main',            // main
  '[up-main]',       // [up-main="root"]
  'link[rel]',       // link[rel="canonical"]
  'meta[property]',  // meta[property="og:title"]
  '*[name]',         // input[name="email"]
  'form[action]',    // form[action="/users"]
  'a[href]',         // a[href="/users/"]
  '[class]',         // .foo (filtered by up.fragment.config.badTargetClasses)
  'form',            // form
]
```

Only applicable pattern will produce a target. E.g. the pattern `'link[rel]'` only applies to `<link rel="...">` elements and will be ignored for anything else.

Note how any attribute in a pattern is expanded to include an element's actual attribute value. E.g. the pattern `a[href]` produces a target like `a[href="/users"]`.
Similarily the asterisk (`*`) will be expanded to the element's actual tag name.

If your deriver can't be expressed in a pattern string, you may also push a `Function(Element): string?`.

Derived target verification
---------------------------

Unpoly verifies if a derived targets will actually match the element. If another element is matched, the next applicable pattern in `up.fragment.config.targetDerivers` is tested.

If no pattern produces a matching target, an error `up.CannotTarget` is thrown. In such cases consider setting an `[id]` attribute, or configure a new [derivation pattern](#derivation-patterns).

Target verification may be [disabled](/up.fragment.config#config.verifyDerivedTarget), which is almost always a bad idea.

Deriving a target programmatically
----------------------------------

Your JavaScript can use `up.fragment.toTarget()` to derive a target from an element:

```js
element = up.element.createFromHTML('<span class="klass">...</span>')
selector = up.fragment.toTarget(element) // returns '.klass'
```

If no [verified](#derived-target-verification) target can be derived, an error `up.CannotTarget` is thrown.

To test if a selector can be derived from a target, use `up.fragment.isTargetable()`.

@page target-derivation


text:
from eventlet import hubs
from eventlet.support import greenlets as greenlet

__all__ = ['Event']

class NOT_USED:
    def __repr__(self):
        return 'NOT_USED'

NOT_USED = NOT_USED()

class Event(object):
    """An abstraction where an arbitrary number of coroutines
    can wait for one event from another.

    Events are similar to a Queue that can only hold one item, but differ
    in two important ways:

    1. calling :meth:`send` never unschedules the current greenthread
    2. :meth:`send` can only be called once; create a new event to send again.

    They are good for communicating results between coroutines, and
    are the basis for how
    :meth:`GreenThread.wait() <eventlet.greenthread.GreenThread.wait>`
    is implemented.

    >>> from eventlet import event
    >>> import eventlet
    >>> evt = event.Event()
    >>> def baz(b):
    ...     evt.send(b + 1)
    ...
    >>> _ = eventlet.spawn_n(baz, 3)
    >>> evt.wait()
    4
    """
    _result = None
    _exc = None
    def __init__(self):
        self._waiters = set()
        self.reset()

    def __str__(self):
        params = (self.__class__.__name__, hex(id(self)),
                  self._result, self._exc, len(self._waiters))
        return '<%s at %s result=%r _exc=%r _waiters[%d]>' % params

    def reset(self):
        # this is kind of a misfeature and doesn't work perfectly well,
        # it's better to create a new event rather than reset an old one
        # removing documentation so that we don't get new use cases for it
        assert self._result is not NOT_USED, 'Trying to re-reset() a fresh event.'
        self._result = NOT_USED
        self._exc = None

    def ready(self):
        """ Return true if the :meth:`wait` call will return immediately.
        Used to avoid waiting for things that might take a while to time out.
        For example, you can put a bunch of events into a list, and then visit
        them all repeatedly, calling :meth:`ready` until one returns ``True``,
        and then you can :meth:`wait` on that one."""
        return self._result is not NOT_USED

    def has_exception(self):
        return self._exc is not None

    def has_result(self):
        return self._result is not NOT_USED and self._exc is None

    def poll(self, notready=None):
        if self.ready():
            return self.wait()
        return notready

    # QQQ make it return tuple (type, value, tb) instead of raising
    # because
    # 1) "poll" does not imply raising
    # 2) it's better not to screw up caller's sys.exc_info() by default
    #    (e.g. if caller wants to calls the function in except or finally)
    def poll_exception(self, notready=None):
        if self.has_exception():
            return self.wait()
        return notready

    def poll_result(self, notready=None):
        if self.has_result():
            return self.wait()
        return notready

    def wait(self):
        """Wait until another coroutine calls :meth:`send`.
        Returns the value the other coroutine passed to
        :meth:`send`.

        >>> from eventlet import event
        >>> import eventlet
        >>> evt = event.Event()
        >>> def wait_on():
        ...    retval = evt.wait()
        ...    print "waited for", retval
        >>> _ = eventlet.spawn(wait_on)
        >>> evt.send('result')
        >>> eventlet.sleep(0)
        waited for result

        Returns immediately if the event has already
        occured.

        >>> evt.wait()
        'result'
        """
        current = greenlet.getcurrent()
        if self._result is NOT_USED:
            self._waiters.add(current)
            try:
                return hubs.get_hub().switch()
            finally:
                self._waiters.discard(current)
        if self._exc is not None:
            current.throw(*self._exc)
        return self._result

    def send(self, result=None, exc=None):
        """Makes arrangements for the waiters to be woken with the
        result and then returns immediately to the parent.

        >>> from eventlet import event
        >>> import eventlet
        >>> evt = event.Event()
        >>> def waiter():
        ...     print 'about to wait'
        ...     result = evt.wait()
        ...     print 'waited for', result
        >>> _ = eventlet.spawn(waiter)
        >>> eventlet.sleep(0)
        about to wait
        >>> evt.send('a')
        >>> eventlet.sleep(0)
        waited for a

        It is an error to call :meth:`send` multiple times on the same event.

        >>> evt.send('whoops')
        Traceback (most recent call last):
        ...
        AssertionError: Trying to re-send() an already-triggered event.

        Use :meth:`reset` between :meth:`send` s to reuse an event object.
        """
        assert self._result is NOT_USED, 'Trying to re-send() an already-triggered event.'
        self._result = result
        if exc is not None and not isinstance(exc, tuple):
            exc = (exc, )
        self._exc = exc
        hub = hubs.get_hub()
        if self._waiters:
            hub.schedule_call_global(
                0, self._do_send, self._result, self._exc, self._waiters.copy())

    def _do_send(self, result, exc, waiters):
        while waiters:
            waiter = waiters.pop()
            if waiter in self._waiters:
                if exc is None:
                    waiter.switch(result)
                else:
                    waiter.throw(*exc)

    def send_exception(self, *args):
        """Same as :meth:`send`, but sends an exception to waiters."""
        # the arguments and the same as for greenlet.throw
        return self.send(None, args)


text:
require 'scoreoid/version'
require 'scoreoid/api'
require 'scoreoid/player'

# The main Scoreoid Ruby namespace.
#
# To get started, set your Scoreoid API key and game ID with {Scoreoid.configure}.
# Then you can use {Scoreoid::API.query_and_parse} to query any Scoreoid API method.
# See the {http://wiki.scoreoid.net/category/api/ Scoreoid Wiki} for information
# on available API methods.
module Scoreoid
	# Configure Scoreoid Ruby by setting default API request parameters.
	# You can set any parameters here, but it is only recommended to set
	# :api_key and :game_id as they are common to all API methods.
	#
	# @example Setting your API key and game ID from environment variables:
	#    Scoreoid.configure(api_key: ENV['SCOREOID_API_KEY'], game_id: ENV['SCOREOID_GAME_ID'])
	#
	# @param [Hash] params A hash of default parameters to set
	#
	# @option params [String] :api_key Your Scoreoid API key
	# @option params [String] :game_id Your Scoreoid game ID
	#
	# @return [Hash] The parameters you just set
	def self.configure(params)
		Scoreoid::API.default_params = params
	end
end


text:
FROM rancher/server:stable
MAINTAINER Eugene Cheah <eugene@picoded.com>

# Runs the entry point with the AWS command
ENTRYPOINT /usr/bin/entry --advertise-address $(curl -s 169.254.169.254/latest/meta-data/local-ipv4)


text:
from __future__ import absolute_import

import pytest
from mock import patch

from tests import *

import basil.industry.facility as f

@pytest.fixture(scope="module")
def system():
    url = "https://public-crest.eveonline.com/solarsystems/30002054/"
    return {"systemCostIndices":
            [{"costIndex": 0.001, "activityID": 8, "activityID_str": "8",
              "activityName": "Invention"},
             {"costIndex": 0.005, "activityID": 1, "activityID_str": "1",
              "activityName": "Manufacturing"},
             {"costIndex": 0.004, "activityID": 3, "activityID_str": "3",
              "activityName": "Researching Time Efficiency"},
             {"costIndex": 0.003, "activityID": 4, "activityID_str": "4",
              "activityName": "Researching Material Efficiency"},
             {"costIndex": 0.002, "activityID": 5, "activityID_str": "5",
              "activityName": "Copying"}],
            "solarSystem":
                {"id_str": "30002054", "href": url, "id": 30002054,
                 "name": "Hror"}}

def test_manufacture_index(system):
    fac = f.IndustryFacility('test', system, 0)
    assert_that(fac, has_property('manufacture_index', equal_to(0.005)))

def test_invention_index(system):
    fac = f.IndustryFacility('test', system, 0)
    assert_that(fac, has_property('invention_index', equal_to(0.001)))

def test_copying_index(system):
    fac = f.IndustryFacility('test', system, 0)
    assert_that(fac, has_property('copying_index', equal_to(0.002)))

def test_material_research_index(system):
    fac = f.IndustryFacility('test', system, 0)
    assert_that(fac, has_property('material_research_index', equal_to(0.003)))

def test_time_research_index(system):
    fac = f.IndustryFacility('test', system, 0)
    assert_that(fac, has_property('time_research_index', equal_to(0.004)))

def test_facility_by_id_npc_station():
    with MockCaches(NPC_STATION):
        fac = f.facility(60002353)
        assert_that(fac, instance_of(f.NPCStation))
        assert_that(fac, has_property('tax_rate', equal_to(10)))
        assert_that(fac, has_property('material_bonus', equal_to(0)))
        assert_that(fac, has_property('time_bonus', equal_to(0)))
        assert_that(fac, has_property('manufacture_index',
                                      equal_to(0.031129044234844177)))
        assert_that(fac, has_property('invention_index',
                                      equal_to(0.07374034740779398)))

def test_facility_by_id_outpost():
    with MockCaches(OUTPOST):
        facts = {'me_bonus': 1, 'te_bonus': 20}
        fac = f.facility(61000123, **facts)
        assert_that(fac, instance_of(f.Outpost))
        assert_that(fac, has_property('tax_rate', equal_to(0)))
        assert_that(fac, has_property('material_bonus', equal_to(1)))
        assert_that(fac, has_property('time_bonus', equal_to(20)))
        assert_that(fac, has_property('manufacture_index',
                                      equal_to(0.0008284715648540996)))
        assert_that(fac, has_property('invention_index', equal_to(0.0006)))

def test_facility_by_dict():
    args = {'structure': 'EquipmentAssemblyArray', 'solar_system_id': 30000181}
    with MockCaches(NPC_STATION):
        fac = f.facility(None, **args)
        assert_that(fac, instance_of(f.EquipmentAssemblyArray))
        assert_that(fac, has_property('tax_rate', equal_to(0)))
        assert_that(fac, has_property('material_bonus', equal_to(2)))
        assert_that(fac, has_property('time_bonus', equal_to(25)))
        assert_that(fac, has_property('manufacture_index',
                                      equal_to(0.031129044234844177)))
        assert_that(fac, has_property('invention_index',
                                      equal_to(0.07374034740779398)))

def test_facility_by_dict_with_name():
    args = {'structure': 'EquipmentAssemblyArray',
            'solar_system_id': 30000181, 'name': 'TTP'}
    with MockCaches(NPC_STATION):
        fac = f.facility(None, **args)
        assert_that(fac, instance_of(f.EquipmentAssemblyArray))
        assert_that(fac, has_property('name', equal_to('TTP')))
        assert_that(fac, has_property('tax_rate', equal_to(0)))
        assert_that(fac, has_property('material_bonus', equal_to(2)))
        assert_that(fac, has_property('time_bonus', equal_to(25)))
        assert_that(fac, has_property('manufacture_index',
                                      equal_to(0.031129044234844177)))
        assert_that(fac, has_property('invention_index',
                                      equal_to(0.07374034740779398)))

def test_cost_per_hour_amarr_small_lowsec():
    with patch('basil.market.PRICES_FUNC', return_value=143.55):
        cost = f.cost_per_hour('Amarr', 'Small')
        assert_that(cost, equal_to(1435.5))

def test_cost_per_hour_amarr_large_lowsec():
    with patch('basil.market.PRICES_FUNC', return_value=143.55):
        cost = f.cost_per_hour('amarr', 'lrg')
        assert_that(cost, equal_to(5742.0))

def test_cost_per_hour_minnie_medium_lowsec():
    with patch('basil.market.PRICES_FUNC', return_value=143.55):
        cost = f.cost_per_hour('minmatar', 'm')
        assert_that(cost, equal_to(2871.0))

def test_cost_per_hour_cal_med_in_gal_hisec():
    def mock_price_func(key):
        return {4246: 4000.5, 24594: 1111.1}.get(key)

    with patch('basil.market.PRICES_FUNC', side_effect=mock_price_func):
        cost = f.cost_per_hour('Cal', 'M', 500004)
        assert_that(cost, equal_to(81121.1))

class MockCaches(object):
    def __init__(self, cache):
        self._cache = cache

    def __enter__(self):
        self._orig_fac_cache = f.FAC_CACHE
        self._orig_sys_cache = f.SYS_CACHE
        f.FAC_CACHE = Wrapper(self._cache)
        f.SYS_CACHE = Wrapper(self._cache)

    def __exit__(self, exc_type, exc_val, exc_tb):
        f.FAC_CACHE = self._orig_fac_cache
        f.SYS_CACHE = self._orig_sys_cache

class Wrapper(object):
    def __init__(self, dictionary):
        self._dict = dictionary

    def get(self, key, blocking=False):
        return self._dict.get(key)

ROOT = 'https://public-crest.eveonline.com'
NPC_FAC = {"facilityID": 60002353,
           "solarSystem": {"id": 30000181, "id_str": "30000181"},
           "name": "Korsiki III - Moon 5 - Lai Dai Corporation Factory",
           "region": {"id": 10000002, "id_str": "10000002"},
           "tax": 0.1, "facilityID_str": "60002353",
           "owner": {"id": 1000020, "id_str": "1000020"},
           "type": {"id": 1529, "id_str": "1529"}}
NPC_SYS = {"systemCostIndices":
           [{"costIndex": 0.07374034740779398, "activityID": 8,
             "activityID_str": "8", "activityName": "Invention"},
            {"costIndex": 0.031129044234844177, "activityID": 1,
             "activityID_str": "1", "activityName": "Manufacturing"},
            {"costIndex": 0.05923129129743867, "activityID": 3,
             "activityID_str": "3",
             "activityName": "Researching Time Efficiency"},
            {"costIndex": 0.05672293125464553, "activityID": 4,
             "activityID_str": "4",
             "activityName": "Researching Material Efficiency"},
            {"costIndex": 0.05369976316936276, "activityID": 5,
             "activityID_str": "5", "activityName": "Copying"}],
           "solarSystem": {"id_str": "30000181",
                           "href": ROOT + "/solarsystems/30000181/",
                           "id": 30000181, "name": "Korsiki"}}
NPC_STATION = {60002353: NPC_FAC, 30000181: NPC_SYS}

OUT_FAC = {"facilityID": 61000123,
           "solarSystem": {"id": 30003767, "id_str": "30003767"},
           "name": "N8XA-L IV - MANIFEST DESTINY 15012",
           "region": {"id": 10000047, "id_str": "10000047"},
           "facilityID_str": "61000123",
           "owner": {"id": 1618223652, "id_str": "1618223652"},
           "type": {"id": 21646, "id_str": "21646"}}
OUT_SYS = {"systemCostIndices":
           [{"costIndex": 0.0006, "activityID": 8, "activityID_str": "8",
             "activityName": "Invention"},
            {"costIndex": 0.0008284715648540996, "activityID": 1,
             "activityID_str": "1", "activityName": "Manufacturing"},
            {"costIndex": 0.0006, "activityID": 3, "activityID_str": "3",
             "activityName": "Researching Time Efficiency"},
            {"costIndex": 0.0006, "activityID": 4, "activityID_str": "4",
             "activityName": "Researching Material Efficiency"},
            {"costIndex": 0.0006, "activityID": 5, "activityID_str": "5",
             "activityName": "Copying"}],
           "solarSystem": {"id_str": "30003767",
                           "href": ROOT + "/solarsystems/30003767/",
                           "id": 30003767, "name": "N8XA-L"}}
OUTPOST = {61000123: OUT_FAC, 30003767: OUT_SYS}


text:
require 'multi_json'

module Travis
  module Addons
    module Campfire

      # Publishes a build notification to campfire rooms as defined in the
      # configuration (`.travis.yml`).
      #
      # Campfire credentials are encrypted using the repository's ssl key.
      class Task < Travis::Task
        DEFAULT_TEMPLATE = [
          "[travis-ci] %{repository}#%{build_number} (%{branch} - %{commit} : %{author}): the build has %{result}",
          "[travis-ci] Change view: %{compare_url}",
          "[travis-ci] Build details: %{build_url}"
        ]

        def targets
          params[:targets]
        end

        def message
          @message ||= template.map { |line| Util::Template.new(line, payload).interpolate }
        end

        private

          def process
            targets.each { |target| send_message(target, message) }
          end

          def send_message(target, lines)
            url, token = parse(target)
            http.basic_auth(token, 'X')
            lines.each { |line| send_line(url, line) }
          rescue => e
            Travis.logger.info("Error connecting to Campfire service for #{target}: #{e.message}")
          end

          def send_line(url, line)
            http.post(url) do |r|
              r.body = MultiJson.encode({ message: { body: line } })
              r.headers['Content-Type'] = 'application/json'
            end
          end

          def template
            template = config[:template] rescue nil
            Array(template || DEFAULT_TEMPLATE)
          end

          def parse(target)
            target =~ /([\w-]+):([\w-]+)@(\d+)/
            ["https://#{$1}.campfirenow.com/room/#{$3}/speak.json", $2]
          end

          def config
            build[:config][:notifications][:campfire] rescue {}
          end
      end
    end
  end
end


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('produto', '0032_produto_protect'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='produto',
            name='imagem_tag',
        ),
    ]


text:
<?php

final class PhabricatorRepositoryCommitPHIDType extends PhabricatorPHIDType {

  const TYPECONST = 'CMIT';

  public function getTypeName() {
    return pht('Diffusion Commit');
  }

  public function newObject() {
    return new PhabricatorRepositoryCommit();
  }

  public function getPHIDTypeApplicationClass() {
    return 'PhabricatorDiffusionApplication';
  }

  protected function buildQueryForObjects(
    PhabricatorObjectQuery $query,
    array $phids) {

    return id(new DiffusionCommitQuery())
      ->withPHIDs($phids);
  }

  public function loadHandles(
    PhabricatorHandleQuery $query,
    array $handles,
    array $objects) {

    $unreachable = array();
    foreach ($handles as $phid => $handle) {
      $commit = $objects[$phid];
      if ($commit->isUnreachable()) {
        $unreachable[$phid] = $commit;
      }
    }

    if ($unreachable) {
      $query = id(new DiffusionCommitHintQuery())
        ->setViewer($query->getViewer())
        ->withCommits($unreachable);

      $query->execute();

      $hints = $query->getCommitMap();
    } else {
      $hints = array();
    }

    foreach ($handles as $phid => $handle) {
      $commit = $objects[$phid];
      $repository = $commit->getRepository();
      $commit_identifier = $commit->getCommitIdentifier();

      $name = $repository->formatCommitName($commit_identifier);

      if ($commit->isUnreachable()) {
        $handle->setStatus(PhabricatorObjectHandle::STATUS_CLOSED);

        // If we have a hint about this commit being rewritten, add the
        // rewrite target to the handle name. This reduces the chance users
        // will be caught offguard by the rewrite.
        $hint = idx($hints, $phid);
        if ($hint && $hint->isRewritten()) {
          $new_name = $hint->getNewCommitIdentifier();
          $new_name = $repository->formatCommitName($new_name);
          $name = pht("%s \xE2\x99\xBB %s",  $name, $new_name);
        }
      }

      $summary = $commit->getSummary();
      if (strlen($summary)) {
        $full_name = $name.': '.$summary;
      } else {
        $full_name = $name;
      }

      $handle->setName($name);
      $handle->setFullName($full_name);
      $handle->setURI($commit->getURI());
      $handle->setTimestamp($commit->getEpoch());

      $status = $commit->getAuditStatusObject();
      $icon = $status->getIcon();
      $color = $status->getColor();
      $name = $status->getName();

      $handle
        ->setStateIcon($icon)
        ->setStateColor($color)
        ->setStateName($name);
    }
  }

  public static function getCommitObjectNamePattern() {
    $min_unqualified = PhabricatorRepository::MINIMUM_UNQUALIFIED_HASH;
    $min_qualified   = PhabricatorRepository::MINIMUM_QUALIFIED_HASH;

    return
      '(?:r[A-Z]+:?|R[0-9]+:)[1-9]\d*'.
      '|'.
      '(?:r[A-Z]+:?|R[0-9]+:)[a-f0-9]{'.$min_qualified.',40}'.
      '|'.
      '[a-f0-9]{'.$min_unqualified.',40}';
  }

  public function canLoadNamedObject($name) {
    $pattern = self::getCommitObjectNamePattern();
    return preg_match('(^'.$pattern.'$)', $name);
  }

  public function loadNamedObjects(
    PhabricatorObjectQuery $query,
    array $names) {

    $query = id(new DiffusionCommitQuery())
      ->setViewer($query->getViewer())
      ->withIdentifiers($names);

    $query->execute();

    return $query->getIdentifierMap();
  }

}


text:
package org.apache.cassandra.utils;

import junit.framework.TestCase;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.io.*;

import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.io.ISerializer;
import org.apache.cassandra.io.IVersionedSerializer;

public class IntervalTreeTest extends TestCase
{
    @Test
    public void testSearch() throws Exception
    {
        List<Interval<Integer, Void>> intervals = new ArrayList<Interval<Integer, Void>>();

        intervals.add(Interval.<Integer, Void>create(-300, -200));
        intervals.add(Interval.<Integer, Void>create(-3, -2));
        intervals.add(Interval.<Integer, Void>create(1,2));
        intervals.add(Interval.<Integer, Void>create(3,6));
        intervals.add(Interval.<Integer, Void>create(2,4));
        intervals.add(Interval.<Integer, Void>create(5,7));
        intervals.add(Interval.<Integer, Void>create(1,3));
        intervals.add(Interval.<Integer, Void>create(4,6));
        intervals.add(Interval.<Integer, Void>create(8,9));
        intervals.add(Interval.<Integer, Void>create(15,20));
        intervals.add(Interval.<Integer, Void>create(40,50));
        intervals.add(Interval.<Integer, Void>create(49,60));

        IntervalTree<Integer, Void, Interval<Integer, Void>> it = IntervalTree.build(intervals);

        assertEquals(3, it.search(Interval.<Integer, Void>create(4,4)).size());
        assertEquals(4, it.search(Interval.<Integer, Void>create(4, 5)).size());
        assertEquals(7, it.search(Interval.<Integer, Void>create(-1,10)).size());
        assertEquals(0, it.search(Interval.<Integer, Void>create(-1,-1)).size());
        assertEquals(5, it.search(Interval.<Integer, Void>create(1,4)).size());
        assertEquals(2, it.search(Interval.<Integer, Void>create(0,1)).size());
        assertEquals(0, it.search(Interval.<Integer, Void>create(10,12)).size());

        List<Interval<Integer, Void>> intervals2 = new ArrayList<Interval<Integer, Void>>();

        //stravinsky 1880-1971
        intervals2.add(Interval.<Integer, Void>create(1880, 1971));
        //Schoenberg
        intervals2.add(Interval.<Integer, Void>create(1874, 1951));
        //Grieg
        intervals2.add(Interval.<Integer, Void>create(1843, 1907));
        //Schubert
        intervals2.add(Interval.<Integer, Void>create(1779, 1828));
        //Mozart
        intervals2.add(Interval.<Integer, Void>create(1756, 1828));
        //Schuetz
        intervals2.add(Interval.<Integer, Void>create(1585, 1672));

        IntervalTree<Integer, Void, Interval<Integer, Void>> it2 = IntervalTree.build(intervals2);

        assertEquals(0, it2.search(Interval.<Integer, Void>create(1829, 1842)).size());

        List<Void> intersection1 = it2.search(Interval.<Integer, Void>create(1907, 1907));
        assertEquals(3, intersection1.size());

        intersection1 = it2.search(Interval.<Integer, Void>create(1780, 1790));
        assertEquals(2, intersection1.size());

    }

    @Test
    public void testIteration()
    {
        List<Interval<Integer, Void>> intervals = new ArrayList<Interval<Integer, Void>>();

        intervals.add(Interval.<Integer, Void>create(-300, -200));
        intervals.add(Interval.<Integer, Void>create(-3, -2));
        intervals.add(Interval.<Integer, Void>create(1,2));
        intervals.add(Interval.<Integer, Void>create(3,6));
        intervals.add(Interval.<Integer, Void>create(2,4));
        intervals.add(Interval.<Integer, Void>create(5,7));
        intervals.add(Interval.<Integer, Void>create(1,3));
        intervals.add(Interval.<Integer, Void>create(4,6));
        intervals.add(Interval.<Integer, Void>create(8,9));
        intervals.add(Interval.<Integer, Void>create(15,20));
        intervals.add(Interval.<Integer, Void>create(40,50));
        intervals.add(Interval.<Integer, Void>create(49,60));

        IntervalTree<Integer, Void, Interval<Integer, Void>> it = IntervalTree.build(intervals);

        Collections.sort(intervals, it.minOrdering);

        List<Interval<Integer, Void>> l = new ArrayList<Interval<Integer, Void>>();
        for (Interval<Integer, Void> i : it)
            l.add(i);

        assertEquals(intervals, l);
    }

    @Test
    public void testSerialization() throws Exception
    {
        List<Interval<Integer, String>> intervals = new ArrayList<Interval<Integer, String>>();

        intervals.add(Interval.<Integer, String>create(-300, -200, "a"));
        intervals.add(Interval.<Integer, String>create(-3, -2, "b"));
        intervals.add(Interval.<Integer, String>create(1,2, "c"));
        intervals.add(Interval.<Integer, String>create(1,3, "d"));
        intervals.add(Interval.<Integer, String>create(2,4, "e"));
        intervals.add(Interval.<Integer, String>create(3,6, "f"));
        intervals.add(Interval.<Integer, String>create(4,6, "g"));
        intervals.add(Interval.<Integer, String>create(5,7, "h"));
        intervals.add(Interval.<Integer, String>create(8,9, "i"));
        intervals.add(Interval.<Integer, String>create(15,20, "j"));
        intervals.add(Interval.<Integer, String>create(40,50, "k"));
        intervals.add(Interval.<Integer, String>create(49,60, "l"));

        IntervalTree<Integer, String, Interval<Integer, String>> it = IntervalTree.build(intervals);

        IVersionedSerializer<IntervalTree<Integer, String, Interval<Integer, String>>> serializer = IntervalTree.serializer(
            new ISerializer<Integer>()
            {
                public void serialize(Integer i, DataOutput out) throws IOException { out.writeInt(i); }
                public Integer deserialize(DataInput in) throws IOException { return in.readInt(); }
                public long serializedSize(Integer i, TypeSizes ts) { return 4; }
            },
            new ISerializer<String>()
            {
                public void serialize(String v, DataOutput out) throws IOException { out.writeUTF(v); }
                public String deserialize(DataInput in) throws IOException { return in.readUTF(); }
                public long serializedSize(String v, TypeSizes ts) { return v.length(); }
            },
            Interval.class.getConstructor(Object.class, Object.class, Object.class)
        );

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(baos);

        serializer.serialize(it, out, 0);

        DataInputStream in = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()));

        IntervalTree<Integer, String, Interval<Integer, String>> it2 = serializer.deserialize(in, 0);
        List<Interval<Integer, String>> intervals2 = new ArrayList<Interval<Integer, String>>();
        for (Interval<Integer, String> i : it2)
            intervals2.add(i);

        assertEquals(intervals, intervals2);
    }
}


text:
namespace Catel.Caching.Policies
{
    using System;

    /// <summary>
	///	The cache item will expire using the duration to calculate the absolute expiration from now.
    /// </summary>
    public class DurationExpirationPolicy : AbsoluteExpirationPolicy
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DurationExpirationPolicy"/> class.
        /// </summary>
        /// <param name="durationTimeSpan">
        /// The expiration.
        /// </param>
        internal DurationExpirationPolicy(TimeSpan durationTimeSpan)
            : this(durationTimeSpan, false)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DurationExpirationPolicy"/> class.
        /// </summary>
        /// <param name="durationTimeSpan">
        /// The expiration.
        /// </param>
        /// <param name="canReset">
        /// The can reset.
        /// </param>
        protected DurationExpirationPolicy(TimeSpan durationTimeSpan, bool canReset)
            : base(DateTime.Now.Add(durationTimeSpan), canReset)
        {
            DurationTimeSpan = durationTimeSpan;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the expiration.
        /// </summary>
        protected TimeSpan DurationTimeSpan { get; set; }
        #endregion
    }
}


text:
package jason.asSemantics;

import jason.asSyntax.ASSyntax;
import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
import jason.asSyntax.StringTermImpl;
import jason.asSyntax.Trigger;
import jason.asSyntax.Trigger.TEOperator;
import jason.asSyntax.Trigger.TEType;

public class GoalListenerForMetaEvents implements GoalListener {

    private TransitionSystem ts;

    public GoalListenerForMetaEvents(final TransitionSystem ts) {
        this.ts = ts;
    }

    public void goalStarted(Event goal) {
        generateGoalStateEvent(goal.getTrigger().getLiteral(), TEType.achieve, GoalStates.started, null);
    }

    public void goalFailed(Trigger goal) {
        generateGoalStateEvent(goal.getLiteral(), goal.getType(), GoalStates.failed, null);
    }

    public void goalFinished(Trigger goal) {
        generateGoalStateEvent(goal.getLiteral(), goal.getType(), GoalStates.finished, null);
    }

    public void goalResumed(Trigger goal) {
        generateGoalStateEvent(goal.getLiteral(), goal.getType(), GoalStates.resumed, null);
    }

    public void goalSuspended(Trigger goal, String reason) {
        generateGoalStateEvent(goal.getLiteral(), goal.getType(), GoalStates.suspended, reason);
    }

    private void generateGoalStateEvent(final Literal goal, final TEType type, final GoalStates state, final String reason) {
        ts.runAtBeginOfNextCycle(new Runnable() {
            public void run() {
                Literal newGoal = goal.forceFullLiteralImpl().copy();
                Literal stateAnnot = ASSyntax.createLiteral("state", new Atom(state.toString()));
                if (reason != null)
                    stateAnnot.addAnnot( ASSyntax.createStructure("reason", new StringTermImpl(reason)));
                newGoal.addAnnot( stateAnnot );
                Trigger eEnd = new Trigger(TEOperator.goalState, type, newGoal);
                if (ts.getAg().getPL().hasCandidatePlan(eEnd))
                    ts.getC().insertMetaEvent(new Event(eEnd, null));
            }
        });
    }

}


text:
<?php
	namespace repository;
	interface IPostRepo{
	public static function getAllFindAHomePosts();
}
?>


text:
==not highlight==

==not highlight==

==not highlight==

some text ==not highlight==


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="{{ cookiecutter.full_package_namespace }}">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.{{ cookiecutter.repo_name }}">
       <activity android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.{{ cookiecutter.repo_name }}.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package org.onosproject.openstacknetworking.impl;

import com.google.common.collect.ImmutableSet;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.onlab.packet.BasePacket;
import org.onlab.packet.Data;
import org.onlab.packet.Ethernet;
import org.onlab.packet.IPv4;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.TCP;
import org.onlab.packet.TpPort;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.LeadershipService;
import org.onosproject.cluster.NodeId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.packet.DefaultOutboundPacket;
import org.onosproject.net.packet.PacketContext;
import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketService;
import org.onosproject.openstacknetworking.api.Constants;
import org.onosproject.openstacknetworking.api.InstancePort;
import org.onosproject.openstacknetworking.api.InstancePortService;
import org.onosproject.openstacknetworking.api.OpenstackFlowRuleService;
import org.onosproject.openstacknetworking.api.OpenstackNetworkService;
import org.onosproject.openstacknode.api.OpenstackNode;
import org.onosproject.openstacknode.api.OpenstackNodeEvent;
import org.onosproject.openstacknode.api.OpenstackNodeListener;
import org.onosproject.openstacknode.api.OpenstackNodeService;
import org.openstack4j.model.network.Port;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.openstacknetworking.api.Constants.DHCP_TABLE;
import static org.onosproject.openstacknetworking.api.Constants.PRIORITY_DHCP_RULE;
import static org.onosproject.openstacknetworking.impl.OpenstackMetadataProxyHandler.Http.Type.RESPONSE;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.hmacEncrypt;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.parseHttpRequest;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.unparseHttpResponseBody;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.unparseHttpResponseHeader;
import static org.onosproject.openstacknode.api.OpenstackNode.NodeType.COMPUTE;
import static org.onosproject.openstacknode.api.OpenstackNode.NodeType.CONTROLLER;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Handles metadata requests for the virtual instances.
 */
@Component(immediate = true)
public class OpenstackMetadataProxyHandler {
    protected final Logger log = getLogger(getClass());

    private static final String METADATA_SERVER_IP = "169.254.169.254";
    private static final int METADATA_SERVER_PORT = 8775;
    private static final int HTTP_SERVER_PORT = 80;
    private static final int PREFIX_LENGTH = 32;
    private static final short WINDOW_SIZE = (short) 0x1000;
    private static final short FIN_FLAG = (short) 0x01;
    private static final short SYN_FLAG = (short) 0x02;
    private static final short ACK_FLAG = (short) 0x10;
    private static final short SYN_ACK_FLAG = (short) 0x12;
    private static final short FIN_ACK_FLAG = (short) 0x11;
    private static final byte DATA_OFFSET = (byte) 0x5;
    private static final short URGENT_POINTER = (short) 0x1;
    private static final byte PACKET_TTL = (byte) 127;
    private static final String HTTP_PREFIX = "http://";
    private static final String COLON = ":";

    private static final String INSTANCE_ID_HEADER = "X-Instance-ID";
    private static final String INSTANCE_ID_SIGNATURE_HEADER = "X-Instance-ID-Signature";
    private static final String TENANT_ID_HEADER = "X-Tenant-ID";
    private static final String FORWARDED_FOR_HEADER = "X-Forwarded-For";

    private static final String HTTP_GET_METHOD = "GET";
    private static final String HTTP_POST_METHOD = "POST";
    private static final String HTTP_PUT_METHOD = "PUT";
    private static final String HTTP_DELETE_METHOD = "DELETE";

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected CoreService coreService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected PacketService packetService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected ClusterService clusterService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected LeadershipService leadershipService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected OpenstackNetworkService osNetworkService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected OpenstackNodeService osNodeService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected InstancePortService instancePortService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected OpenstackFlowRuleService osFlowRuleService;

    private final ExecutorService eventExecutor = newSingleThreadExecutor(
            groupedThreads(this.getClass().getSimpleName(), "event-handler", log));
    private final PacketProcessor packetProcessor = new InternalPacketProcessor();
    private final OpenstackNodeListener osNodeListener = new InternalNodeEventListener();

    private Set<String> excludedHeaders = ImmutableSet.of("content-type", "content-length");

    private ApplicationId appId;
    private NodeId localNodeId;

    @Activate
    protected void activate() {
        appId = coreService.registerApplication(Constants.OPENSTACK_NETWORKING_APP_ID);
        localNodeId = clusterService.getLocalNode().id();
        osNodeService.addListener(osNodeListener);
        packetService.addProcessor(packetProcessor, PacketProcessor.director(0));
        leadershipService.runForLeadership(appId.name());

        log.info("Started");
    }

    @Deactivate
    protected void deactivate() {
        packetService.removeProcessor(packetProcessor);
        osNodeService.removeListener(osNodeListener);
        leadershipService.withdraw(appId.name());
        eventExecutor.shutdown();

        log.info("Stopped");
    }

    private class InternalPacketProcessor implements PacketProcessor {

        @Override
        public void process(PacketContext context) {

            if (context.isHandled()) {
                return;
            }

            // FIXME: need to find a way to spawn a new thread to check metadata proxy mode
            if (!useMetadataProxy()) {
                return;
            }

            Ethernet ethPacket = context.inPacket().parsed();
            if (ethPacket == null || ethPacket.getEtherType() != Ethernet.TYPE_IPV4) {
                return;
            }

            IPv4 ipv4Packet = (IPv4) ethPacket.getPayload();
            if (ipv4Packet.getProtocol() != IPv4.PROTOCOL_TCP ||
                    !IpAddress.valueOf(ipv4Packet.getDestinationAddress()).
                            equals(IpAddress.valueOf(METADATA_SERVER_IP))) {
                return;
            }

            TCP tcpPacket = (TCP) ipv4Packet.getPayload();
            if (tcpPacket.getDestinationPort() != HTTP_SERVER_PORT) {
                return;
            }

            // (three-way handshaking)
            // reply TCP SYN-ACK packet with receiving TCP SYN packet
            if (tcpPacket.getFlags() == SYN_FLAG) {
                Ethernet ethReply = buildTcpSynAckPacket(ethPacket, ipv4Packet, tcpPacket);
                sendReply(context, ethReply);
                return;
            }

            // (four-way handshaking)
            // reply TCP ACK and TCP FIN-ACK packets with receiving TCP FIN-ACK packet
            if (tcpPacket.getFlags() == FIN_ACK_FLAG) {
                Ethernet ackReply = buildTcpAckPacket(ethPacket, ipv4Packet, tcpPacket);
                sendReply(context, ackReply);
                Ethernet finAckReply = buildTcpFinAckPacket(ethPacket, ipv4Packet, tcpPacket);
                sendReply(context, finAckReply);
                return;
            }

            // normal TCP data transmission
            Data data = (Data) tcpPacket.getPayload();
            byte[] byteData = data.getData();

            if (byteData.length != 0) {
                eventExecutor.execute(() -> {
                    processHttpRequest(context, ethPacket, ipv4Packet, tcpPacket, byteData);
                });
            }
        }

        private void processHttpRequest(PacketContext context, Ethernet ethPacket,
                                        IPv4 ipv4Packet, TCP tcpPacket, byte[] byteData) {
            HttpRequest request = parseHttpRequest(byteData);
            ConnectPoint cp = context.inPacket().receivedFrom();
            InstancePort instPort = instancePortService.instancePort(cp.deviceId(), cp.port());

            if (instPort == null || request == null) {
                log.warn("Cannot send metadata request due to lack of information");
                return;
            }

            // attempt to send HTTP request to the meta-data server (nova-api),
            // obtain the HTTP response, relay the response to VM through packet-out
            CloseableHttpResponse proxyResponse = proxyHttpRequest(request, instPort);

            if (proxyResponse == null) {
                log.warn("No response was received from metadata server");
                return;
            }

            HttpResponse response = new BasicHttpResponse(proxyResponse.getStatusLine());
            response.setEntity(proxyResponse.getEntity());
            response.setHeaders(proxyResponse.getAllHeaders());

            Http httpResponse = new Http();
            httpResponse.setType(RESPONSE);
            httpResponse.setMessage(response);

            TCP tcpReply = buildTcpDataPacket(tcpPacket, byteData.length, response);
            Ethernet ethReply = buildEthFrame(ethPacket, ipv4Packet, tcpReply);
            sendReply(context, ethReply);

            try {
                proxyResponse.close();
            } catch (IOException e) {
                log.warn("Failed to close the response connection due to {}", e);
            }
        }

        /**
         * Builds an ethernet frame contains TCP sync-ack packet generated
         * from the given TCP sync request packet.
         *
         * @param ethRequest    ethernet request frame
         * @param ipv4Request   IPv4 request
         * @param tcpRequest    TCP request
         * @return an ethernet frame contains newly generated TCP reply
         */
        private Ethernet buildTcpSynAckPacket(Ethernet ethRequest,
                                              IPv4 ipv4Request, TCP tcpRequest) {

            TCP tcpReply = buildTcpSignalPacket(tcpRequest, tcpRequest.getSequence(),
                    tcpRequest.getSequence() + 1, SYN_ACK_FLAG);

            return buildEthFrame(ethRequest, ipv4Request, tcpReply);
        }

        /**
         * Builds a TCP ACK packet receiving SYN packet.
         *
         * @param ethRequest    ethernet request frame
         * @param ipv4Request   IPv4 request
         * @param tcpRequest    TCP request
         * @return an ethernet frame contains newly generated TCP reply
         */
        private Ethernet buildTcpAckPacket(Ethernet ethRequest,
                                           IPv4 ipv4Request, TCP tcpRequest) {
            TCP tcpReply = buildTcpSignalPacket(tcpRequest, tcpRequest.getAcknowledge(),
                    tcpRequest.getSequence() + 1, ACK_FLAG);

            return buildEthFrame(ethRequest, ipv4Request, tcpReply);
        }

        /**
         * Builds a TCP FIN-ACK packet receiving FIN-ACK packet.
         *
         * @param ethRequest    ethernet request frame
         * @param ipv4Request   IPv4 request
         * @param tcpRequest    TCP request
         * @return an ethernet frame contains newly generated TCP reply
         */
        private Ethernet buildTcpFinAckPacket(Ethernet ethRequest,
                                              IPv4 ipv4Request, TCP tcpRequest) {
            TCP tcpReply = buildTcpSignalPacket(tcpRequest, tcpRequest.getAcknowledge(),
                    tcpRequest.getSequence() + 1, FIN_ACK_FLAG);

            return buildEthFrame(ethRequest, ipv4Request, tcpReply);
        }

        /**
         * Builds a TCP signaling packet.
         *
         * @param tcpRequest    TCP request
         * @param seq           sequence number
         * @param ack           ack number
         * @param flags         TCP flags
         * @return TCP signal packet
         */
        private TCP buildTcpSignalPacket(TCP tcpRequest, int seq, int ack, short flags) {
            TCP tcpReply = new TCP();
            tcpReply.setSourcePort(tcpRequest.getDestinationPort());
            tcpReply.setDestinationPort(tcpRequest.getSourcePort());
            tcpReply.setSequence(seq);
            tcpReply.setAcknowledge(ack);
            tcpReply.setDataOffset(DATA_OFFSET);
            tcpReply.setFlags(flags);
            tcpReply.setWindowSize(WINDOW_SIZE);
            tcpReply.setUrgentPointer(URGENT_POINTER);

            return tcpReply;
        }

        /**
         * Builds a TCP data packet.
         *
         * @param tcpRequest    TCP request
         * @param requestLength TCP request data length
         * @param response      HTTP response
         * @return a TCP data packet
         */
        private TCP buildTcpDataPacket(TCP tcpRequest, int requestLength,
                                       HttpResponse response) {
            TCP tcpReply = new TCP();
            tcpReply.setSourcePort(tcpRequest.getDestinationPort());
            tcpReply.setDestinationPort(tcpRequest.getSourcePort());
            tcpReply.setSequence(tcpRequest.getAcknowledge());
            tcpReply.setAcknowledge(tcpRequest.getSequence() + requestLength);
            tcpReply.setDataOffset(DATA_OFFSET);        // no options
            tcpReply.setFlags(ACK_FLAG);
            tcpReply.setWindowSize(WINDOW_SIZE);
            tcpReply.setUrgentPointer(URGENT_POINTER);

            Http httpResponse = new Http();
            httpResponse.setType(RESPONSE);
            httpResponse.setMessage(response);

            tcpReply.setPayload(httpResponse);

            return tcpReply;
        }

        /**
         * Builds an ethernet frame with the given IPv4 and TCP payload.
         *
         * @param ethRequest    ethernet request frame
         * @param ipv4Request   IPv4 request
         * @param tcpReply      TCP reply
         * @return an ethernet frame contains TCP payload
         */
        private Ethernet buildEthFrame(Ethernet ethRequest, IPv4 ipv4Request,
                                       TCP tcpReply) {
            Ethernet ethReply = new Ethernet();
            ethReply.setSourceMACAddress(ethRequest.getDestinationMAC());
            ethReply.setDestinationMACAddress(ethRequest.getSourceMAC());
            ethReply.setEtherType(ethRequest.getEtherType());

            IPv4 ipv4Reply = new IPv4();
            ipv4Reply.setSourceAddress(ipv4Request.getDestinationAddress());
            ipv4Reply.setDestinationAddress(ipv4Request.getSourceAddress());
            ipv4Reply.setTtl(PACKET_TTL);

            ipv4Reply.setPayload(tcpReply);
            ethReply.setPayload(ipv4Reply);

            return ethReply;
        }

        /**
         * Obtains the metadata path.
         *
         * @param uri metadata request URI
         * @return full metadata path
         */
        private String getMetadataPath(String uri) {
            OpenstackNode controller = osNodeService.completeNodes(CONTROLLER).
                    stream().findFirst().orElse(null);
            if (controller == null) {
                return null;
            }

            String novaMetadataIpTmp = controller.neutronConfig().novaMetadataIp();
            String novaMetadataIp = novaMetadataIpTmp != null
                    ? novaMetadataIpTmp : controller.managementIp().toString();
            Integer novaMetadataPortTmp = controller.neutronConfig().novaMetadataPort();
            int novaMetadataPort = novaMetadataPortTmp != null
                    ? novaMetadataPortTmp : METADATA_SERVER_PORT;

            return HTTP_PREFIX + novaMetadataIp + COLON + novaMetadataPort + uri;
        }

        /**
         * Proxyies HTTP request.
         *
         * @param oldRequest    HTTP request
         * @param instPort      instance port
         * @return HTTP response
         */
        private CloseableHttpResponse proxyHttpRequest(HttpRequest oldRequest,
                                                       InstancePort instPort) {

            CloseableHttpClient client = HttpClientBuilder.create().build();
            String url = getMetadataPath(oldRequest.getRequestLine().getUri());

            if (StringUtils.isEmpty(url)) {
                log.warn("The metadata endpoint is not configured!");
                return null;
            }

            HttpRequestBase request;

            String method = oldRequest.getRequestLine().getMethod().toUpperCase();

            log.info("Sending HTTP {} request to metadata endpoint {}...", method, url);

            switch (method) {
                case HTTP_POST_METHOD:
                    request = new HttpPost(url);
                    HttpEntityEnclosingRequest postRequest =
                            (HttpEntityEnclosingRequest) oldRequest;
                    ((HttpPost) request).setEntity(postRequest.getEntity());
                    break;
                case HTTP_PUT_METHOD:
                    request = new HttpPut(url);
                    HttpEntityEnclosingRequest putRequest =
                            (HttpEntityEnclosingRequest) oldRequest;
                    ((HttpPut) request).setEntity(putRequest.getEntity());
                    break;
                case HTTP_DELETE_METHOD:
                    request = new HttpDelete(url);
                    break;
                case HTTP_GET_METHOD:
                default:
                    request = new HttpGet(url);
                    break;
            }

            // configure headers from original HTTP request
            for (Header header : oldRequest.getAllHeaders()) {
                if (method.equals(HTTP_POST_METHOD) ||
                        method.equals(HTTP_PUT_METHOD)) {
                    // we DO NOT add duplicated HTTP headers for POST and PUT methods
                    if (excludedHeaders.contains(header.getName().toLowerCase())) {
                        continue;
                    }
                }
                request.addHeader(header);
            }

            request.setProtocolVersion(oldRequest.getProtocolVersion());

            Port port = osNetworkService.port(instPort.portId());

            request.addHeader(new BasicHeader(INSTANCE_ID_HEADER, port.getDeviceId()));
            request.addHeader(new BasicHeader(TENANT_ID_HEADER, port.getTenantId()));
            request.addHeader(new BasicHeader(FORWARDED_FOR_HEADER,
                                                instPort.ipAddress().toString()));
            if (metadataSecret() != null) {
                request.addHeader(new BasicHeader(INSTANCE_ID_SIGNATURE_HEADER,
                        hmacEncrypt(metadataSecret(), port.getDeviceId())));
            }

            try {
                return client.execute(request);
            } catch (IOException e) {
                log.warn("Failed to get response from metadata server due to {}", e);
            }

            return null;
        }

        /**
         * Sends out ethernet frame.
         *
         * @param context   packet context
         * @param ethReply  ethernet frame
         */
        private void sendReply(PacketContext context, Ethernet ethReply) {
            if (ethReply == null) {
                return;
            }
            ConnectPoint srcPoint = context.inPacket().receivedFrom();
            TrafficTreatment treatment = DefaultTrafficTreatment
                    .builder()
                    .setOutput(srcPoint.port())
                    .build();

            packetService.emit(new DefaultOutboundPacket(
                    srcPoint.deviceId(),
                    treatment,
                    ByteBuffer.wrap(ethReply.serialize())));
            context.block();
        }

        private String metadataSecret() {
            OpenstackNode controller = osNodeService.completeNodes(CONTROLLER)
                    .stream().findFirst().orElse(null);

            if (controller != null && controller.neutronConfig() != null) {
                return controller.neutronConfig().metadataProxySecret();
            }

            return null;
        }
    }

    private class InternalNodeEventListener implements OpenstackNodeListener {
        @Override
        public boolean isRelevant(OpenstackNodeEvent event) {
            return event.subject().type() == COMPUTE;
        }

        private boolean isRelevantHelper() {
            return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()))
                    && useMetadataProxy();
        }

        @Override
        public void event(OpenstackNodeEvent event) {
            OpenstackNode osNode = event.subject();
            switch (event.type()) {
                case OPENSTACK_NODE_COMPLETE:
                    eventExecutor.execute(() -> processNodeCompletion(osNode));
                    break;
                case OPENSTACK_NODE_INCOMPLETE:
                    eventExecutor.execute(() -> processNodeIncompletion(osNode));
                    break;
                case OPENSTACK_NODE_CREATED:
                case OPENSTACK_NODE_UPDATED:
                case OPENSTACK_NODE_REMOVED:
                default:
                    break;
            }
        }

        private void processNodeCompletion(OpenstackNode osNode) {
            if (!isRelevantHelper()) {
                return;
            }

            setMetadataRule(osNode, true);
        }

        private void processNodeIncompletion(OpenstackNode osNode) {
            if (!isRelevantHelper()) {
                return;
            }

            setMetadataRule(osNode, false);
        }

        /**
         * Installs metadata rule for receiving all metadata request packets.
         *
         * @param osNode    openstack node
         * @param install   installation flag
         */
        private void setMetadataRule(OpenstackNode osNode, boolean install) {
            TrafficSelector selector = DefaultTrafficSelector.builder()
                    .matchEthType(Ethernet.TYPE_IPV4)
                    .matchIPProtocol(IPv4.PROTOCOL_TCP)
                    .matchIPDst(IpPrefix.valueOf(
                            IpAddress.valueOf(METADATA_SERVER_IP), PREFIX_LENGTH))
                    .matchTcpDst(TpPort.tpPort(HTTP_SERVER_PORT))
                    .build();

            TrafficTreatment treatment = DefaultTrafficTreatment.builder()
                    .punt()
                    .build();

            osFlowRuleService.setRule(
                    appId,
                    osNode.intgBridge(),
                    selector,
                    treatment,
                    PRIORITY_DHCP_RULE,
                    DHCP_TABLE,
                    install);
        }
    }

    private boolean useMetadataProxy() {
        OpenstackNode gw = osNodeService.completeNodes(CONTROLLER)
                .stream().findFirst().orElse(null);

        if (gw != null && gw.neutronConfig() != null) {
            return gw.neutronConfig().useMetadataProxy();
        }

        return false;
    }

    /**
     * Implements Http packet format.
     */
    protected static class Http extends BasePacket {

        /**
         * HTTP packet type.
         */
        public enum Type {

            /**
             * Signifies that this is a Http REQUEST packet.
             */
            REQUEST,

            /**
             * Signifies that this is a Http RESPONSE packet.
             */
            RESPONSE,
        }

        private Type type;
        private HttpMessage message;

        Http() {
        }

        /**
         * Obtains the Http type.
         *
         * @return Http type
         */
        public Type getType() {
            return type;
        }

        /**
         * Configures the Http type.
         *
         * @param type Http type
         */
        public void setType(Type type) {
            this.type = type;
        }

        /**
         * Obtains the Http message.
         *
         * @return Http message
         */
        public HttpMessage getMessage() {
            return message;
        }

        /**
         * Configures the Http message.
         *
         * @param message Http message
         */
        public void setMessage(HttpMessage message) {
            this.message = message;
        }

        @Override
        public byte[] serialize() {
            if (type == RESPONSE) {

                byte[] header = unparseHttpResponseHeader((HttpResponse) message);
                byte[] body = unparseHttpResponseBody((HttpResponse) message);

                if (header == null || body == null) {
                    return new byte[0];
                }

                final byte[] data = new byte[header.length + body.length];
                final ByteBuffer bb = ByteBuffer.wrap(data);
                bb.put(header);
                bb.put(body);

                return data;
            }
            return new byte[0];
        }

        @Override
        public boolean equals(Object o) {

            if (this == o) {
                return true;
            }

            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            if (!super.equals(o)) {
                return false;
            }

            Http http = (Http) o;
            return type == http.type &&
                    com.google.common.base.Objects.equal(message, http.message);
        }

        @Override
        public int hashCode() {
            return Objects.hash(type, message);
        }
    }
}


text:
//  (C) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, Howard
//  Hinnant & John Maddock 2000.
//  Use, modification and distribution are subject to 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).
//
//  See http://www.boost.org/libs/type_traits for most recent version including documentation.

#ifndef BOOST_TT_REMOVE_VOLATILE_HPP_INCLUDED
#define BOOST_TT_REMOVE_VOLATILE_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <cstddef> // size_t

namespace boost {

   //  convert a type T to a non-cv-qualified type - remove_volatile<T>
   template <class T> struct remove_volatile{ typedef T type; };
   template <class T> struct remove_volatile<T volatile>{ typedef T type; };

#if !defined(BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS)
   template <class T, std::size_t N> struct remove_volatile<T volatile[N]>{ typedef T type[N]; };
#if !BOOST_WORKAROUND(__BORLANDC__, < 0x600) && !defined(__IBMCPP__) &&  !BOOST_WORKAROUND(__DMC__, BOOST_TESTED_AT(0x840))
   template <class T> struct remove_volatile<T volatile[]>{ typedef T type[]; };
#endif
#endif

} // namespace boost

#endif // BOOST_TT_REMOVE_VOLATILE_HPP_INCLUDED


text:
<?php
namespace Hamcrest\Type;

use Hamcrest\Core\IsTypeOf;

/**
 * Tests whether the value is a scalar (boolean, integer, double, or string).
 */
class IsScalar extends IsTypeOf
{

    public function __construct()
    {
        parent::__construct('scalar');
    }

    public function matches($item)
    {
        return is_scalar($item);
    }

    /**
     * Is the value a scalar (boolean, integer, double, or string)?
     *
     * @factory
     */
    public static function scalarValue()
    {
        return new self;
    }
}


text:
package chatty.bot.Run;

import chatty.bot.Accounts.AccountManager;
import chatty.bot.Run.RunBot.Sender;

public class RunReactUserInput extends RunReactInput {

	private String follower;

	public RunReactUserInput(Sender listener,String follower,RunInput runInput,RunComposedInput reaction,int SlowMode) {
		super(listener,runInput,reaction,SlowMode);
		this.follower = follower;

	}

	@Override
	protected boolean MustReact(String user) {
		return follower.equals(user);
	}

}


text:
* Add MIT License information
* Fix case where some header elements are repeated

## 0.2 (0.3 Greasemonkey) - 12 September 2011

* Rename project to Infinitely Stellar
* Initial release of Greasemonkey User Script

## 0.1 (Chrome) - 11 September 2011

Initial Release (project named Infinite Stellar.io)


text:
package fuzzytime

import (
	"fmt"
)

// A Date represents a year/month/day set where any of the three may be
// unset.
// default initialisation (ie Date{}) is a valid but empty Date.
type Date struct {
	year, month, day int // internally, we'll say 0=undefined
}

// Year returns the year (result undefined if field unset)
func (d *Date) Year() int { return d.year }

// Month returns the month (result undefined if field unset)
func (d *Date) Month() int { return d.month }

// Day returns the day (result undefined if field unset)
func (d *Date) Day() int { return d.day }

// SetYear sets the year field
func (d *Date) SetYear(year int) { d.year = year }

// SetMonth sets the month field
func (d *Date) SetMonth(month int) { d.month = month }

// SetDay sets the day field
func (d *Date) SetDay(day int) { d.day = day }

// HasYear returns true if the year is set
func (d *Date) HasYear() bool { return d.year != 0 }

// HasMonth returns true if the month is set
func (d *Date) HasMonth() bool { return d.month != 0 }

// HasDay returns trus if the day is set
func (d *Date) HasDay() bool { return d.day != 0 }

// Equals returns true if dates match. Fields present in one date but
// not the other are considered mismatches.
func (d *Date) Equals(other *Date) bool {
	// TODO: should check if fields are set before comparing
	if d.year == other.year && d.month == other.month && d.day == other.day {
		return true
	}
	return false
}

// Conflicts returns true if date d conflicts with the other date.
// Missing fields are not considered so, for example "2013-01-05"
// doesn't conflict with "2013-01"
func (d *Date) Conflicts(other *Date) bool {
	if d.HasYear() && other.HasYear() && d.Year() != other.Year() {
		return true
	}
	if d.HasMonth() && other.HasMonth() && d.Month() != other.Month() {
		return true
	}
	if d.HasDay() && other.HasDay() && d.Day() != other.Day() {
		return true
	}
	return false
}

// Merge copies all fields set in other into d.
// any fields unset in other are left unchanged in d.
func (d *Date) Merge(other *Date) {
	if other.HasYear() {
		d.SetYear(other.Year())
	}
	if other.HasMonth() {
		d.SetMonth(other.Month())
	}
	if other.HasDay() {
		d.SetDay(other.Day())
	}
}

// Empty tests if date is blank (ie all fields unset)
func (d *Date) Empty() bool {
	if d.HasYear() || d.HasMonth() || d.HasDay() {
		return false
	}
	return true
}

// sane returns true if date isn't obviously bogus
func (d *Date) sane() bool {
	if d.HasMonth() {
		if d.Month() < 1 || d.Month() > 12 {
			return false
		}
	}
	if d.HasDay() {
		// TODO: adjust for month! (and leapyears!)
		if d.Day() < 1 || d.Day() > 31 {
			return false
		}
	}
	return true
}

// String returns "YYYY-MM-DD" with question marks in place of
// any missing values
func (d *Date) String() string {
	var year, month, day = "????", "??", "??"
	if d.HasYear() {
		year = fmt.Sprintf("%04d", d.Year())
	}
	if d.HasMonth() {
		month = fmt.Sprintf("%02d", d.Month())
	}
	if d.HasDay() {
		day = fmt.Sprintf("%02d", d.Day())
	}

	return year + "-" + month + "-" + day
}

// ISOFormat returns "YYYY-MM-DD", "YYYY-MM" or "YYYY" depending on which
// fields are available (or "" if year is missing).
func (d *Date) ISOFormat() string {
	if d.HasYear() {
		if d.HasMonth() {
			if d.HasDay() {
				return fmt.Sprintf("%04d-%02d-%02d", d.Year(), d.Month(), d.Day())
			}
			return fmt.Sprintf("%04d-%02d", d.Year(), d.Month())
		}
		return fmt.Sprintf("%04d", d.Year())
	}
	return ""
}

// NewDate creates a Date with all fields set
func NewDate(y, m, d int) *Date {
	return &Date{y, m, d}
}


text:
FROM
MAINTAINER Chris Holman <awltux@chrisanddervilla.plus.com>
RUN rpm -ivh https://yum.puppetlabs.com/puppetlabs-release-el-6.noarch.rpm
RUN yum update
RUN yum install puppet
RUN puppet resource package puppet-server ensure=latest