text:
<?php

defined('JPATH_PLATFORM') or die;

/**
 * Form Field class for the Joomla Platform.
 * Supports a generic list of options.
 *
 * @package     Joomla.Platform
 * @subpackage  Form
 * @since       11.1
 */
class JFormFieldBackgroundProcessing extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  11.1
	 */
	protected $type = 'BackgroundProcessing';
	/**
	 * @var bool
	 */
	protected static $js_loaded = false;
	/**
	 * @var array
	 */
	protected $options = array();

	protected static $ob_enabled;

	public function __construct($form = null)
	{
		parent::__construct($form);
		if (!isset(self::$ob_enabled)) {
			self::$ob_enabled = (bool)ini_get('output_buffering');
			if (self::$ob_enabled){
				JFactory::getApplication()->enqueueMessage(JText::_('ROKBOOSTER_BACKGROUND_PROCESSING_NOT_AVAILABLE'), 'notice');
			}
		}

	}

	/**
	 * @param $name
	 *
	 * @return null
	 */
	public function __get($name)
	{
		switch ($name) {
			case 'class':
			case 'description':
			case 'formControl':
			case 'hidden':
			case 'id':
			case 'multiple':
			case 'name':
			case 'required':
			case 'type':
			case 'validate':
			case 'value':
			case 'fieldname':
			case 'group':
				return $this->$name;
				break;

			case 'input':
				// If the input hasn't yet been generated, generate it.
				if (empty($this->input)) {
					$this->input = ($this->multiple || $this->element['readonly'] == 'true') ? $this->getInput() : $this->fancyDropDown($this->getInput());
				}

				return $this->input;
				break;

			case 'label':
				// If the label hasn't yet been generated, generate it.
				if (empty($this->label)) {
					$this->label = $this->getLabel();
				}

				return $this->label;
				break;
			case 'title':
				return $this->getTitle();
				break;
		}

		return null;
	}

	protected function getLabel()
	{
		if (!self::$ob_enabled) {
			return parent::getLabel();
		}
	}

	/**
	 * Method to get the field input markup for a generic list.
	 * Use the multiple attribute to enable multiselect.
	 *
	 * @return  string  The field input markup.
	 *
	 * @since   11.1
	 */
	protected function getInput()
	{

		$html = array();
		if (!self::$ob_enabled) {
			// Initialize variables.
			$attr = '';

			// Initialize some field attributes.
			$attr .= $this->element['class'] ? ' class="' . (string)$this->element['class'] . '"' : '';

			// To avoid user's confusion, readonly="true" should imply disabled="true".
			if ((string)$this->element['readonly'] == 'true' || (string)$this->element['disabled'] == 'true') {
				$attr .= ' disabled="disabled"';
			}

			$attr .= $this->element['size'] ? ' size="' . (int)$this->element['size'] . '"' : '';
			$attr .= $this->multiple ? ' multiple="multiple"' : '';

			// Initialize JavaScript field attributes.
			$attr .= $this->element['onchange'] ? ' onchange="' . (string)$this->element['onchange'] . '"' : '';

			if ($this->element['attrs']) {
				$additional_attrs = explode(',', (string)$this->element['attrs']);
				foreach ($additional_attrs as $additional_attr) {
					$additional_attr = strtolower(trim($additional_attr));
					$attr .= $this->element[$additional_attr] ? sprintf(' %s="', $additional_attr) . (string)$this->element[$additional_attr] . '"' : '';
				}
			}

			// Get the field options.
			$options = (array)$this->getOptions();

			// Create a read-only list (no name) with a hidden input to store the value.
			if ((string)$this->element['readonly'] == 'true') {
				$html[] = JHtml::_('select.genericlist', $options, '', trim($attr), 'value', 'text', $this->value, $this->id);
				$html[] = '<input type="hidden" name="' . $this->name . '" value="' . $this->value . '"/>';
			} // Create a regular list.
			else {
				$list   = JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id);
				$html[] = $list;
			}

		} else {
			$html[] = '';
		}
		return implode($html);

	}

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   11.1
	 */
	protected function getOptions()
	{
		// Initialize variables.
		$options = array();

		foreach ($this->element->children() as $option) {

			// Only add <option /> elements.
			if ($option->getName() != 'option') {
				continue;
			}

			// Create a new option object based on the <option /> element.
			$tmp = JHtml::_('select.option', (string)$option['value'], JText::alt(trim((string)$option), preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname)), 'value', 'text', ((string)$option['disabled'] == 'true'));

			// Set some option attributes.
			$tmp->class   = (string)$option['class'];
			$tmp->divider = $option['divider'];
			$tmp->divider = empty($tmp->divider) ? false : true;

			// Set some JavaScript option attributes.
			$tmp->onclick = (string)$option['onclick'];

			// Add the option object to the result set.
			$options[] = $tmp;
		}

		reset($options);

		return $options;
	}

	/**
	 * @param $html
	 *
	 * @return string
	 */
	public function fancyDropDown($html)
	{

		$list = $output = $displayText = $displayValue = "";
		if (!self::$ob_enabled) {
			$options = $this->getOptions();

			// if no options or just 1, something wrong, let's return the original html to be safe
			if (!count($options) || count($options) == 1) return $html;

			// cycling through options for the dropdown list and to get the selected option text to display

			foreach ($options as $option) {
				$class   = (isset($option->class) ? $option->class : "") . (isset($option->disabled) ? " disabled" : "");
				$divider = (isset($option->divider)) ? $option->divider : false;
				$class   = (strlen($class) ? 'class="' . $class . '"' : "");
				$icon    = (isset($option->icon) ? $option->icon : "");

				if ($this->value == $option->value) {
					$displayText  = $option->text;
					$displayValue = $option->value;
				}

				if (strlen($icon)) $icon_html = 'fieldname . ' ' . $option->value . '">'; else $icon_html = "";

				$class = (isset($option->attr['class']) && !empty($option->attr['class'])) ? ' class="' . $option->attr['class'] . '"' : '';
				if ($divider) {
					$list .= '
' . "\n";
				} else {
					$list .= '
text . '" data-value="' . $option->value . '">' . "\n";
					$list .= '			' . $icon_html . '' . $option->text . '' . "\n";
				}
				$list .= '
' . "\n";
			}

			// rendering output
			$class = $this->fieldname . " " . $displayValue;

			$output .= '
' . "\n";
			$output .= '	' . "\n";
			if (strlen($icon)) $output .= '		 ' . "\n";
			$output .= '		' . $displayText . '' . "\n";
			$output .= ' 		' . "\n";
			$output .= '	' . "\n";
			$output .= '
' . "\n";

			$output .= $list;

			$output .= '
' . "\n";
			$output .= '
' . $html . '
' . "\n";
			$output .= "
";
		}
		return $output;
	}

	/**
	 * @param array $options
	 */
	public function addOptions($options = array())
	{
		foreach ($options as $option) {
			$this->options[] = $option;
		}
	}

	/**
	 * @param $option
	 */
	public function addOption($option)
	{
		$this->options[] = $option;
	}

	/**
	 * @param array $options
	 */
	public function setOptions($options = array())
	{
		$this->options = $options;
	}

}


text:
<?php declare(strict_types=1);

namespace Novuso\Common\Adapter\Http\Guzzle;

use Exception;
use function GuzzleHttp\Psr7\stream_for;
use Novuso\Common\Application\Http\Message\StreamFactory;
use Novuso\System\Exception\DomainException;
use Psr\Http\Message\StreamInterface;

class GuzzleStreamFactory implements StreamFactory
{
    /**
     * {@inheritdoc}
     */
    public function createStream($body = null): StreamInterface
    {
        try {
            return stream_for($body);
        } catch (Exception $exception) {
            throw new DomainException($exception->getMessage(), $exception->getCode(), $exception);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace BinanceExchange.API.Models.Request.Interfaces
{
    public interface IRequest
    {
    }
}


text:
\hypertarget{interface_s_c_services_ident_result}{}\section{S\+C\+Services\+Ident\+Result Class Reference}
\label{interface_s_c_services_ident_result}\index{S\+C\+Services\+Ident\+Result@{S\+C\+Services\+Ident\+Result}}
Inheritance diagram for S\+C\+Services\+Ident\+Result\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=3.000000cm]{interface_s_c_services_ident_result}
\end{center}
\end{figure}
\subsection*{Properties}
\begin{DoxyCompactItemize}
\item
\hyperlink{interface_s_c_services_ident_request}{S\+C\+Services\+Ident\+Request} $\ast$ {\bfseries request}\hypertarget{interface_s_c_services_ident_result_a4bce272cf169bca5c6b81e5f6ad983de}{}\label{interface_s_c_services_ident_result_a4bce272cf169bca5c6b81e5f6ad983de}

\item
N\+S\+String $\ast$ {\bfseries status}\hypertarget{interface_s_c_services_ident_result_af03cc190ab007948076e55dcf2a735e7}{}\label{interface_s_c_services_ident_result_af03cc190ab007948076e55dcf2a735e7}

\item
N\+S\+Array $\ast$ {\bfseries persons}\hypertarget{interface_s_c_services_ident_result_a44beaf0655b6a1678bb5ce5a883d52b9}{}\label{interface_s_c_services_ident_result_a44beaf0655b6a1678bb5ce5a883d52b9}

\item
N\+S\+Date $\ast$ {\bfseries created}\hypertarget{interface_s_c_services_ident_result_ab8467a12bc014fe22fb1d818bb8c265a}{}\label{interface_s_c_services_ident_result_ab8467a12bc014fe22fb1d818bb8c265a}

\item
\hyperlink{interface_s_c_services_contract}{S\+C\+Services\+Contract} $\ast$ {\bfseries contract}\hypertarget{interface_s_c_services_ident_result_a7026ee77a9e7d9651d6da0b9d8d4c32b}{}\label{interface_s_c_services_ident_result_a7026ee77a9e7d9651d6da0b9d8d4c32b}

\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}

The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
Pod/\+Classes/\+Model/\+Services/S\+C\+Services\+Ident\+Result.\+h\end{DoxyCompactItemize}


text:
text-encoding
==============

This is a polyfill for the [Encoding Living Standard](http://encoding.spec.whatwg.org/)
API for the Web, allowing encoding and decoding of textual data to and from Typed Array
buffers for binary data in JavaScript.

By default it adheres to the spec and does not support *encoding* to non-UTF encodings,
only *decoding*. It is also implemented to match the specification's algorithms, rather
than for performance. The intended use is within Web pages, so it has no dependency
on server frameworks or particular module schemes.

Basic examples and tests are included.

### Install ###

There are a few ways you can get the `text-encoding` library.

#### Node ####

`text-encoding` is on `npm`. Simply run:

```js
npm install text-encoding
```

Or add it to your `package.json` dependencies.

#### Bower ####

`text-encoding` is on `bower` as well. Install with bower like so:

```js
bower install text-encoding
```

Or add it to your `bower.json` dependencies.

### HTML Page Usage ###

```html
  <!-- Required for non-UTF encodings -->
  <script src="encoding-indexes.js"></script>
  <script src="encoding.js"></script>
```

### API Overview ###

Basic Usage

```js
  var uint8array = TextEncoder(encoding).encode(string);
  var string = TextDecoder(encoding).decode(uint8array);
```

Streaming Decode

```js
  var string = "", decoder = TextDecoder(encoding), buffer;
  while (buffer = next_chunk()) {
    string += decoder.decode(buffer, {stream:true});
  }
  string += decoder.decode(); // finish the stream
```

### Encodings ###

All encodings from the Encoding specification are supported:

utf-8 ibm866 iso-8859-2 iso-8859-3 iso-8859-4 iso-8859-5 iso-8859-6 iso-8859-7 iso-8859-8 iso-8859-8-i iso-8859-10 iso-8859-13 iso-8859-14 iso-8859-15 iso-8859-16 koi8-r koi8-u macintosh windows-874 windows-1250 windows-1251 windows-1252 windows-1253 windows-1254 windows-1255 windows-1256 windows-1257 windows-1258 x-mac-cyrillic gb18030 hz-gb-2312 big5 euc-jp iso-2022-jp shift_jis euc-kr replacement utf-16be utf-16le x-user-defined

(Some encodings may be supported under other names, e.g. ascii, iso-8859-1, etc.
See [Encoding](http://encoding.spec.whatwg.org/) for additional labels for each encoding.)

Encodings other than **utf-8**, **utf-16le** and **utf-16be** require an additional
`encoding-indexes.js` file to be included. It is rather large
(596kB uncompressed, 188kB gzipped); portions may be deleted if
support for some encodings is not required.

### Non-Standard Behavior ###

As required by the specification, only encoding to **utf-8**,
**utf-16le** and **utf-16be** is supported. If you want to try it out, you can
force a non-standard behavior by passing the `NONSTANDARD_allowLegacyEncoding`
option to TextEncoder. For example:

```js
var uint8array = new TextEncoder(
  'windows-1252', { NONSTANDARD_allowLegacyEncoding: true }).encode(text);
```

But note that the above won't work if you're using the polyfill in a browser that
natively supports the TextEncoder API natively, since the polyfill won't be used!
You'd need to fork and modify the polyfill to... not be a polyfill.

To support the legacy encodings (which may be stateful), the TextEncoder `encode()`
method accepts an optional dictionary and `stream` option,
e.g. `encoder.encode(string, {stream: true});` This is not needed for the
stateless UTF encodings since the input is always in complete code points.

The polyfill also allows construction of encoder/decoder objects without the
`new` keyword. (This non-standard behavior is supported for constructing DOM
objects in Firefox but not other browsers.)


text:
class SponsorLogoUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick
  CarrierWave.root = "#{G2.config.root_dir}"
  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog
  asset_host Settings.asset_host
  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "#{G2.config.root_dir}/public/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Process files as they are uploaded:
  # process :scale => [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process :resize_to_fit => [50, 50]
  # end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  # def extension_white_list
  #   %w(jpg jpeg gif png)
  # end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end

end


text:
{-# LANGUAGE OverloadedStrings #-}
module Identifiers.IMDB
(
    search,
    getTitleInfo,
    updateInfo,
    sResultUpdateNMedia,
    tResultUpdateNMedia
)
where

import           Base.HTTP
import           Base.Types
import           Control.Applicative
import           Control.Lens
import           Control.Monad
import           Data.Aeson
import           Data.Data
import           Data.List.Split
import           Data.Maybe
import qualified Data.Text           as T
import           Data.Attoparsec.Text
import           Control.Monad.Maybe

data TitleResult = TitleResult {
                ttitle      :: T.Text, --Movie Title
                tyear       :: T.Text, --Year Movie was Released
                trated      :: T.Text, --The Age Rating
                treleased   :: T.Text, --The Full Release Date
                truntime    :: T.Text,
                tgenre      :: T.Text,
                tdirector   :: T.Text,
                twriter     :: T.Text,
                tactors     :: T.Text,
                tplot       :: T.Text,
                tposter     :: T.Text, --Url to Poster
                timdbRating :: T.Text,
                timdbVotes  :: T.Text,
                timdbID     :: T.Text,
                toType      :: T.Text,
                tresponse   :: T.Text}
                deriving (Eq, Show)

data SearchResult = SearchResult {
                sTitle  :: T.Text,
                sYear   :: T.Text,
                sImdbID :: T.Text,
                sOType  :: T.Text}
                deriving (Eq, Show)

newtype SearchObject = SearchObject {unSObject :: [SearchResult]} deriving (Eq, Show)

instance FromJSON SearchObject where
    parseJSON (Object v) = SearchObject <$>
                            v .: "Search"
    parseJSON _          = mzero

instance FromJSON TitleResult where
    parseJSON (Object v) = TitleResult <$>
                            v .: "Title" <*> v .: "Year" <*> v .: "Rated" <*>
                            v .: "Released" <*> v .: "Runtime" <*> v .: "Genre" <*>
                            v .: "Director" <*> v .: "Writer" <*> v .: "Actors" <*>
                            v .: "Plot" <*> v .: "Poster" <*> v .: "imdbRating" <*>
                            v .: "imdbVotes" <*> v .: "imdbID" <*> v .: "Type" <*>
                            v .: "Response"
    parseJSON _          = mzero

instance FromJSON SearchResult where
    parseJSON (Object v) = SearchResult <$>
                            v .: "Title" <*>
                            v .: "Year" <*>
                            v .: "imdbID" <*>
                            v .: "Type"
    parseJSON _          = mzero

search :: T.Text -> Maybe Int -> MaybeIO [SearchResult]
search title year = MaybeT $! do
    let y = case year of
                Just a -> "&y=" ++ show a
                Nothing -> ""
    let t = T.unpack $! T.intercalate "%20" (T.splitOn " " title)
    doc <- getHTML $! "http://www.omdbapi.com/?s=" ++ t ++ y
    return  (unSObject <$> (decode doc :: Maybe SearchObject))

sResultUpdateNMedia :: NMedia -> SearchResult -> NMedia
sResultUpdateNMedia nMedia sres =
    (setImdb (sImdbID sres)) $!
    (setYear (sYear sres)) $!
    (setTitle (sTitle sres) nMedia)
    where
        setTitle = set title
        setYear val = set year (Just (read (T.unpack val) :: Int))
        setImdb val = set imdbid (Just $! T.unpack val)

getTitleInfo :: T.Text -> Maybe Int -> Maybe String -> MaybeIO TitleResult
getTitleInfo theTitle theYear theIMDBid = MaybeT  $! do
    let y = case theYear of
                Just a -> "&y="++(show a)
                Nothing -> ""
    let t = T.unpack $! T.intercalate "%20" (T.splitOn " " theTitle)
    let idb = case theIMDBid of
                Just a -> "&i="++a
                Nothing -> ""
    doc <- getHTML $! "http://www.omdbapi.com/?t=" ++ t ++ y ++ idb
    return  (decode doc :: Maybe TitleResult)

tResultUpdateNMedia :: NMedia -> TitleResult -> NMedia
-- |Still unfinished.  Need to add actors, episode, series and poster
tResultUpdateNMedia nmedia tres =
    set title (ttitle tres) $! --Add string diff calc to this
    uIntIfNothing (view year nmedia) year (tyear tres) $
        uNothingNoJust (view runtime nmedia) runtime (getRuntime $! truntime tres) $
            uIfNothing (view imdbid nmedia) imdbid (T.unpack $! timdbID tres) $
                uFloatIfNothing (view imdbrating nmedia) imdbrating (timdbRating tres) $
                    uIfNothing (view synopsis nmedia) synopsis (tplot tres) $
                        uIfNothing (view actors nmedia) actors (unpackActors (tactors tres)) nmedia

    where
        unpackActors :: T.Text -> [Actor]
        unpackActors tactors = fmap (Actor) $! T.splitOn ", " tactors
        uNothingNoJust (Just a) field val nmed = nmed
        uNothingNoJust Nothing field val nmed = set field (val) nmed
        uIfNothing  (Just a) field val nmed = nmed
        uIfNothing  Nothing field val nmed = set field (Just val) nmed
        uIntIfNothing  (Just a) field val nmed = nmed
        uIntIfNothing  Nothing field val nmed = set field (Just (read (T.unpack val) :: Int)) nmed
        uFloatIfNothing  (Just a) field val nmed = nmed
        uFloatIfNothing  Nothing field val nmed = set field (Just (read(T.unpack val) :: Float)) nmed

updateInfo :: MediaFile -> IO MediaFile
updateInfo mfile = do
    gotteninfo <- runMaybeT $! getTitleInfo (view (info.title) mfile) (view (info.year) mfile) (view (info.imdbid) mfile)
    return $! case gotteninfo of
        Nothing -> mfile
        (Just ginfo) -> set info (tResultUpdateNMedia (view info mfile) ginfo) mfile

parserRuntime :: Parser Int
parserRuntime = do
    x <- many1 (choice [hour, minute])
    return $! sum x
    where
        hour = do
            x <- double
            " h "
            return $! (floor x) * 60
        minute = do
            y <- double
            " min"
            return $! floor y

getRuntime :: T.Text -> Maybe Int
getRuntime txt = maybeResult $! feed (parse parserRuntime txt) T.empty

_baseMedia :: NMedia
_baseMedia = NMedia "Grandma's Boy" (Just 2006) Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
_baseFile :: MediaFile
_baseFile = MediaFile "" _baseMedia Nothing Nothing Nothing Nothing

main2 = print =<< runMaybeT (getTitleInfo "vincent" Nothing Nothing)
main1 = print =<< updateInfo _baseFile


text:
<?php

namespace Bermone\TutoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Bermone\TutoBundle\Form\Type\EtatType;
use Symfony\Component\Security\Core\SecurityContext;

class TutorielType extends AbstractType
{
	private $securityContext;

	public function __construct(SecurityContext $service)
    {
        $this->securityContext = $service;
    }

   /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
			->add('titre', 'text', array(
				'required' => True,
				'attr' => array(
					'placeholder'=>"Titre du tuto"
				),
			))
			->add('tutocategories','collection', array(
				'type' =>  new  TutoCategoriesType(),
				'allow_add' => true,
				'allow_delete' => true,
				'by_reference' => false,
				'required'    => true,
				'label' => 'Catégorie'
			))
            ->add('etat', new EtatType($this->securityContext), array(
				'required' => True,
				'label' => 'Etat : ',
				'empty_value' => 'Preciser l\'etat actuel du tuto',
			))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Bermone\TutoBundle\Entity\Tutoriel'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'bermone_tutobundle_tutoriel';
    }
}


text:
package org.apache.hadoop.yarn.server.federation.store.records;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.records.ReservationId;
import org.apache.hadoop.yarn.util.Records;

/**
 * Request class to obtain the home sub-cluster for the specified
 * {@link ReservationId}.
 */
@Private
@Unstable
public abstract class GetReservationHomeSubClusterRequest {

  @Private
  @Unstable
  public static GetReservationHomeSubClusterRequest newInstance(
      ReservationId reservationId) {
    GetReservationHomeSubClusterRequest appMapping =
        Records.newRecord(GetReservationHomeSubClusterRequest.class);
    appMapping.setReservationId(reservationId);
    return appMapping;
  }

  /**
   * Get the {@link ReservationId} representing the unique identifier of the
   * application.
   *
   * @return the application identifier
   */
  @Public
  @Unstable
  public abstract ReservationId getReservationId();

  /**
   * Set the {@link ReservationId} representing the unique identifier of the
   * application.
   *
   * @param reservationId the reservatopm identifier
   */
  @Private
  @Unstable
  public abstract void setReservationId(ReservationId reservationId);

}


text:
package org.scalatest.examples.wordspec.ignore

import org.scalatest.WordSpec

class SetSpec extends WordSpec {

  "A Set" when {
    "empty" should {
      "have size 0" ignore {
        assert(Set.empty.size === 0)
      }

      "produce NoSuchElementException when head is invoked" in {
        assertThrows[NoSuchElementException] {
          Set.empty.head
        }
      }
    }
  }
}


text:
package software.amazon.awssdk.services;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationRequest;

/**
 * Test to ensure that operations that use the {@link software.amazon.awssdk.auth.signer.AsyncAws4Signer} don't apply
 * the override when the signer is overridden by the customer.
 */
@RunWith(MockitoJUnitRunner.class)
public class AsyncSignerOverrideTest {
    @Mock
    public Signer mockSigner;

    @Test
    public void test_signerOverriddenForStreamingInput_takesPrecedence() {
        ProtocolRestJsonAsyncClient asyncClient = ProtocolRestJsonAsyncClient.builder()
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
                .region(Region.US_WEST_2)
                .overrideConfiguration(o -> o.putAdvancedOption(SIGNER, mockSigner))
                .build();

        try {
            asyncClient.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
                    AsyncRequestBody.fromString("test")).join();
        } catch (Exception expected) {
        }

        verify(mockSigner).sign(any(SdkHttpFullRequest.class), any(ExecutionAttributes.class));
    }
}


text:
// Copyright 2020-2022, University of Colorado Boulder

/**
 * Contrast filter
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

import toSVGNumber from '../../../dot/js/toSVGNumber.js';
import { ColorMatrixFilter, scenery } from '../imports.js';

export default class Contrast extends ColorMatrixFilter {

  private readonly amount: number;

  /**
   * @param amount - The amount of the effect, from 0 (gray), 1 (normal), or above for high-contrast
   */
  public constructor( amount: number ) {
    assert && assert( isFinite( amount ), 'Contrast amount should be finite' );
    assert && assert( amount >= 0, 'Contrast amount should be non-negative' );

    super(
      amount, 0, 0, 0, -( 0.5 * amount ) + 0.5,
      0, amount, 0, 0, -( 0.5 * amount ) + 0.5,
      0, 0, amount, 0, -( 0.5 * amount ) + 0.5,
      0, 0, 0, 1, 0
    );

    this.amount = amount;
  }

  /**
   * Returns the CSS-style filter substring specific to this single filter, e.g. `grayscale(1)`. This should be used for
   * both DOM elements (https://developer.mozilla.org/en-US/docs/Web/CSS/filter) and when supported, Canvas
   * (https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter).
   */
  public override getCSSFilterString(): string {
    return `contrast(${toSVGNumber( this.amount )})`;
  }

  public override isDOMCompatible(): boolean {
    return true;
  }

  // Turns the content gray
  public static readonly GRAY = new Contrast( 0 );
}

scenery.register( 'Contrast', Contrast );


text:
#ifndef HTMLPlugInElement_h
#define HTMLPlugInElement_h

#include "HTMLFrameOwnerElement.h"
#include "Image.h"
#include "ImageLoaderClient.h"
#include "ScriptInstance.h"

#if ENABLE(NETSCAPE_PLUGIN_API)
struct NPObject;
#endif

namespace WebCore {

class RenderEmbeddedObject;
class RenderWidget;
class Widget;

class HTMLPlugInElement : public HTMLFrameOwnerElement {
public:
    virtual ~HTMLPlugInElement();

    void resetInstance();

    PassScriptInstance getInstance();

    Widget* pluginWidget() const;

    enum DisplayState {
        WaitingForSnapshot,
        DisplayingSnapshot,
        Playing
    };
    DisplayState displayState() const { return m_displayState; }
    void setDisplayState(DisplayState state) { m_displayState = state; }
    virtual void updateSnapshot(PassRefPtr<Image>) { }

#if ENABLE(NETSCAPE_PLUGIN_API)
    NPObject* getNPObject();
#endif

    bool isCapturingMouseEvents() const { return m_isCapturingMouseEvents; }
    void setIsCapturingMouseEvents(bool capturing) { m_isCapturingMouseEvents = capturing; }

    bool canContainRangeEndPoint() const { return false; }

protected:
    HTMLPlugInElement(const QualifiedName& tagName, Document*);

    virtual void detach();
    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
    virtual void collectStyleForAttribute(const Attribute&, StylePropertySet*) OVERRIDE;
    virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }

    bool m_inBeforeLoadEventHandler;
    // Subclasses should use guardedDispatchBeforeLoadEvent instead of calling dispatchBeforeLoadEvent directly.
    bool guardedDispatchBeforeLoadEvent(const String& sourceURL);

private:
    bool dispatchBeforeLoadEvent(const String& sourceURL); // Not implemented, generates a compile error if subclasses call this by mistake.

    virtual void defaultEventHandler(Event*);

    virtual RenderWidget* renderWidgetForJSBindings() const = 0;

    virtual bool isKeyboardFocusable(KeyboardEvent*) const;
    virtual bool isPluginElement() const;

private:
    mutable ScriptInstance m_instance;
#if ENABLE(NETSCAPE_PLUGIN_API)
    NPObject* m_NPObject;
#endif
    bool m_isCapturingMouseEvents;

    DisplayState m_displayState;
};

} // namespace WebCore

#endif // HTMLPlugInElement_h


text:
/*
** Implementation of tables (aka arrays, objects, or hash tables).
** Tables keep its elements in two parts: an array part and a hash part.
** Non-negative integer keys are all candidates to be kept in the array
** part. The actual size of the array is the largest `n' such that at
** least half the slots between 0 and n are in use.
** Hash uses a mix of chained scatter table with Brent's variation.
** A main invariant of these tables is that, if an element is not
** in its main position (i.e. the `original' position that its hash gives
** to it), then the colliding element is in its own main position.
** Hence even when the load factor reaches 100%, performance remains good.
*/

#include <string.h>

#define ltable_c
#define LUA_CORE

#include "lua.h"

#include "ldebug.h"
#include "ldo.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "lvm.h"

/*
** max size of array part is 2^MAXBITS
*/
#if LUAI_BITSINT >= 32
#define MAXBITS		30
#else
#define MAXBITS		(LUAI_BITSINT-2)
#endif

#define MAXASIZE	(1 << MAXBITS)

#define hashpow2(t,n)		(gnode(t, lmod((n), sizenode(t))))

#define hashstr(t,str)		hashpow2(t, (str)->tsv.hash)
#define hashboolean(t,p)	hashpow2(t, p)

/*
** for some types, it is better to avoid modulus by power of 2, as
** they tend to have many 2 factors.
*/
#define hashmod(t,n)	(gnode(t, ((n) % ((sizenode(t)-1)|1))))

#define hashpointer(t,p)	hashmod(t, IntPoint(p))

#define dummynode		(&dummynode_)

#define isdummy(n)		((n) == dummynode)

static const Node dummynode_ = {
  {NILCONSTANT},  /* value */
  {{NILCONSTANT, NULL}}  /* key */
};

/*
** hash for lua_Numbers
*/
static Node *hashnum (const Table *t, lua_Number n) {
  int i;
  luai_hashnum(i, n);
  if (i < 0) {
    if (cast(unsigned int, i) == 0u - i)  /* use unsigned to avoid overflows */
      i = 0;  /* handle INT_MIN */
    i = -i;  /* must be a positive value */
  }
  return hashmod(t, i);
}

/*
** returns the `main' position of an element in a table (that is, the index
** of its hash value)
*/
static Node *mainposition (const Table *t, const TValue *key) {
  switch (ttype(key)) {
    case LUA_TNUMBER:
      return hashnum(t, nvalue(key));
    case LUA_TLNGSTR: {
      TString *s = rawtsvalue(key);
      if (s->tsv.extra == 0) {  /* no hash? */
        s->tsv.hash = luaS_hash(getstr(s), s->tsv.len, s->tsv.hash);
        s->tsv.extra = 1;  /* now it has its hash */
      }
      return hashstr(t, rawtsvalue(key));
    }
    case LUA_TSHRSTR:
      return hashstr(t, rawtsvalue(key));
    case LUA_TBOOLEAN:
      return hashboolean(t, bvalue(key));
    case LUA_TLIGHTUSERDATA:
      return hashpointer(t, pvalue(key));
    case LUA_TLCF:
      return hashpointer(t, fvalue(key));
    default:
      return hashpointer(t, gcvalue(key));
  }
}

/*
** returns the index for `key' if `key' is an appropriate key to live in
** the array part of the table, -1 otherwise.
*/
static int arrayindex (const TValue *key) {
  if (ttisnumber(key)) {
    lua_Number n = nvalue(key);
    int k;
    lua_number2int(k, n);
    if (luai_numeq(cast_num(k), n))
      return k;
  }
  return -1;  /* `key' did not match some condition */
}

/*
** returns the index of a `key' for table traversals. First goes all
** elements in the array part, then elements in the hash part. The
** beginning of a traversal is signaled by -1.
*/
static int findindex (lua_State *L, Table *t, StkId key) {
  int i;
  if (ttisnil(key)) return -1;  /* first iteration */
  i = arrayindex(key);
  if (0 < i && i <= t->sizearray)  /* is `key' inside array part? */
    return i-1;  /* yes; that's the index (corrected to C) */
  else {
    Node *n = mainposition(t, key);
    for (;;) {  /* check whether `key' is somewhere in the chain */
      /* key may be dead already, but it is ok to use it in `next' */
      if (luaV_rawequalobj(gkey(n), key) ||
            (ttisdeadkey(gkey(n)) && iscollectable(key) &&
             deadvalue(gkey(n)) == gcvalue(key))) {
        i = cast_int(n - gnode(t, 0));  /* key index in hash table */
        /* hash elements are numbered after array ones */
        return i + t->sizearray;
      }
      else n = gnext(n);
      if (n == NULL)
        luaG_runerror(L, "invalid key to " LUA_QL("next"));  /* key not found */
    }
  }
}

int luaH_next (lua_State *L, Table *t, StkId key) {
  int i = findindex(L, t, key);  /* find original element */
  for (i++; i < t->sizearray; i++) {  /* try first array part */
    if (!ttisnil(&t->array[i])) {  /* a non-nil value? */
      setnvalue(key, cast_num(i+1));
      setobj2s(L, key+1, &t->array[i]);
      return 1;
    }
  }
  for (i -= t->sizearray; i < sizenode(t); i++) {  /* then hash part */
    if (!ttisnil(gval(gnode(t, i)))) {  /* a non-nil value? */
      setobj2s(L, key, gkey(gnode(t, i)));
      setobj2s(L, key+1, gval(gnode(t, i)));
      return 1;
    }
  }
  return 0;  /* no more elements */
}

/*
** {=============================================================
** Rehash
** ==============================================================
*/

static int computesizes (int nums[], int *narray) {
  int i;
  int twotoi;  /* 2^i */
  int a = 0;  /* number of elements smaller than 2^i */
  int na = 0;  /* number of elements to go to array part */
  int n = 0;  /* optimal size for array part */
  for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
    if (nums[i] > 0) {
      a += nums[i];
      if (a > twotoi/2) {  /* more than half elements present? */
        n = twotoi;  /* optimal size (till now) */
        na = a;  /* all elements smaller than n will go to array part */
      }
    }
    if (a == *narray) break;  /* all elements already counted */
  }
  *narray = n;
  lua_assert(*narray/2 <= na && na <= *narray);
  return na;
}

static int countint (const TValue *key, int *nums) {
  int k = arrayindex(key);
  if (0 < k && k <= MAXASIZE) {  /* is `key' an appropriate array index? */
    nums[luaO_ceillog2(k)]++;  /* count as such */
    return 1;
  }
  else
    return 0;
}

static int numusearray (const Table *t, int *nums) {
  int lg;
  int ttlg;  /* 2^lg */
  int ause = 0;  /* summation of `nums' */
  int i = 1;  /* count to traverse all array keys */
  for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) {  /* for each slice */
    int lc = 0;  /* counter */
    int lim = ttlg;
    if (lim > t->sizearray) {
      lim = t->sizearray;  /* adjust upper limit */
      if (i > lim)
        break;  /* no more elements to count */
    }
    /* count elements in range (2^(lg-1), 2^lg] */
    for (; i <= lim; i++) {
      if (!ttisnil(&t->array[i-1]))
        lc++;
    }
    nums[lg] += lc;
    ause += lc;
  }
  return ause;
}

static int numusehash (const Table *t, int *nums, int *pnasize) {
  int totaluse = 0;  /* total number of elements */
  int ause = 0;  /* summation of `nums' */
  int i = sizenode(t);
  while (i--) {
    Node *n = &t->node[i];
    if (!ttisnil(gval(n))) {
      ause += countint(gkey(n), nums);
      totaluse++;
    }
  }
  *pnasize += ause;
  return totaluse;
}

static void setarrayvector (lua_State *L, Table *t, int size) {
  int i;
  luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
  for (i=t->sizearray; i<size; i++)
     setnilvalue(&t->array[i]);
  t->sizearray = size;
}

static void setnodevector (lua_State *L, Table *t, int size) {
  int lsize;
  if (size == 0) {  /* no elements to hash part? */
    t->node = cast(Node *, dummynode);  /* use common `dummynode' */
    lsize = 0;
  }
  else {
    int i;
    lsize = luaO_ceillog2(size);
    if (lsize > MAXBITS)
      luaG_runerror(L, "table overflow");
    size = twoto(lsize);
    t->node = luaM_newvector(L, size, Node);
    for (i=0; i<size; i++) {
      Node *n = gnode(t, i);
      gnext(n) = NULL;
      setnilvalue(gkey(n));
      setnilvalue(gval(n));
    }
  }
  t->lsizenode = cast_byte(lsize);
  t->lastfree = gnode(t, size);  /* all positions are free */
}

void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {
  int i;
  int oldasize = t->sizearray;
  int oldhsize = t->lsizenode;
  Node *nold = t->node;  /* save old hash ... */
  if (nasize > oldasize)  /* array part must grow? */
    setarrayvector(L, t, nasize);
  /* create new hash part with appropriate size */
  setnodevector(L, t, nhsize);
  if (nasize < oldasize) {  /* array part must shrink? */
    t->sizearray = nasize;
    /* re-insert elements from vanishing slice */
    for (i=nasize; i<oldasize; i++) {
      if (!ttisnil(&t->array[i]))
        luaH_setint(L, t, i + 1, &t->array[i]);
    }
    /* shrink array */
    luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
  }
  /* re-insert elements from hash part */
  for (i = twoto(oldhsize) - 1; i >= 0; i--) {
    Node *old = nold+i;
    if (!ttisnil(gval(old))) {
      /* doesn't need barrier/invalidate cache, as entry was
         already present in the table */
      setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old));
    }
  }
  if (!isdummy(nold))
    luaM_freearray(L, nold, cast(size_t, twoto(oldhsize))); /* free old array */
}

void luaH_resizearray (lua_State *L, Table *t, int nasize) {
  int nsize = isdummy(t->node) ? 0 : sizenode(t);
  luaH_resize(L, t, nasize, nsize);
}

static void rehash (lua_State *L, Table *t, const TValue *ek) {
  int nasize, na;
  int nums[MAXBITS+1];  /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */
  int i;
  int totaluse;
  for (i=0; i<=MAXBITS; i++) nums[i] = 0;  /* reset counts */
  nasize = numusearray(t, nums);  /* count keys in array part */
  totaluse = nasize;  /* all those keys are integer keys */
  totaluse += numusehash(t, nums, &nasize);  /* count keys in hash part */
  /* count extra key */
  nasize += countint(ek, nums);
  totaluse++;
  /* compute new size for array part */
  na = computesizes(nums, &nasize);
  /* resize the table to new computed sizes */
  luaH_resize(L, t, nasize, totaluse - na);
}

/*
** }=============================================================
*/

Table *luaH_new (lua_State *L) {
  Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h;
  t->metatable = NULL;
  t->flags = cast_byte(~0);
  t->array = NULL;
  t->sizearray = 0;
  setnodevector(L, t, 0);
  return t;
}

void luaH_free (lua_State *L, Table *t) {
  if (!isdummy(t->node))
    luaM_freearray(L, t->node, cast(size_t, sizenode(t)));
  luaM_freearray(L, t->array, t->sizearray);
  luaM_free(L, t);
}

static Node *getfreepos (Table *t) {
  while (t->lastfree > t->node) {
    t->lastfree--;
    if (ttisnil(gkey(t->lastfree)))
      return t->lastfree;
  }
  return NULL;  /* could not find a free place */
}

/*
** inserts a new key into a hash table; first, check whether key's main
** position is free. If not, check whether colliding node is in its main
** position or not: if it is not, move colliding node to an empty place and
** put new key in its main position; otherwise (colliding node is in its main
** position), new key goes to an empty position.
*/
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
  Node *mp;
  if (ttisnil(key)) luaG_runerror(L, "table index is nil");
  else if (ttisnumber(key) && luai_numisnan(L, nvalue(key)))
    luaG_runerror(L, "table index is NaN");
  mp = mainposition(t, key);
  if (!ttisnil(gval(mp)) || isdummy(mp)) {  /* main position is taken? */
    Node *othern;
    Node *n = getfreepos(t);  /* get a free place */
    if (n == NULL) {  /* cannot find a free place? */
      rehash(L, t, key);  /* grow table */
      /* whatever called 'newkey' take care of TM cache and GC barrier */
      return luaH_set(L, t, key);  /* insert key into grown table */
    }
    lua_assert(!isdummy(n));
    othern = mainposition(t, gkey(mp));
    if (othern != mp) {  /* is colliding node out of its main position? */
      /* yes; move colliding node into free position */
      while (gnext(othern) != mp) othern = gnext(othern);  /* find previous */
      gnext(othern) = n;  /* redo the chain with `n' in place of `mp' */
      *n = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
      gnext(mp) = NULL;  /* now `mp' is free */
      setnilvalue(gval(mp));
    }
    else {  /* colliding node is in its own main position */
      /* new node will go into free position */
      gnext(n) = gnext(mp);  /* chain new position */
      gnext(mp) = n;
      mp = n;
    }
  }
  setobj2t(L, gkey(mp), key);
  luaC_barrierback(L, obj2gco(t), key);
  lua_assert(ttisnil(gval(mp)));
  return gval(mp);
}

/*
** search function for integers
*/
const TValue *luaH_getint (Table *t, int key) {
  /* (1 <= key && key <= t->sizearray) */
  if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
    return &t->array[key-1];
  else {
    lua_Number nk = cast_num(key);
    Node *n = hashnum(t, nk);
    do {  /* check whether `key' is somewhere in the chain */
      if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
        return gval(n);  /* that's it */
      else n = gnext(n);
    } while (n);
    return luaO_nilobject;
  }
}

/*
** search function for short strings
*/
const TValue *luaH_getstr (Table *t, TString *key) {
  Node *n = hashstr(t, key);
  lua_assert(key->tsv.tt == LUA_TSHRSTR);
  do {  /* check whether `key' is somewhere in the chain */
    if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key))
      return gval(n);  /* that's it */
    else n = gnext(n);
  } while (n);
  return luaO_nilobject;
}

/*
** main search function
*/
const TValue *luaH_get (Table *t, const TValue *key) {
  switch (ttype(key)) {
    case LUA_TNIL: return luaO_nilobject;
    case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key));
    case LUA_TNUMBER: {
      int k;
      lua_Number n = nvalue(key);
      lua_number2int(k, n);
      if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
        return luaH_getint(t, k);  /* use specialized version */
      /* else go through */
    }
    default: {
      Node *n = mainposition(t, key);
      do {  /* check whether `key' is somewhere in the chain */
        if (luaV_rawequalobj(gkey(n), key))
          return gval(n);  /* that's it */
        else n = gnext(n);
      } while (n);
      return luaO_nilobject;
    }
  }
}

/*
** beware: when using this function you probably need to check a GC
** barrier and invalidate the TM cache.
*/
TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
  const TValue *p = luaH_get(t, key);
  if (p != luaO_nilobject)
    return cast(TValue *, p);
  else return luaH_newkey(L, t, key);
}

void luaH_setint (lua_State *L, Table *t, int key, TValue *value) {
  const TValue *p = luaH_getint(t, key);
  TValue *cell;
  if (p != luaO_nilobject)
    cell = cast(TValue *, p);
  else {
    TValue k;
    setnvalue(&k, cast_num(key));
    cell = luaH_newkey(L, t, &k);
  }
  setobj2t(L, cell, value);
}

static int unbound_search (Table *t, unsigned int j) {
  unsigned int i = j;  /* i is zero or a present index */
  j++;
  /* find `i' and `j' such that i is present and j is not */
  while (!ttisnil(luaH_getint(t, j))) {
    i = j;
    j *= 2;
    if (j > cast(unsigned int, MAX_INT)) {  /* overflow? */
      /* table was built with bad purposes: resort to linear search */
      i = 1;
      while (!ttisnil(luaH_getint(t, i))) i++;
      return i - 1;
    }
  }
  /* now do a binary search between them */
  while (j - i > 1) {
    unsigned int m = (i+j)/2;
    if (ttisnil(luaH_getint(t, m))) j = m;
    else i = m;
  }
  return i;
}

/*
** Try to find a boundary in table `t'. A `boundary' is an integer index
** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
*/
int luaH_getn (Table *t) {
  unsigned int j = t->sizearray;
  if (j > 0 && ttisnil(&t->array[j - 1])) {
    /* there is a boundary in the array part: (binary) search for it */
    unsigned int i = 0;
    while (j - i > 1) {
      unsigned int m = (i+j)/2;
      if (ttisnil(&t->array[m - 1])) j = m;
      else i = m;
    }
    return i;
  }
  /* else must find a boundary in hash part */
  else if (isdummy(t->node))  /* hash part is empty? */
    return j;  /* that is easy... */
  else return unbound_search(t, j);
}

#if defined(LUA_DEBUG)

Node *luaH_mainposition (const Table *t, const TValue *key) {
  return mainposition(t, key);
}

int luaH_isdummy (Node *n) { return isdummy(n); }

#endif


text:
package org.zaproxy.zap.extension.openapi.v3;

import static fi.iki.elonen.NanoHTTPD.newFixedLengthResponse;
import static org.junit.jupiter.api.Assertions.assertEquals;

import fi.iki.elonen.NanoHTTPD;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpSender;
import org.zaproxy.zap.extension.openapi.AbstractServerTest;
import org.zaproxy.zap.extension.openapi.converter.Converter;
import org.zaproxy.zap.extension.openapi.converter.swagger.SwaggerConverter;
import org.zaproxy.zap.extension.openapi.converter.swagger.SwaggerException;
import org.zaproxy.zap.extension.openapi.network.RequesterListener;
import org.zaproxy.zap.extension.openapi.network.Requestor;
import org.zaproxy.zap.testutils.NanoServerHandler;

public class OpenApiPrimitivesInBodyUnitTest extends AbstractServerTest {

    @Test
    public void shouldExploreBodiesWithPrimitiveValues()
            throws NullPointerException, IOException, SwaggerException {
        String test = "/OpenApi_defn_body_with_primitives/";

        this.nano.addHandler(
                new NanoServerHandler(test) {
                    @Override
                    protected NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
                        String response;
                        String uri = session.getUri();
                        if (uri.endsWith("defn.yaml")) {
                            response =
                                    getHtml(
                                            "OpenApi_defn_body_with_primitives.yaml",
                                            new String[][] {
                                                {"PORT", String.valueOf(nano.getListeningPort())}
                                            });
                        } else {
                            // We dont actually care about the response in this test ;)
                            response = getHtml("Blank.html");
                        }
                        return newFixedLengthResponse(response);
                    }
                });

        Requestor requestor = new Requestor(HttpSender.MANUAL_REQUEST_INITIATOR);
        HttpMessage defnMsg = this.getHttpMessage(test + "defn.yaml");
        Converter converter =
                new SwaggerConverter(
                        requestor.getResponseBody(defnMsg.getRequestHeader().getURI()), null);
        final Map<String, String> accessedUrls = new HashMap<String, String>();
        RequesterListener listener =
                new RequesterListener() {
                    @Override
                    public void handleMessage(HttpMessage message, int initiator) {
                        accessedUrls.put(
                                message.getRequestHeader().getMethod()
                                        + " "
                                        + message.getRequestHeader().getURI().toString(),
                                message.getRequestBody().toString());
                    }
                };
        requestor.addListener(listener);
        requestor.run(converter.getRequestModels());
        checkRequests(accessedUrls, "localhost:" + nano.getListeningPort());
    }

    private void checkRequests(Map<String, String> accessedUrls, String host) {
        // Check all of the expected URLs have been accessed and with the right data
        assertEquals("true", accessedUrls.get("POST http://" + host + "/api/boolean"));
        assertEquals("[true,true]", accessedUrls.get("POST http://" + host + "/api/booleans"));

        assertEquals("1.2", accessedUrls.get("POST http://" + host + "/api/double"));
        assertEquals("[1.2,1.2]", accessedUrls.get("POST http://" + host + "/api/doubles"));

        assertEquals("10", accessedUrls.get("POST http://" + host + "/api/integer"));
        assertEquals("[10,10]", accessedUrls.get("POST http://" + host + "/api/integers"));

        assertEquals("10", accessedUrls.get("POST http://" + host + "/api/long"));
        assertEquals("[10,10]", accessedUrls.get("POST http://" + host + "/api/longs"));

        assertEquals("\"John Doe\"", accessedUrls.get("POST http://" + host + "/api/string"));
        assertEquals(
                "[\"John Doe\",\"John Doe\"]",
                accessedUrls.get("POST http://" + host + "/api/strings"));

        assertEquals(10, accessedUrls.size());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

    <ImageButton
        android:id="@+id/add_button"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="left|bottom"
        android:layout_marginBottom="30dp"
        android:layout_marginLeft="30dp"
        android:elevation="30dp"
        android:tint="@android:color/white"
        android:background="@drawable/oval"
        android:src="@android:drawable/ic_input_add"/>

</FrameLayout><!-- From: file:/Users/miraclewong/AndroidStudioProjects/HelloWorld/recycarddemo/src/main/res/layout/recycle_view.xml -->


text:
package com.lonict.android.bbplayer.ui;

import android.app.ActivityOptions;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.MediaRouteButton;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.lonict.android.bbplayer.R;
import com.lonict.android.bbplayer.utils.LogHelper;
import com.google.android.libraries.cast.companionlibrary.cast.VideoCastManager;
import com.google.android.libraries.cast.companionlibrary.cast.callbacks.VideoCastConsumerImpl;
import com.google.android.libraries.cast.companionlibrary.widgets.IntroductoryOverlay;

/**
 * Abstract activity with toolbar, navigation drawer and cast support. Needs to be extended by
 * any activity that wants to be shown as a top level activity.
 *
 * The requirements for a subclass is to call {@link #initializeToolbar()} on onCreate, after
 * setContentView() is called and have three mandatory layout elements:
 * a {@link android.support.v7.widget.Toolbar} with id 'toolbar',
 * a {@link android.support.v4.widget.DrawerLayout} with id 'drawerLayout' and
 * a {@link android.widget.ListView} with id 'drawerList'.
 */
public abstract class ActionBarCastActivity extends AppCompatActivity {

    private static final String TAG = LogHelper.makeLogTag(ActionBarCastActivity.class);

    private static final int DELAY_MILLIS = 1000;

    private VideoCastManager mCastManager;
    private MenuItem mMediaRouteMenuItem;
    private Toolbar mToolbar;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;

    private boolean mToolbarInitialized;

    private int mItemToOpenWhenDrawerCloses = -1;

    private final VideoCastConsumerImpl mCastConsumer = new VideoCastConsumerImpl() {

        @Override
        public void onFailed(int resourceId, int statusCode) {
            LogHelper.d(TAG, "onFailed ", resourceId, " status ", statusCode);
        }

        @Override
        public void onConnectionSuspended(int cause) {
            LogHelper.d(TAG, "onConnectionSuspended() was called with cause: ", cause);
        }

        @Override
        public void onConnectivityRecovered() {
        }

        @Override
        public void onCastAvailabilityChanged(boolean castPresent) {
            if (castPresent) {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (mMediaRouteMenuItem.isVisible()) {
                            LogHelper.d(TAG, "Cast Icon is visible");
                            showFtu();
                        }
                    }
                }, DELAY_MILLIS);
            }
        }

    };

    private final DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerClosed(View drawerView) {
            if (mDrawerToggle != null) mDrawerToggle.onDrawerClosed(drawerView);
            if (mItemToOpenWhenDrawerCloses >= 0) {
                Bundle extras = ActivityOptions.makeCustomAnimation(
                    ActionBarCastActivity.this, R.anim.fade_in, R.anim.fade_out).toBundle();

                Class activityClass = null;
                switch (mItemToOpenWhenDrawerCloses) {
                    case R.id.navigation_allmusic:
                        activityClass = MusicPlayerActivity.class;
                        break;
                    case R.id.navigation_playlists:
                        activityClass = PlaceholderActivity.class;
                        break;
                }
                if (activityClass != null) {
                    startActivity(new Intent(ActionBarCastActivity.this, activityClass), extras);
                    finish();
                }
            }
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            if (mDrawerToggle != null) mDrawerToggle.onDrawerStateChanged(newState);
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            if (mDrawerToggle != null) mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            if (mDrawerToggle != null) mDrawerToggle.onDrawerOpened(drawerView);
            if (getSupportActionBar() != null) getSupportActionBar()
                    .setTitle(R.string.app_name);
        }
    };

    private final FragmentManager.OnBackStackChangedListener mBackStackChangedListener =
        new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                updateDrawerToggle();
            }
        };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogHelper.d(TAG, "Activity onCreate");

        // Ensure that Google Play Service is available.
        VideoCastManager.checkGooglePlayServices(this);

        mCastManager = VideoCastManager.getInstance();
        mCastManager.reconnectSessionIfPossible();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!mToolbarInitialized) {
            throw new IllegalStateException("You must run super.initializeToolbar at " +
                "the end of your onCreate method");
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (mDrawerToggle != null) {
            mDrawerToggle.syncState();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mCastManager.addVideoCastConsumer(mCastConsumer);
        mCastManager.incrementUiCounter();

        // Whenever the fragment back stack changes, we may need to update the
        // action bar toggle: only top level screens show the hamburger-like icon, inner
        // screens - either Activities or fragments - show the "Up" icon instead.
        getFragmentManager().addOnBackStackChangedListener(mBackStackChangedListener);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mDrawerToggle != null) {
            mDrawerToggle.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mCastManager.removeVideoCastConsumer(mCastConsumer);
        mCastManager.decrementUiCounter();
        getFragmentManager().removeOnBackStackChangedListener(mBackStackChangedListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main, menu);
        mMediaRouteMenuItem = mCastManager.addMediaRouterButton(menu, R.id.media_route_menu_item);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle != null && mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // If not handled by drawerToggle, home needs to be handled by returning to previous
        if (item != null && item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        // If the drawer is open, back will close it
        if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawers();
            return;
        }
        // Otherwise, it may return to the previous fragment stack
        FragmentManager fragmentManager = getFragmentManager();
        if (fragmentManager.getBackStackEntryCount() > 0) {
            fragmentManager.popBackStack();
        } else {
            // Lastly, it will rely on the system behavior for back
            super.onBackPressed();
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        mToolbar.setTitle(title);
    }

    @Override
    public void setTitle(int titleId) {
        super.setTitle(titleId);
        mToolbar.setTitle(titleId);
    }

    protected void initializeToolbar() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        if (mToolbar == null) {
            throw new IllegalStateException("Layout is required to include a Toolbar with id " +
                "'toolbar'");
        }
        mToolbar.inflateMenu(R.menu.main);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (mDrawerLayout != null) {
            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            if (navigationView == null) {
                throw new IllegalStateException("Layout requires a NavigationView " +
                        "with id 'nav_view'");
            }

            // Create an ActionBarDrawerToggle that will handle opening/closing of the drawer:
            mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                mToolbar, R.string.open_content_drawer, R.string.close_content_drawer);
            mDrawerLayout.setDrawerListener(mDrawerListener);
            populateDrawerItems(navigationView);
            setSupportActionBar(mToolbar);
            updateDrawerToggle();
        } else {
            setSupportActionBar(mToolbar);
        }

        mToolbarInitialized = true;
    }

    private void populateDrawerItems(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        menuItem.setChecked(true);
                        mItemToOpenWhenDrawerCloses = menuItem.getItemId();
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });
        if (MusicPlayerActivity.class.isAssignableFrom(getClass())) {
            navigationView.setCheckedItem(R.id.navigation_allmusic);
        } else if (PlaceholderActivity.class.isAssignableFrom(getClass())) {
            navigationView.setCheckedItem(R.id.navigation_playlists);
        }
    }

    protected void updateDrawerToggle() {
        if (mDrawerToggle == null) {
            return;
        }
        boolean isRoot = getFragmentManager().getBackStackEntryCount() == 0;
        mDrawerToggle.setDrawerIndicatorEnabled(isRoot);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowHomeEnabled(!isRoot);
            getSupportActionBar().setDisplayHomeAsUpEnabled(!isRoot);
            getSupportActionBar().setHomeButtonEnabled(!isRoot);
        }
        if (isRoot) {
            mDrawerToggle.syncState();
        }
    }

    /**
     * Shows the Cast First Time User experience to the user (an overlay that explains what is
     * the Cast icon)
     */
    private void showFtu() {
        Menu menu = mToolbar.getMenu();
        View view = menu.findItem(R.id.media_route_menu_item).getActionView();
        if (view != null && view instanceof MediaRouteButton) {
            IntroductoryOverlay overlay = new IntroductoryOverlay.Builder(this)
                    .setMenuItem(mMediaRouteMenuItem)
                    .setTitleText(R.string.touch_to_cast)
                    .setSingleTime()
                    .build();
            overlay.show();
        }
    }
}


text:
var searchData=
[
  ['operator_20tags',['Operator Tags',['../group___operator_tags.html',1,'']]]
];


text:
default['cubrid']['broker_count'] = 1
default['cubrid']['min_num_appl_server'] = 5
default['cubrid']['max_num_appl_server'] = 40
default['cubrid']['slow_log'] = 'ON'
default['cubrid']['sql_log'] = 'ON'

# the target directory to install CUBRID
default['cubrid']['home'] = "/opt/cubrid"

# CUBRID configurations directory.
set['cubrid']['conf_dir'] = "#{node['cubrid']['home']}/conf"
# Full path to cubrid_broker.conf.
set['cubrid']['broker_conf'] = "#{node['cubrid']['conf_dir']}/cubrid_broker.conf"


text:
package org.jf.dexlib2.dexbacked;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.jf.dexlib2.base.reference.BaseMethodReference;
import org.jf.dexlib2.dexbacked.raw.MethodIdItem;
import org.jf.dexlib2.dexbacked.raw.ProtoIdItem;
import org.jf.dexlib2.dexbacked.raw.TypeListItem;
import org.jf.dexlib2.dexbacked.util.AnnotationsDirectory;
import org.jf.dexlib2.dexbacked.util.FixedSizeList;
import org.jf.dexlib2.dexbacked.util.ParameterIterator;
import org.jf.dexlib2.iface.Annotation;
import org.jf.dexlib2.iface.Method;
import org.jf.dexlib2.iface.MethodParameter;
import org.jf.util.AbstractForwardSequentialList;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;

public class DexBackedMethod extends BaseMethodReference implements Method {
    @Nonnull public final DexBackedDexFile dexFile;
    @Nonnull public final DexBackedClassDef classDef;

    public final int accessFlags;

    private final int codeOffset;
    private final int parameterAnnotationSetListOffset;
    private final int methodAnnotationSetOffset;

    public final int methodIndex;

    private int methodIdItemOffset;
    private int protoIdItemOffset;
    private int parametersOffset = -1;

    public DexBackedMethod(@Nonnull DexReader reader,
                           @Nonnull DexBackedClassDef classDef,
                           int previousMethodIndex) {
        this.dexFile = reader.dexBuf;
        this.classDef = classDef;

        // large values may be used for the index delta, which cause the cumulative index to overflow upon
        // addition, effectively allowing out of order entries.
        int methodIndexDiff = reader.readLargeUleb128();
        this.methodIndex = methodIndexDiff + previousMethodIndex;
        this.accessFlags = reader.readSmallUleb128();
        this.codeOffset = reader.readSmallUleb128();

        this.methodAnnotationSetOffset = 0;
        this.parameterAnnotationSetListOffset = 0;
    }

    public DexBackedMethod(@Nonnull DexReader reader,
                           @Nonnull DexBackedClassDef classDef,
                           int previousMethodIndex,
                           @Nonnull AnnotationsDirectory.AnnotationIterator methodAnnotationIterator,
                           @Nonnull AnnotationsDirectory.AnnotationIterator paramaterAnnotationIterator) {
        this.dexFile = reader.dexBuf;
        this.classDef = classDef;

        // large values may be used for the index delta, which cause the cumulative index to overflow upon
        // addition, effectively allowing out of order entries.
        int methodIndexDiff = reader.readLargeUleb128();
        this.methodIndex = methodIndexDiff + previousMethodIndex;
        this.accessFlags = reader.readSmallUleb128();
        this.codeOffset = reader.readSmallUleb128();

        this.methodAnnotationSetOffset = methodAnnotationIterator.seekTo(methodIndex);
        this.parameterAnnotationSetListOffset = paramaterAnnotationIterator.seekTo(methodIndex);
    }

    public int getMethodIndex() { return methodIndex; }
    @Nonnull @Override public String getDefiningClass() { return classDef.getType(); }
    @Override public int getAccessFlags() { return accessFlags; }

    @Nonnull
    @Override
    public String getName() {
        return dexFile.getString(dexFile.readSmallUint(getMethodIdItemOffset() + MethodIdItem.NAME_OFFSET));
    }

    @Nonnull
    @Override
    public String getReturnType() {
        return dexFile.getType(dexFile.readSmallUint(getProtoIdItemOffset() + ProtoIdItem.RETURN_TYPE_OFFSET));
    }

    @Nonnull
    @Override
    public List<? extends MethodParameter> getParameters() {
        int parametersOffset = getParametersOffset();
        if (parametersOffset > 0) {
            final List<String> parameterTypes = getParameterTypes();

            return new AbstractForwardSequentialList<MethodParameter>() {
                @Nonnull @Override public Iterator<MethodParameter> iterator() {
                    return new ParameterIterator(parameterTypes,
                            getParameterAnnotations(),
                            getParameterNames());
                }

                @Override public int size() {
                    return parameterTypes.size();
                }
            };
        }
        return ImmutableList.of();
    }

    @Nonnull
    public List<? extends Set<? extends DexBackedAnnotation>> getParameterAnnotations() {
        return AnnotationsDirectory.getParameterAnnotations(dexFile, parameterAnnotationSetListOffset);
    }

    @Nonnull
    public Iterator<String> getParameterNames() {
        DexBackedMethodImplementation methodImpl = getImplementation();
        if (methodImpl != null) {
            return methodImpl.getParameterNames(null);
        }
        return Iterators.emptyIterator();
    }

    @Nonnull
    @Override
    public List<String> getParameterTypes() {
        final int parametersOffset = getParametersOffset();
        if (parametersOffset > 0) {
            final int parameterCount = dexFile.readSmallUint(parametersOffset + TypeListItem.SIZE_OFFSET);
            final int paramListStart = parametersOffset + TypeListItem.LIST_OFFSET;
            return new FixedSizeList<String>() {
                @Nonnull
                @Override
                public String readItem(final int index) {
                    return dexFile.getType(dexFile.readUshort(paramListStart + 2*index));
                }
                @Override public int size() { return parameterCount; }
            };
        }
        return ImmutableList.of();
    }

    @Nonnull
    @Override
    public Set<? extends Annotation> getAnnotations() {
        return AnnotationsDirectory.getAnnotations(dexFile, methodAnnotationSetOffset);
    }

    @Nullable
    @Override
    public DexBackedMethodImplementation getImplementation() {
        if (codeOffset > 0) {
            return new DexBackedMethodImplementation(dexFile, this, codeOffset);
        }
        return null;
    }

    private int getMethodIdItemOffset() {
        if (methodIdItemOffset == 0) {
            methodIdItemOffset = dexFile.getMethodIdItemOffset(methodIndex);
        }
        return methodIdItemOffset;
    }

    private int getProtoIdItemOffset() {
        if (protoIdItemOffset == 0) {
            int protoIndex = dexFile.readUshort(getMethodIdItemOffset() + MethodIdItem.PROTO_OFFSET);
            protoIdItemOffset = dexFile.getProtoIdItemOffset(protoIndex);
        }
        return protoIdItemOffset;
    }

    private int getParametersOffset() {
        if (parametersOffset == -1) {
            parametersOffset = dexFile.readSmallUint(getProtoIdItemOffset() + ProtoIdItem.PARAMETERS_OFFSET);
        }
        return parametersOffset;
    }

    /**
     * Skips the reader over the specified number of encoded_method structures
     *
     * @param reader The reader to skip
     * @param count The number of encoded_method structures to skip over
     */
    public static void skipMethods(@Nonnull DexReader reader, int count) {
        for (int i=0; i<count; i++) {
            reader.skipUleb128();
            reader.skipUleb128();
            reader.skipUleb128();
        }
    }
}


text:
'use strict';

const test = require('ava');

const { setupApp } = require('../../helpers/test-helper');
const metricsExample = require('../../../examples/client-metrics.json');
const dbInit = require('../../helpers/database-init');
const getLogger = require('../../../fixtures/no-logger');

let stores;

test.before(async () => {
    const db = await dbInit('metrics_api_client', getLogger);
    stores = db.stores;
});

test.after(async () => {
    await stores.db.destroy();
});

test.serial('should be possble to send metrics', async t => {
    t.plan(0);
    const request = await setupApp(stores);
    return request
        .post('/api/client/metrics')
        .send(metricsExample)
        .expect(202);
});

test.serial('should require valid send metrics', async t => {
    t.plan(0);
    const request = await setupApp(stores);
    return request
        .post('/api/client/metrics')
        .send({
            appName: 'test',
        })
        .expect(400);
});

test.serial('should register client', async t => {
    t.plan(0);
    const request = await setupApp(stores);
    return request
        .post('/api/client/register')
        .send({
            appName: 'demo',
            instanceId: 'test',
            strategies: ['default'],
            started: Date.now(),
            interval: 10,
        })
        .expect(202);
});

test.serial('should allow client to register multiple times', async t => {
    t.plan(0);
    const request = await setupApp(stores);
    const clientRegistration = {
        appName: 'multipleRegistration',
        instanceId: 'test',
        strategies: ['default', 'another'],
        started: Date.now(),
        interval: 10,
    };

    return request
        .post('/api/client/register')
        .send(clientRegistration)
        .expect(202)
        .then(() =>
            request
                .post('/api/client/register')
                .send(clientRegistration)
                .expect(202),
        );
});

test.serial('should accept client metrics', async t => {
    t.plan(0);
    const request = await setupApp(stores);
    return request
        .post('/api/client/metrics')
        .send({
            appName: 'demo',
            instanceId: '1',
            bucket: {
                start: Date.now(),
                stop: Date.now(),
                toggles: {},
            },
        })
        .expect(202);
});


text:
import { createSelector } from 'reselect'
import { arrayIntersection } from '../util'

/** ------------------------------ */
// Posts selectors and helpers
/** ------------------------------ */

/**
 * Creates a selector that returns IDs of posts of the given category
 * or an empty array if none
 * Use case: select posts "HOT" posts
 */
export const categorySelectorFactory = category => state => state.posts.byCategory[category] || []

/**
 * Creates a selector that returns IDs of posts that belong to the given subreddit
 * or an empty array if none
 * Use case: select posts from "WEBDEV"
 */
export const subredditSelectorFactory = subreddit => state => state.posts.bySubreddit[subreddit] || []

/**
 * Creates a selector that returns IDs of posts that belong to the
 * given subreddit AND the given category (UNION).
 * Use Case: select "HOT" posts from "WEBDEV".
 */
export const categorySubredditSelectorFactory = (category, subreddit) => createSelector(
  categorySelectorFactory(category),
  subredditSelectorFactory(subreddit),
  arrayIntersection
)

/**
 * Maps an array of ids to an array of Posts
 */
export const mapIdsToPosts = state => ids => ids.map(id => state.posts.byId[id])


text:
\documentclass[9pt,twocolumn,twoside]{../../styles/osajnl}
\usepackage{fancyvrb}
\journal{i524}

\title{Music Predictive Analysis Project based on Lyrics}

\author[1,*]{Leonard Mwangi}

\affil[1]{School of Informatics and Computing, Bloomington, IN 47408, U.S.A.}

\affil[*]{Corresponding authors: lmwangi@iu.edu}

\dates{project-01, \today}

\ociscodes{Cloud, I524}

% replace this with your url in github/gitlab
\doi{\url{https://github.com/lmundia/sp17-i524/tree/master/project/S17-IO-3013/report/report.pdf}}

\begin{abstract}
Being certain that lyrics of your song will lead to the next greatest
hit would boost confidence to a lot of amateur artists who are faced
with fears of never making it thus never attempting to make good their
creativity. With Machine Learning (ML) this can be a thing of the
past, these artists would have the ability to let ML models determine
the viability of their lyrics becoming the next hit based on history
of other songs that have made it to top. Through training, the model
can certainly determine the outcome of different songs which will be
depicted in this project.\newline
\end{abstract}

\setboolean{displaycopyright}{true}

\begin{document}

\maketitle

\section{Introduction}
When faced with the decision to forward their song to a recording
company, amateur artists find it daunting due to uncertainty of
whether their song would be recorded and if it is if it will make them
wealthy.  Having ability to run the lyrics through a predictive
analysis process that would determine the viability of the song making
it would be a huge win and confidence booster to many artists. That
prediction is achievable by use of machine learning and creating a
model that takes already greatest his and trains it to determine what
makes the song successful. This would be done by analyzing the lyrics,
the locality and time of release.

In this project, we will utilize machine learning to help determine
the viability of a song becoming the next greatest hit based on the
lyrics, time of production, locality and the artist. The project will
utilize the greatest hits of all time [1] to train a model which will
then be used to analyze larger dataset of random songs [2] and provide
an in-depth analysis of the next possible hit. The project will
utilize a Hadoop cluster deployed on Chameleon Cloud using CloudMesh
to accomplish this analysis.

\section{Environment}

To achieve the analysis, Cloudmesh was used in order to allow the end
users ability to choose a cloud of their liking. Chameleon Cloud and
Jetstream were used for initial testing but changing the default cloud
on CloudMesh would allow deployment to other clouds.

\subsection{Cloudmesh}

Cloudmesh is an open source component aimed at delivering
software-defined system. It's a collection of virtualized bare-metal
infrastructure, networks, application, systems and platform software
unifying different clouds as a Cloud Testbeds as a Service (CTaas)
\cite{cloudmesh}. Cloudmesh was developed by Professor Gregor von
Laszewski in collaboration with his team at Indiana University \cite{multipleclouds}. In this environment, cloudmesh is used to
automate installation of a four-node cluster.

\subsection{Ansible}

Ansible is also an open source platform used in automation of
deployments and tasks executions  \cite{ansible} . It has the ability to
execute scripts to a remote system thus making it easy to administer
and manage hosts farm. Ansible is written in Python thus it requires
python to be installed in the remote host for successful executions.

\subsubsection{Ansible Playboks}

Deemed as the real strength of Ansible, a playbook is a collection of
instructions that defines what Ansible will do when it connects to
each host \cite{docansible} . Playbooks are written in YAML an easy to
read data serialization language  \cite{yaml} . In this project, Ansible
is used to deploy the required components to successfully accomplished
the deployment, configuration and analysis of the defined files.

\subsection{Apache Spark}

Apache Spark is an open-source data processing and analytics engine
designed to handle large scale dataset. Spark was originally developed
by UC Berkeley but has been adopted in the Apache software stack since
2013  \cite{amplab}. Spark has the ability to run as part of Hadoop,
Mesos, Standalone or in a cloud environment  \cite{spark}. In this
project, Spark is deployed as a standalone environment and primarily
used to analyze music data to in order to identify patterns and make
predictions.

\subsection{MongoDB}

MongoDB is a NoSQL, open source database program aimed at hosting
documents in JSON-like format. MongoDB is favorable in storing
unstructured data since it does not follow the traditional RDBMS
structure. Its performance is also paramount when coupling related
unstructured data  \cite{mongod}. For this project, MongoDB become the
ideal database application because the source data structure is unknow
and it can span in many directions where one dataset doesn't resemble
the next. Putting such data in a structured database program would be
cumbersome.

\subsection{Python}

Python is used as the programming of choice in this project due to its
extensibility and also as a requirement for Ansible to execute
successfully.

\section{Deployment}

Environment deployment is automated as mentioned earlier using
Cloudmesh and Ansible scripts. The environment is deployed on a 4-node
cluster with the following resources.

\subsection{Resources Table}

Table \ref{tab:shape-functions} resources.

\begin{table}[htbp]
\centering
\caption{\bf resources dedicated to the environment}
\begin{tabular}{ccc}
\hline
Node & Role & Flavor  \\
\hline
$Node 1$ & $Spark$ & $m1.small$ \\
$Node 2$ & $Mesos$ & $m1.small$ \\
$Node 3$ & $MongoDB$ & $m1.medium$ \\
$Node 4$ & $Analytics$ & $m1.small$ \\
\hline
\end{tabular}
  \label{tab:shape-functions}
\end{table}

\subsection{Cloudmesh}
Code snippet below generates 4 node cluster that will be used in the
inventory file for the Ansible roles. In order to use Cloudmesh
Cluster, the following package levels or higher must be installed
\begin{itemize}
\item Cloudmesh client 4.7.2
\item Pip 8.1.2
\item Python 2.7.12
\end{itemize}

\begin{algorithm}
\caption{cloudmesh code}\label{alg:python}
\begin{quote}
\begin{Verbatim}[numbers=left]
\$ cm cluster define --count 4 --image CC-Ubuntu16.04
\$ cm cluster use cluster-001
\$ cm cluster allocate
\$ cm cluster nodes > inventory.txt
\end{Verbatim}
\end{quote}
\end{algorithm}

\subsubsection {format inventory file}
Define roles in the inventory file and also remove the resolved
name. After formatting the inventory file, the server roles and their
corresponding public IP address should look similar to the output
below with the right IP address.

\begin{algorithm}
\caption{Inventory file}\label{alg:python}
\begin{quote}
\begin{Verbatim}[numbers=left]
[spark\_server]
<ip address>

[mesos\_server]
<ip address>

[mongo\_server]
<ip address>

[data\_node]
<ip address>
\end{Verbatim}
\end{quote}
\end{algorithm}

\subsection{Ansible}
After configuring deployment of virtual machines and configuring the
inventory.txt, Ansible playbooks are used to automate deployment of
the required components to the nodes defined above.
The following Ansible files are included:
ansible.cfg – used to define default configurations for Ansible including role\_path and remote user.

\begin{algorithm}
\caption{ansible config file}\label{alg:python}
\begin{quote}
\begin{Verbatim}[numbers=left]
[defaults]
roles\_path = roles
host\_key_checking=false
callback\_whitelist = profile_tasks
remote\_user=cc
\end{Verbatim}
\end{quote}
\end{algorithm}

\subsubsection{Playbooks}

The following playbooks are utilized for deployment

\begin{enumerate}
  \item predict.yml – main file for the playbooks, used to call all
    the other playbooks and define their locations. Role-based
    playbooks are contained in scripts directory of the environment.
  \item spark.yml – used to define the host, roles location and
    execution of Spark installation playbook. The playbooks redirect
    the folder structure to /roles/ansible-role-spark.
    \begin{itemize}
      \item Tasks directory - contains main.yml playbook that's used
        to define all the tasks for Spark installation.
      \item Defaults directory – contains main.yml that defines the
        default requirements for Spark installation including the
        spark version and download site for the distribution.
    \end{itemize}

    \item mesos.yml – used to define the host, roles location and
      execution of MongoDB installation playbook. The playbooks
      redirect the folder structure to /roles/ansible-role-mesos.
       \begin{itemize}
      \item tasks directory – contains main.yml playbook that checks
        the operating system to determine the flavor of mesos that
        would be deployed. The environment contains playbooks for
        Debian and Redhat flavors.
      \item defaults directory – contains main.yml which defines the
        version of mesos that will be downloaded and installed.
       \end{itemize}
    \item mongo.yml – used to define the host, roles location and
      execution of MongoDB installation playbook. The playbooks
      redirect the folder structure to /roles/ansible-role-mongo.
      \begin{itemize}
      \item tasks directory - contains main.yml playbook that's used
        to define all the tasks for MongoDB installation. The file
        also includes task to create a database and initial user for
        the Mongo environment.
      \item defaults directory – contains main.yml that defines the
        default requirements for MongoDB installation including the
        MongoD version and download site for the distribution.
      \item vars directory – contains main.yml that defines the
        variables for the environment like data path, admin account
        and password.
      \item template directory – contains mongod\_config.j2 file which
        is used to define MongoDB configurations.
      \end{itemize}

      \item data.yml - used to define the host, roles location and
        execution of dataset playbook. The playbooks redirect the
        folder structure to /roles/ansible-role-dataset.
        \begin{itemize}
        \item tasks directory - contains main.yml playbook that's
          downloads the MillionSongs dataset and copies into to
          MongoDB. The file also contains task to create collection
          and load data into MongoDB by executing a remote file
          myfiles.py
        \end{itemize}

\end{enumerate}

\section{Conclusion}

Ability for amateur artists, artists and record labels to quick
determine the viability of a hit is paramount to their success and
missed chances due to inexperience, fear of unknows, bad song or
acting when time is not ripe can be costly. Machine learning has the
ability to change these outcomes, a well-trained model can help
determine with high accuracy where the song will end up.

% Bibliography

\bibliography{references}

\end{document}


text:
package com.alibaba.jstorm.container.cgroup.core;

import java.io.IOException;

import com.alibaba.jstorm.container.CgroupUtils;
import com.alibaba.jstorm.container.Constants;
import com.alibaba.jstorm.container.SubSystemType;
import com.alibaba.jstorm.container.cgroup.Device;

public class NetClsCore implements CgroupCore {

    public static final String NET_CLS_CLASSID = "/net_cls.classid";

    private final String dir;

    public NetClsCore(String dir) {
        this.dir = dir;
    }

    @Override
    public SubSystemType getType() {
        // TODO Auto-generated method stub
        return SubSystemType.net_cls;
    }

    private StringBuilder toHex(int num) {
        String hex = num + "";
        StringBuilder sb = new StringBuilder();
        int l = hex.length();
        if (l > 4) {
            hex = hex.substring(l - 4 - 1, l);
        }
        for (; l < 4; l++) {
            sb.append('0');
        }
        sb.append(hex);
        return sb;
    }

    public void setClassId(int major, int minor) throws IOException {
        StringBuilder sb = new StringBuilder("0x");
        sb.append(toHex(major));
        sb.append(toHex(minor));
        CgroupUtils.writeFileByLine(
                Constants.getDir(this.dir, NET_CLS_CLASSID), sb.toString());
    }

    public Device getClassId() throws IOException {
        String output =
                CgroupUtils.readFileByLine(
                        Constants.getDir(this.dir, NET_CLS_CLASSID)).get(0);
        output = Integer.toHexString(Integer.parseInt(output));
        int major = Integer.parseInt(output.substring(0, output.length() - 4));
        int minor = Integer.parseInt(output.substring(output.length() - 4));
        return new Device(major, minor);
    }

}


text:
package com.venky.cache;

import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.nio.channels.FileLock;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.CompatibleFieldSerializer;

import de.javakaffee.kryoserializers.JdkProxySerializer;

public  class KryoStore {
	Store fileStore ;
	Kryo kryo ;
	Input ki;
	Output ko;
	private void ensureDir(File directory){
        directory.mkdirs();
        if (!directory.exists()) {
            throw new RuntimeException("Unable to create directory " + directory );
        }else if (!directory.isDirectory()) {
            throw new RuntimeException(directory + " is not a directory!");
        }
    }
	public KryoStore(String storePath) {
		this(new File(storePath));
	}
    public KryoStore(File store) {
        ensureDir(store.getParentFile());
		try {
            fileStore = new Store(store,"rws");
			kryo = createCryo();
			ki = new Input(fileStore.getInputStream());
			ko = new Output(fileStore.getOutputStream());
		} catch (FileNotFoundException e) {
			throw new KryoException(e); //Soften the exception.
		}

	}
	public void flush() {
        ko.flush();
    }
	public boolean eof() {
	    try {
            return (fileStore.getInputStream().available() <=0 && ki.available() <= 0);
        }catch (IOException e){
	        if (e instanceof  EOFException){
	            return true;
            }
            throw new RuntimeException(e);
        }
	}
	public long getWriterPosition() {
		try {
			return fileStore.position() + ( ko.position() );
		} catch (IOException e) {
			throw new KryoException(e); //Soften the exception.
		}
	}
	public long getReaderPosition(){
		try {
			return fileStore.position() - ( ki.limit() - ki.position());
		} catch (IOException e) {
			throw new KryoException(e); //Soften the exception.
		}
	}
	public void position(long offset){
		try {
			if (ko.position() >0 ) {
				//Pending flush
				ko.flush();
			}
			fileStore.position(offset);
			ki = new Input(fileStore.getInputStream());
			ko = new Output(fileStore.getOutputStream());
		} catch (IOException e) {
			throw new KryoException(e); //Soften the exception.
		}
	}
	@SuppressWarnings("unchecked")
	public <T> T read()  {
		return (T) kryo.readClassAndObject(ki);
	}
	public <T> void write(T object){
		kryo.writeClassAndObject(ko, object);
	}

	public void truncate(long size) {
		try {
			fileStore.truncate(size);
		} catch (IOException e) {
			throw new KryoException(e); //Soften the exception.
		}
	}

	protected Kryo createCryo(){
		Kryo kryo = new Kryo();
		kryo.setClassLoader(getClass().getClassLoader());
		kryo.setDefaultSerializer(CompatibleFieldSerializer.class);
		kryo.register(InvocationHandler.class,new JdkProxySerializer());

		return kryo;
	}

	public void close(){
		ki.close();
		ko.close();
        try {
            fileStore.close();
        } catch (IOException e) {
            throw new KryoException(e);
        }
    }
	public void delete() {
		close();
        try {
            fileStore.delete();
        } catch (IOException e) {
            throw new KryoException(e);
        }
    }

	public long size(){
        try {
            return fileStore.size();
        } catch (IOException e) {
            throw new KryoException(e);
        }
    }
    public FileLock lock() {
        try {
            return fileStore.lock();
        } catch (IOException e) {
            throw new KryoException(e);
        }
    }
}


text: Rails.application.config.session_store :cookie_store, key: '_h8Rd8_session'


text:
module Renalware
  module Transplants
    WAITLIST_FILTERS = %w(
      all
      active
      suspended
      active_and_suspended
      working_up
      status_mismatch
    ).freeze

    def self.table_name_prefix
      "transplant_"
    end

    def self.cast_patient(patient)
      ActiveType.cast(patient, ::Renalware::Transplants::Patient)
    end
  end
end


text:
import {
  Component,
  OnInit
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'about',
  styles: ['./about.component.css'],
  templateUrl: './about.component.html'
})
export class AboutComponent implements OnInit {

  public localState: any;

  constructor(
    public route: ActivatedRoute
  ) {

  }

  private flexBorderSize: number = 1;
  private flexImageSize: number = 10;
  private galleryName: string = '';

  public ngOnInit() {
    this.route
      .data
      .subscribe((data: any) => {
        // your resolved data from route
        this.localState = data.yourData;
      });
    this.asyncDataWithWebpack();
  }
  private asyncDataWithWebpack() {
    setTimeout(() => {

      System.import('../../assets/mock-data/mock-data.json')
        .then((json) => {
          //console.log('async mockData', json);
          this.localState = json;
        });

    });
  }

  onViewerVisibilityChanged(isVisibile: boolean) {
   // console.log('viewer visible: ' + isVisibile);
  }
}


text:
require 'rails_helper'

describe ApplicationController, :type => :controller do

end


text:
package ui.premiseView

import javax.swing.JFrame

/**
  * Created by MarioDiniz on 16/12/16.
  */
class LogicCompiler extends JFrame {

}


text:
package org.gwtbootstrap3.client.ui;

import org.gwtbootstrap3.client.ui.constants.Styles;

import com.google.gwt.dom.client.Document;
import com.google.gwt.i18n.client.HasDirection.Direction;
import com.google.gwt.i18n.shared.DirectionEstimator;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.user.client.DOM;

/**
 * An inline check box widget.
 *
 * @author Sven Jacobs
 * @see org.gwtbootstrap3.client.ui.CheckBox
 */
public class InlineCheckBox extends CheckBox {

    /**
     * Creates a check box with the specified text label.
     *
     * @param label
     *            the check box's label
     */
    public InlineCheckBox(SafeHtml label) {
        this(label.asString(), true);
    }

    /**
     * Creates a check box with the specified text label.
     *
     * @param label
     *            the check box's label
     * @param dir
     *            the text's direction. Note that {@code DEFAULT} means
     *            direction should be inherited from the widget's parent
     *            element.
     */
    public InlineCheckBox(SafeHtml label, Direction dir) {
        this();
        setHTML(label, dir);
    }

    /**
     * Creates a check box with the specified text label.
     *
     * @param label
     *            the check box's label
     * @param directionEstimator
     *            A DirectionEstimator object used for automatic direction
     *            adjustment. For convenience,
     *            {@link #DEFAULT_DIRECTION_ESTIMATOR} can be used.
     */
    public InlineCheckBox(SafeHtml label, DirectionEstimator directionEstimator) {
        this();
        setDirectionEstimator(directionEstimator);
        setHTML(label.asString());
    }

    /**
     * Creates a check box with the specified text label.
     *
     * @param label
     *            the check box's label
     */
    public InlineCheckBox(String label) {
        this();
        setText(label);
    }

    /**
     * Creates a check box with the specified text label.
     *
     * @param label
     *            the check box's label
     * @param dir
     *            the text's direction. Note that {@code DEFAULT} means
     *            direction should be inherited from the widget's parent
     *            element.
     */
    public InlineCheckBox(String label, Direction dir) {
        this();
        setText(label, dir);
    }

    /**
     * Creates a label with the specified text and a default direction
     * estimator.
     *
     * @param label
     *            the check box's label
     * @param directionEstimator
     *            A DirectionEstimator object used for automatic direction
     *            adjustment. For convenience,
     *            {@link #DEFAULT_DIRECTION_ESTIMATOR} can be used.
     */
    public InlineCheckBox(String label, DirectionEstimator directionEstimator) {
        this();
        setDirectionEstimator(directionEstimator);
        setText(label);
    }

    /**
     * Creates a check box with the specified text label.
     *
     * @param label
     *            the check box's label
     * @param asHTML
     *            true to treat the specified label as html
     */
    public InlineCheckBox(String label, boolean asHTML) {
        this();
        if (asHTML) {
            setHTML(label);
        } else {
            setText(label);
        }
    }

    public InlineCheckBox() {
        super(DOM.createLabel(), Document.get().createCheckInputElement());
        setStyleName(Styles.CHECKBOX_INLINE);

        getElement().appendChild(inputElem);
        getElement().appendChild(labelElem);
    }

}


text:
Just a few LISP coding tricks

asdas

Just a few LISP coding tricks

asdas

 '(home (©2019 ("Tim Menzies")))
'(:site (src (contrib (discuss)))

  :code (lib (oo (sample))))

Just a few LISP coding tricks

asdas

asd asd as asd


text:
<?php
namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class MessageRedirect extends AbstractPlugin{
    public function __invoke($title, $msg) {
        //set flash msg and redirect
        $flashMsger = $this->getController()->flashmessenger();
        $flashMsger->addMessage($title . ':::' . $msg, 'messagePage');
        return $this->getController()->redirect()->toRoute('message');
    }
}


text:
const IPHistoryData = require('./iphistory.data');
const IPHistoryUI   = require('./iphistory.ui');
const BinarySocket  = require('../../../../../base/socket');

const IPHistoryInit = (() => {
    const responseHandler = (response) => {
        if (response.error && response.error.message) {
            return IPHistoryUI.displayError(response.error.message);
        }
        const parsed = response.login_history.map(IPHistoryData.parse);
        return IPHistoryUI.update(parsed);
    };

    const init = () => {
        const req = {
            login_history: '1',
            limit        : 50,
        };
        BinarySocket.send(req).then((response) => {
            responseHandler(response);
        });
    };

    const clean = () => {
        IPHistoryUI.clean();
    };

    return {
        init,
        clean,
    };
})();

module.exports = IPHistoryInit;