text:
require 'spec_helper'

describe 'sensu::plugin', :type => :define do
  let(:pre_condition) do
    <<-'ENDofPUPPETcode'
    class { '::sensu':
      manage_plugins_dir => false,
    }
    ENDofPUPPETcode
  end

  context 'file' do
    let(:title) { 'puppet:///data/plug1' }

    context 'defaults' do
      it { should contain_file('/etc/sensu/plugins/plug1').with(
        :source => 'puppet:///data/plug1'
      ) }
    end

    context 'setting params' do
      let(:params) { {
        :install_path => '/var/sensu/plugins',
      } }

      it { should contain_file('/var/sensu/plugins/plug1').with(
        :source => 'puppet:///data/plug1'
      ) }
    end
  end

  context 'url' do
    let(:title) { 'https://raw.githubusercontent.com/sensu/sensu-community-plugins/master/plugins/system/check-mem.sh' }

    context 'defaults' do
      let(:params) { {
        :type         => 'url',
        :pkg_checksum => '1d58b78e9785f893889458f8e9fe8627'
      } }

      it { should contain_remote_file('https://raw.githubusercontent.com/sensu/sensu-community-plugins/master/plugins/system/check-mem.sh').with(
        :ensure   => 'present',
        :path     => '/etc/sensu/plugins/check-mem.sh',
        :checksum => '1d58b78e9785f893889458f8e9fe8627'
      ) }
    end

    context 'setting params' do
      let(:params) { {
        :type         => 'url',
        :install_path => '/var/sensu/plugins',
        :pkg_checksum => '1d58b78e9785f893889458f8e9fe8627'
      } }

      it { should contain_remote_file('https://raw.githubusercontent.com/sensu/sensu-community-plugins/master/plugins/system/check-mem.sh').with(
        :ensure   => 'present',
        :path     => '/var/sensu/plugins/check-mem.sh',
        :checksum => '1d58b78e9785f893889458f8e9fe8627'
      ) }
    end

    context 'new plugin should provide source' do
      let(:title) { 'https://raw.githubusercontent.com/sensu-plugins/sensu-plugins-puppet/master/bin/check-puppet-last-run.rb' }
      let(:params) { {
        :type         => 'url',
        :install_path => '/var/sensu/plugins',
      } }

      it { should contain_remote_file('https://raw.githubusercontent.com/sensu-plugins/sensu-plugins-puppet/master/bin/check-puppet-last-run.rb').with(
        :ensure   => 'present',
        :path     => '/var/sensu/plugins/check-puppet-last-run.rb',
        :source   => 'https://raw.githubusercontent.com/sensu-plugins/sensu-plugins-puppet/master/bin/check-puppet-last-run.rb'
      ) }
    end
  end

  context 'directory' do
    let(:title) { 'puppet:///data/sensu/plugins' }

    context 'defaults' do
      let(:params) { { :type => 'directory' } }

      it { should contain_file('/etc/sensu/plugins_for_plugin_puppet:///data/sensu/plugins').with(
        'source'  => 'puppet:///data/sensu/plugins',
        'path'    => '/etc/sensu/plugins',
        'ensure'  => 'directory',
        'recurse' => 'true',
        'force'   => 'true',
        'purge'   => 'true'
      ) }
    end

    context 'set install_path' do
      let(:params) { { :type => 'directory', :install_path => '/opt/sensu/plugins' } }

      it { should contain_file('/opt/sensu/plugins_for_plugin_puppet:///data/sensu/plugins').with(
        'path' => '/opt/sensu/plugins',
      ) }
    end

    context 'set purge params' do
      let(:params) { { :type => 'directory', :recurse => false, :force => false, :purge => false } }

      it { should contain_file('/etc/sensu/plugins_for_plugin_puppet:///data/sensu/plugins').with(
        'recurse' => false,
        'purge'   => false,
        'force'   => false,
        'mode'    => '0555',
        'owner'   => 'sensu',
        'group'   => 'sensu'
      ) }
    end
  end

  context 'package' do
    let(:title) { 'sensu-plugins' }

    context 'default' do
      let(:params) { { :type => 'package' } }

      it { should contain_package('sensu-plugins').with_ensure('latest') }

      it do
        should contain_package('sensu-plugins').with({
          'ensure'          => 'latest',
          'provider'        => nil,
          'install_options' => nil,
        })
      end
    end

    context 'set pkg_version' do
      let(:params) { { :type => 'package', :pkg_version => '1.1.1' } }

      it { should contain_package('sensu-plugins').with_ensure('1.1.1') }
    end

    context 'set pkg_provider' do
      let(:params) { { :type => 'package', :pkg_provider => 'sensu_gem' } }

      it { should contain_package('sensu-plugins').with_provider('sensu_gem') }
    end

    context 'without pkg_provider set' do
      let(:params) { { :type => 'package' } }

      it { should contain_package('sensu-plugins').with_provider(nil) }
    end

    # without pkg_provider => gem gem_install_options will be ignored
    context 'set gem_install_options' do
      let(:params) { { :type => 'package', :gem_install_options => [{ '-p' => 'http://user:pass@myproxy.company.org:8080' }] } }
      it { should contain_package('sensu-plugins').with_install_options(nil) }
    end

    context 'set gem_install_options and pkg_provider = gem' do
      let(:params) { { :type => 'package', :gem_install_options => [{ '-p' => 'http://user:pass@myproxy.company.org:8080' }], :pkg_provider => 'gem' } }
      it { should contain_package('sensu-plugins').with_install_options([{ '-p' => 'http://user:pass@myproxy.company.org:8080' }]) }
    end
  end

  context 'default' do
    let(:params) { { :type => 'unknown' } }
    it { expect { should raise_error(Puppet::Error) } }
  end

  describe 'ordering (#463)' do
  let(:pre_condition) do
    <<-'ENDofPUPPETcode'
    class { '::sensu':
      manage_plugins_dir => false,
    }
    sensu::check { 'ntp':
      command     => 'check_ntp_time -H pool.ntp.org -w 30 -c 60',
      handlers    => 'default',
      subscribers => 'sensu-test',
    }
    ENDofPUPPETcode
  end
    let(:title) { 'puppet:///data/plug1' }
    describe 'notifies the sensu-client service' do
      let(:expected) { { notify: ['Service[sensu-client]'] } }
      it { is_expected.to contain_sensu__plugin(title).with(expected)}
    end
    describe 'comes before sensu checks via Anchor[plugins_before_checks]' do
      let(:expected) { { before: ['Anchor[plugins_before_checks]'] } }
      it { is_expected.to contain_sensu__plugin(title).with(expected)}
    end
  end
end


text:
package edu.hm.hafner.analysis.parser.jcreport;

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

/**
 * This is the Report-Class. It is mandatory to create Warnings. It represents the outer-most node within the
 * report.xml.
 *
 * @author Johann Vierthaler, johann.vierthaler@web.de
 */
public class Report {
    private List<File> files = new ArrayList<>();

    /**
     * Returns an unmodifiable Collection.
     *
     * @return files getter
     */
    public List<File> getFiles() {
        return Collections.unmodifiableList(files);
    }

    /**
     * Setter for the List files.
     *
     * @param files a list of files.
     */
    public void setFiles(final List<File> files) {
        this.files = files;
    }

    /**
     * Adds a new File to the Collection.
     *
     * @param file setter
     */
    public void addFile(final File file) {
        files.add(file);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<<<<<<< HEAD
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.techversat.ledimanager;

public final class R {
    public static final class array {
        public static final int settings_font_size_name=0x7f050000;
        public static final int settings_font_size_value=0x7f050001;
    }
    public static final class attr {
    }
    public static final class drawable {
        public static final int connected=0x7f020000;
        public static final int connected_large=0x7f020001;
        public static final int disconnected=0x7f020002;
        public static final int disconnected_large=0x7f020003;
        public static final int ic_launcher=0x7f020004;
        public static final int ic_launcher_ledi=0x7f020005;
    }
    public static final class id {
        public static final int about=0x7f080013;
        public static final int button1=0x7f080001;
        public static final int button2=0x7f080002;
        public static final int button3=0x7f080003;
        public static final int button4=0x7f080004;
        public static final int button5=0x7f080007;
        public static final int editText1=0x7f080006;
        public static final int exit=0x7f080014;
        public static final int image=0x7f08000c;
        public static final int layout=0x7f080009;
        public static final int linearLayout1=0x7f080000;
        public static final int linearLayout2=0x7f080005;
        public static final int menu_settings=0x7f08000e;
        public static final int settings=0x7f080012;
        public static final int start=0x7f08000f;
        public static final int stop=0x7f080010;
        public static final int test=0x7f080011;
        public static final int text=0x7f08000d;
        public static final int text1=0x7f08000a;
        public static final int text2=0x7f08000b;
        public static final int textView1=0x7f080008;
    }
    public static final class layout {
        public static final int activity_main=0x7f030000;
        public static final int device_selection=0x7f030001;
        public static final int list_item=0x7f030002;
        public static final int notification=0x7f030003;
        public static final int settings=0x7f030004;
    }
    public static final class menu {
        public static final int menu=0x7f070000;
    }
    public static final class string {
        public static final int activitiy_title_main=0x7f040015;
        public static final int activitiy_title_settings=0x7f040017;
        public static final int activitiy_title_tests=0x7f040016;
        public static final int app_name=0x7f040000;
        public static final int hello_world=0x7f040001;
        public static final int menu_settings=0x7f040002;
        public static final int settings_Alarm=0x7f04000d;
        public static final int settings_Alarm_desc=0x7f04000e;
        public static final int settings_Call=0x7f040007;
        public static final int settings_Call_desc=0x7f040008;
        public static final int settings_Device=0x7f040011;
        public static final int settings_K9=0x7f04000b;
        public static final int settings_K9_desc=0x7f04000c;
        public static final int settings_Mac=0x7f040012;
        public static final int settings_Mac_desc=0x7f040013;
        public static final int settings_Main=0x7f040003;
        public static final int settings_Music=0x7f04000f;
        public static final int settings_Music_desc=0x7f040010;
        public static final int settings_Notifications=0x7f040006;
        public static final int settings_Other=0x7f040014;
        public static final int settings_SMS=0x7f040009;
        public static final int settings_SMS_desc=0x7f04000a;
        public static final int settings_StartOnBoot=0x7f040004;
        public static final int settings_StartOnBoot_desc=0x7f040005;
    }
    public static final class style {
        /**
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.

         */
        public static final int AppBaseTheme=0x7f060000;
        /**  Application theme.
 All customizations that are NOT specific to a particular API-level can go here.
         */
        public static final int AppTheme=0x7f060001;
    }
}
=======
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.techversat.ledimanager;

public final class R {
    public static final class array {
        public static final int settings_font_size_name=0x7f050000;
        public static final int settings_font_size_value=0x7f050001;
    }
    public static final class attr {
    }
    public static final class drawable {
        public static final int connected=0x7f020000;
        public static final int connected_large=0x7f020001;
        public static final int disconnected=0x7f020002;
        public static final int disconnected_large=0x7f020003;
        public static final int dk_grey=0x7f02000a;
        public static final int green=0x7f020007;
        public static final int grey=0x7f020009;
        public static final int ic_launcher=0x7f020004;
        public static final int ic_launcher_ledi=0x7f020005;
        public static final int lt_grey=0x7f020008;
        public static final int red=0x7f020006;
        public static final int white=0x7f02000b;
    }
    public static final class id {
        public static final int about=0x7f080016;
        public static final int button1=0x7f080001;
        public static final int button2=0x7f080002;
        public static final int button3=0x7f080003;
        public static final int button4=0x7f080004;
        public static final int button5=0x7f080008;
        public static final int button6=0x7f080005;
        public static final int dots=0x7f080010;
        public static final int editText1=0x7f080007;
        public static final int exit=0x7f080017;
        public static final int image=0x7f08000d;
        public static final int layout=0x7f08000a;
        public static final int linearLayout1=0x7f080000;
        public static final int linearLayout2=0x7f080006;
        public static final int menu_clear=0x7f080018;
        public static final int menu_settings=0x7f080011;
        public static final int root=0x7f08000f;
        public static final int settings=0x7f080015;
        public static final int start=0x7f080012;
        public static final int stop=0x7f080013;
        public static final int test=0x7f080014;
        public static final int text=0x7f08000e;
        public static final int text1=0x7f08000b;
        public static final int text2=0x7f08000c;
        public static final int textView1=0x7f080009;
    }
    public static final class layout {
        public static final int activity_main=0x7f030000;
        public static final int device_selection=0x7f030001;
        public static final int list_item=0x7f030002;
        public static final int notification=0x7f030003;
        public static final int settings=0x7f030004;
        public static final int virtual_ledi=0x7f030005;
    }
    public static final class menu {
        public static final int menu=0x7f070000;
        public static final int simple_menu=0x7f070001;
    }
    public static final class string {
        public static final int activitiy_title_main=0x7f040019;
        public static final int activitiy_title_settings=0x7f04001b;
        public static final int activitiy_title_tests=0x7f04001a;
        public static final int app_name=0x7f040004;
        public static final int defaultText=0x7f040000;
        public static final int hello_world=0x7f040005;
        public static final int labelGreen=0x7f040002;
        public static final int labelRed=0x7f040001;
        public static final int menuClear=0x7f040003;
        public static final int menu_settings=0x7f040006;
        public static final int settings_Alarm=0x7f040011;
        public static final int settings_Alarm_desc=0x7f040012;
        public static final int settings_Call=0x7f04000b;
        public static final int settings_Call_desc=0x7f04000c;
        public static final int settings_Device=0x7f040015;
        public static final int settings_K9=0x7f04000f;
        public static final int settings_K9_desc=0x7f040010;
        public static final int settings_Mac=0x7f040016;
        public static final int settings_Mac_desc=0x7f040017;
        public static final int settings_Main=0x7f040007;
        public static final int settings_Music=0x7f040013;
        public static final int settings_Music_desc=0x7f040014;
        public static final int settings_Notifications=0x7f04000a;
        public static final int settings_Other=0x7f040018;
        public static final int settings_SMS=0x7f04000d;
        public static final int settings_SMS_desc=0x7f04000e;
        public static final int settings_StartOnBoot=0x7f040008;
        public static final int settings_StartOnBoot_desc=0x7f040009;
    }
    public static final class style {
        /**
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.

         */
        public static final int AppBaseTheme=0x7f060000;
        /**  Application theme.
 All customizations that are NOT specific to a particular API-level can go here.
         */
        public static final int AppTheme=0x7f060001;
    }
}
>>>>>>> 08d591b8e71d36124faac1e1916fe90cdb75fe10


text:
from __future__ import print_function
import os
import sys
import time
from mock import Mock as MagicMock

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))

import plaso
from plaso import dependencies

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
    'sphinxcontrib.napoleon'
]

# There are many of dependencies we can't install on readthedocs, as it's
# not possible to install any python library that has a C dependency, and
# installing non-PyPi packages requires a complicated requirements.txt,
# so instead, we need to mock them.
class Mock(MagicMock):
  # Ensure the mock sqlite method will be loaded.
  sqlite_version_info = (3, 7, 9)

  @classmethod
  def __getattr__(cls, name):
    return Mock()

  # We always have the most up to date version of everything.
  def get_version(self):
    return time.strftime(u'%Y%m%d')

  # We're mocking pyparsing, and some parsers use the + method in their init,
  # So mock it.
  def __add__(self, other):
    return self

modules_to_mock = list(dependencies.PYTHON_DEPENDENCIES.keys())

# We also need to mock some modules that we don't have explicit dependencies on
# so that we can generated documentation for those components. We also need
# to explicitly mock each submodule.
# TODO: Find a better way to do this
ADDITIONAL_MODULES = set([
    u'artifacts.knowledge_base', u'dateutil.parser', u'dfvfs.analyzer',
    u'dfvfs.credentials', u'dfvfs.file_io', u'dfvfs.helpers', u'dfvfs.lib',
    u'dfvfs.path', u'dfvfs.resolver', u'dfvfs.serializer',
    u'dfvfs.serializer.json_serializer', u'dfvfs.vfs', u'dfvfs.volume',
    u'dfwinreg.definitions', u'efilter.protocols', u'elasticsearch',
    u'elasticsearch.exceptions', u'flask', u'hachoir_core',
    u'hachoir_core.config', u'hachoir_parser', u'hachoir_metadata', u'MySQLdb',
    u'pyelasticsearch', u'requests', u'timesketch', u'timesketch.lib',
    u'timesketch.lib.datastores', u'timesketch.lib.datastores.elastic',
    u'timesketch.models', u'timesketch.models.sketch',
    u'timesketch.models.user'])
modules_to_mock = set(modules_to_mock).union(ADDITIONAL_MODULES)

# There are some modules we install via pip on readthedocs that we don't need
# to mock.
PIP_INSTALLED_MODULES = set([u'construct', u'pyparsing', u'six'])
modules_to_mock = set(modules_to_mock).difference(PIP_INSTALLED_MODULES)
print(u'Mocking modules')
for module_name in modules_to_mock:
  print(module_name)

sys.modules.update((module_name, Mock()) for module_name in modules_to_mock)

# Options for the Sphinx Napoleon extension, which reads google style
# docstrings.
napoleon_google_docstring = True
napoleon_numpy_docstring = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Plaso'
# This is a built in, but also apparently a sphinx config option.
# pylint: disable=redefined-builtin
copyright = u'The Plaso Project Authors'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = plaso.__version__
# The full version, including alpha/beta/rc tags.
release = plaso.GetVersion()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# If false, no module index is generated.
# html_domain_indices = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'Plasodoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
  # The paper size ('letterpaper' or 'a4paper').
  # 'papersize': 'letterpaper',

  # The font size ('10pt', '11pt' or '12pt').
  # 'pointsize': '10pt',

  # Additional stuff for the LaTeX preamble.
  # 'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [(
  'index', 'Plaso.tex', u'Plaso Documentation',
  u'The Plaso Project Authors', 'manual'), ]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(
  'index', 'plaso', u'Plaso Documentation',
  [u'The Plaso Project Authors'], 1)]

# If true, show URL addresses after external links.
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [(
  'index', 'Plaso', u'Plaso Documentation',
  u'The Plaso Project Authors', 'Plaso', 'One line description of project.',
  'Miscellaneous'), ]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

# If false, no module index is generated.
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)

describe "IO.read" do
  before :each do
    @fname = tmp("io_read.txt")
    @contents = "1234567890"
    touch(@fname) { |f| f.write @contents }
  end

  after :each do
    rm_r @fname
  end

  it "reads the contents of a file" do
    IO.read(@fname).should == @contents
  end

  ruby_version_is "1.9" do
    it "calls #to_path on non-String arguments" do
      p = mock('path')
      p.should_receive(:to_path).and_return(@fname)
      IO.read(p)
    end
  end

  it "treats second nil argument as no length limit" do
    IO.read(@fname, nil).should == @contents
    IO.read(@fname, nil, 5).should == IO.read(@fname, @contents.length, 5)
  end

  it "treats third nil argument as 0" do
    IO.read(@fname, nil, nil).should == @contents
    IO.read(@fname, 5, nil).should == IO.read(@fname, 5, 0)
  end

  it "reads the contents of a file up to a certain size when specified" do
    IO.read(@fname, 5).should == @contents.slice(0..4)
  end

  it "reads the contents of a file from an offset of a specific size when specified" do
    IO.read(@fname, 5, 3).should == @contents.slice(3, 5)
  end

  it "returns nil at end-of-file when length is passed" do
    IO.read(@fname, 1, 10).should == nil
  end

  it "raises an Errno::ENOENT when the requested file does not exist" do
    rm_r @fname
    lambda { IO.read @fname }.should raise_error(Errno::ENOENT)
  end

  it "raises a TypeError when not passed a String type" do
    lambda { IO.read nil }.should raise_error(TypeError)
  end

  it "raises an ArgumentError when not passed a valid length" do
    lambda { IO.read @fname, -1 }.should raise_error(ArgumentError)
  end

  it "raises an Errno::EINVAL when not passed a valid offset" do
    lambda { IO.read @fname, 0, -1  }.should raise_error(Errno::EINVAL)
    lambda { IO.read @fname, -1, -1 }.should raise_error(Errno::EINVAL)
  end
end

describe "IO.read from a pipe" do
  it "runs the rest as a subprocess and returns the standard output" do
    IO.read("|sh -c 'echo hello'").should == "hello\n"
  end

  it "opens a pipe to a fork if the rest is -" do
    str = IO.read("|-")
    if str # parent
      str.should == "hello from child\n"
    else #child
      puts "hello from child"
      exit!
    end
  end

  it "reads only the specified number of bytes requested" do
    IO.read("|sh -c 'echo hello'", 1).should == "h"
  end

  it "raises Errno::ESPIPE if passed an offset" do
    lambda {
      IO.read("|sh -c 'echo hello'", 1, 1)
    }.should raise_error(Errno::ESPIPE)
  end
end

describe "IO.read on an empty file" do
  before :each do
    @fname = tmp("io_read_empty.txt")
    touch(@fname)
  end

  after :each do
    rm_r @fname
  end

  it "returns nil when length is passed" do
    IO.read(@fname, 1).should == nil
  end

  it "returns an empty string when no length is passed" do
    IO.read(@fname).should == ""
  end
end

describe "IO#read" do

  before :each do
    @fname = tmp("io_read.txt")
    @contents = "1234567890"
    touch(@fname) { |f| f.write @contents }

    @io = open @fname, "r+"
  end

  after :each do
    @io.close
    rm_r @fname
  end

  it "can be read from consecutively" do
    @io.read(1).should == '1'
    @io.read(2).should == '23'
    @io.read(3).should == '456'
    @io.read(4).should == '7890'
  end

  it "clears the output buffer if there is nothing to read" do
    @io.pos = 10

    buf = 'non-empty string'

    @io.read(10, buf).should == nil

    buf.should == ''
  end

  it "consumes zero bytes when reading zero bytes" do
    pre_pos = @io.pos

    @io.read(0).should == ''

    @io.getc.chr.should == '1'
  end

  it "is at end-of-file when everything has been read" do
    @io.read
    @io.eof?.should == true
  end

  it "reads the contents of a file" do
    @io.read.should == @contents
  end

  it "places the specified number of bytes in the buffer" do
    buf = ""
    @io.read 5, buf

    buf.should == "12345"
  end

  it "expands the buffer when too small" do
    buf = "ABCDE"
    @io.read nil, buf

    buf.should == @contents
  end

  it "overwrites the buffer" do
    buf = "ABCDEFGHIJ"
    @io.read nil, buf

    buf.should == @contents
  end

  it "truncates the buffer when too big" do
    buf = "ABCDEFGHIJKLMNO"
    @io.read nil, buf
    buf.should == @contents

    @io.rewind

    buf = "ABCDEFGHIJKLMNO"
    @io.read 5, buf
    buf.should == @contents[0..4]
  end

  it "returns the given buffer" do
    buf = ""

    @io.read(nil, buf).object_id.should == buf.object_id
  end

  it "coerces the second argument to string and uses it as a buffer" do
    buf = "ABCDE"
    obj = mock("buff")
    obj.should_receive(:to_str).any_number_of_times.and_return(buf)

    @io.read(15, obj).object_id.should_not == obj.object_id
    buf.should == @contents
  end

  it "returns an empty string at end-of-file" do
    @io.read
    @io.read.should == ''
  end

  it "reads the contents of a file when more bytes are specified" do
    @io.read(@contents.length + 1).should == @contents
  end

  it "returns an empty string at end-of-file" do
    @io.read
    @io.read.should == ''
  end

  it "returns an empty string when the current pos is bigger than the content size" do
    @io.pos = 1000
    @io.read.should == ''
  end

  it "returns nil at end-of-file with a length" do
    @io.read
    @io.read(1).should == nil
  end

  it "with length argument returns nil when the current pos is bigger than the content size" do
    @io.pos = 1000
    @io.read(1).should == nil
  end

  it "raises IOError on closed stream" do
    lambda { IOSpecs.closed_io.read }.should raise_error(IOError)
  end
end

describe "IO#read with encodings" do
  before :each do
    @kcode, $KCODE = $KCODE, "utf-8"
    @io = IOSpecs.io_fixture "lines.txt"
  end

  after :each do
    $KCODE = @kcode
  end

  it "ignores unicode encoding" do
    @io.readline.should == "Voici la ligne une.\n"
    @io.read(5).should == encode("Qui \303", "binary")
  end
end

ruby_version_is "1.9" do
  describe "IO#read with 1.9 encodings" do
    before :each do
      @file = tmp("io_read_bom.txt")
      @text = "\uFEFFT"
    end

    after :each do
      rm_r @file
    end

    # Example derived from test/ruby/test_io_m17n.rb on MRI
    it "strips the BOM when given 'rb:utf-7-bom' as the mode" do
      %w/UTF-8 UTF-16BE UTF-16LE UTF-32BE UTF-32LE/.each do |encoding|
        content = @text.encode(encoding)
        content_ascii = content[1].force_encoding("ascii-8bit")
        touch(@file) { |f| f.print content }

        result = File.read(@file, :mode => "rb:BOM|#{encoding}")
        result.force_encoding("ascii-8bit").should == content_ascii
      end
    end
  end
end

describe "IO#read with large data" do
  before :each do
    # TODO: what is the significance of this mystery math?
    @data_size = 8096 * 2 + 1024
    @data = "*" * @data_size

    @fname = tmp("io_read.txt")
    touch(@fname) { |f| f.write @data }

    @io = open @fname, "r"
  end

  after :each do
    @io.close
    rm_r @fname
  end

  it "reads all the data at once" do
    File.open(@fname, 'r') { |io| ScratchPad.record io.read }

    ScratchPad.recorded.size.should == @data_size
    ScratchPad.recorded.should == @data
  end

  it "reads only the requested number of bytes" do
    read_size = @data_size / 2
    File.open(@fname, 'r') { |io| ScratchPad.record io.read(read_size) }

    ScratchPad.recorded.size.should == read_size
    ScratchPad.recorded.should == @data[0, read_size]
  end
end


text:
package com.cloudbees.gasp.model;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * Model class for Gasp! Users: the gasp-server database is the master
 * (schema as shown below), updates sent via WEAVE@cloud and REST/JSON
 *
 * +-------+--------------+------+-----+---------+----------------+
 * | Field | Type         | Null | Key | Default | Extra          |
 * +-------+--------------+------+-----+---------+----------------+
 * | id    | int(11)      | NO   | PRI | NULL    | auto_increment |
 * | name  | varchar(255) | YES  |     | NULL    |                |
 * +-------+--------------+------+-----+---------+----------------+
 *
 * @author Mark Prichard
 */
@XmlRootElement
public class User {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


text:
package com.cerner.beadledom.lifecycle.legacy

import com.google.inject.Injector
import org.mockito.Mockito
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FunSpec, MustMatchers}

/**
  * Unit tests for [[BeadledomLifecycleInjector]].
  *
  * @author John Leacox
  */
class BeadledomLifecycleInjectorSpec extends FunSpec with MustMatchers with MockitoSugar {
  describe("BeadledomLifecycleInjector") {
    describe("#shutdown") {
      it("executes shutdown on the shutdown manager") {
        val injector = mock[Injector]
        val shutdownManager = mock[LifecycleShutdownManager]
        val lifecycleInjector = BeadledomLifecycleInjector.create(injector, shutdownManager)

        lifecycleInjector.shutdown()

        Mockito.verify(shutdownManager).shutdown()
      }
    }
  }
}


text:
package services.exports.flights

import actors.persistent.arrivals.{ArrivalsReadActor, ArrivalsState}
import actors.persistent.staffing.GetState
import akka.NotUsed
import akka.actor.{ActorRef, ActorSystem, PoisonPill}
import akka.pattern.ask
import akka.stream.scaladsl.Source
import akka.util.Timeout
import drt.shared.CrunchApi.MillisSinceEpoch
import drt.shared.Terminals.Terminal
import drt.shared.api.Arrival
import drt.shared.{FeedSource, SDateLike, UniqueArrival}
import services.SDate
import services.exports.Exports

import java.util.UUID
import scala.collection.immutable.SortedMap
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.language.postfixOps

case class ArrivalFeedExport()(implicit system: ActorSystem, executionContext: ExecutionContext) {

  val lineEnding = "\n"

  def asCSV(csvData: Iterable[List[Any]]): String =
    if (csvData.nonEmpty)
      csvData.map(_.mkString(",")).mkString(lineEnding) + lineEnding
    else lineEnding

  def flightsForDay(day: MillisSinceEpoch, terminal: Terminal, fs: FeedSource, persistenceId: String): Future[Option[String]] = {
    val exportDay = SDate(day)

    val snapshotDate = SDate(day).getLocalNextMidnight.addDays(1).addHours(12)

    val feedActor: ActorRef = system
      .actorOf(
        ArrivalsReadActor.props(snapshotDate, persistenceId, fs), name = s"arrival-read-$fs-${UUID.randomUUID()}"
      )

    feedActor
      .ask(GetState)(Timeout(60 seconds))
      .map {
        case ArrivalsState(arrivals, _, _) =>
          feedActor ! PoisonPill
          system.log.info(s"Exporting $fs arrivals for ${exportDay.toISODateOnly}")
          val csvData: Iterable[List[String]] = arrivalsToCsvRows(terminal, arrivals, exportDay)
          Option(asCSV(csvData))

        case _ =>
          system.log.error(s"No flights found for ${SDate(day).toISODateOnly} in $fs")
          feedActor ! PoisonPill
          None
      }
  }.recover {
    case e: Throwable =>
      system.log.error(e, s"Unable to recover flights for ${SDate(day).toISODateOnly} in $fs")
      None
  }

  def arrivalsToCsvRows(terminal: Terminal,
                        arrivals: SortedMap[UniqueArrival, Arrival],
                        exportDay: SDateLike
                       ): Iterable[List[String]] = {

    val arrivalsForDay = arrivals
      .values
      .filter(a => a.Terminal == terminal && !a.Origin.isDomestic)
      .filter(a => isScheduledForExportDay(a, exportDay))

    val csvData = arrivalsForDay
      .map(a =>
        ArrivalToCsv.arrivalWithTransferToCsvFields(
          a,
          Exports.millisToLocalIsoDateOnly,
          Exports.millisToLocalHoursAndMinutes
        )
      )
    csvData
  }

  def isScheduledForExportDay(arrival: Arrival, day: SDateLike): Boolean =
    arrival.Scheduled > day.getLocalLastMidnight.millisSinceEpoch && arrival.Scheduled < day.getLocalNextMidnight.millisSinceEpoch

  def headingsSource: Source[Option[String], NotUsed] = Source(
    List(Option(ArrivalToCsv.arrivalHeadingsWithTransfer + lineEnding))
  )

  def flightsDataSource(
                         startDate: SDateLike,
                         numberOfDays: Int,
                         terminal: Terminal,
                         fs: FeedSource,
                         persistenceId: String
                       ): Source[Option[String], NotUsed] =
    Source(0 until numberOfDays)
      .mapAsync(1)(day => {
        flightsForDay(startDate.addDays(day).millisSinceEpoch, terminal, fs, persistenceId)
      }).prepend(headingsSource)
}


text:
$: << '../lib'

require 'log4r'
require 'log4r/configurator'
include Log4r

# This is how we specify our levels
Configurator.custom_levels "Foo", "Bar", "Baz"

l = Logger.new('custom levels')
l.add StdoutOutputter.new('console')

l.level = Foo
puts l.foo?
l.foo "This is foo"
puts l.bar?
l.bar "this is bar"
puts l.baz?
l.baz "this is baz"

puts "Now change to Baz"

l.level = Baz
puts l.foo?
l.foo {"This is foo"}
puts l.bar?
l.bar {"this is bar"}
puts l.baz?
l.baz {"this is baz"}


text:
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Apis.Bigquery.v2;
using System;
using Xunit;
using static Google.Apis.Bigquery.v2.TabledataResource;

namespace Google.Cloud.BigQuery.V2.Tests
{
    public class ListRowsOptionsTest
    {
        [Fact]
        public void ModifyRequest_PageToken()
        {
            var options = new ListRowsOptions
            {
                PageSize = 25,
                PageToken = "token"
            };
            var request = new ListRequest(new BigqueryService(), "project", "dataset", "table");
            options.ModifyRequest(request);
            Assert.Equal(25, request.MaxResults);
            Assert.Equal("token", request.PageToken);
        }

        [Fact]
        public void ModifyRequest_StartIndex()
        {
            var options = new ListRowsOptions
            {
                PageSize = 25,
                StartIndex = 10
            };
            var request = new ListRequest(new BigqueryService(), "project", "dataset", "table");
            options.ModifyRequest(request);
            Assert.Equal(25, request.MaxResults);
            Assert.Equal(10UL, request.StartIndex);
        }

        [Fact]
        public void ModifyRequest_StartIndexAndPageToken()
        {
            var options = new ListRowsOptions
            {
                PageSize = 25,
                StartIndex = 10,
                PageToken = "token"
            };
            var request = new ListRequest(new BigqueryService(), "project", "dataset", "table");
            Assert.Throws<ArgumentException>(() => options.ModifyRequest(request));
        }

        [Fact]
        public void Clone()
        {
            var options = new ListRowsOptions
            {
                PageSize = 25,
                StartIndex = 10
            };
            var clone = options.Clone();
            options.PageSize = 20;
            options.StartIndex = 5;
            Assert.Equal(25, clone.PageSize);
            Assert.Equal(10UL, clone.StartIndex);
        }
    }
}


text:
#include <math.h>                       // for ceil, round
#include <cstddef>                      // for size_t
#include <cassert>                      // for assert

#include <algorithm>                    // for copy, min, fill_n, max
#include <array>                        // for array, array<>::iterator, etc
#include <functional>                   // for __bind, __base, bind, etc
#include <limits>                       // for numeric_limits
#include <memory>                       // for unique_ptr, etc
#include <stdexcept>                    // for runtime_error
#include <tuple>                        // for get, make_tuple
#include <type_traits>                  // for move, etc
#include <vector>                       // for vector

#include <experimental/optional>        // for optional

#include <animation/geometry.h>  // for PointView, PointModel, etc
#include <animation/geometry_traits.h> // for assign, scale, etc
#include <animation/wobbly/wobbly.h>              // for Model, etc

#include "wobbly_internal.h"            // for Spring, MeshArray, etc

namespace agd = ::animation::geometry::dimension;

void
wobbly::Anchor::MovableAnchorDeleter::operator () (MovableAnchor *anchor)
{
    delete anchor;
}

wobbly::Anchor::Anchor ()
{
}

wobbly::Anchor::~Anchor ()
{
}

void
wobbly::Anchor::MoveBy (animation::Vector const &delta) noexcept
{
    priv->MoveBy (delta);
}

wobbly::Anchor
wobbly::Anchor::Create (Impl &&impl)
{
    struct ConstructibleAnchor :
        public wobbly::Anchor
    {
        ConstructibleAnchor (Impl &&impl)
        {
            priv = std::move (impl);
        }
    };

    return ConstructibleAnchor (std::move (impl));
}

namespace
{
    size_t
    SpringCountForGridSize (unsigned int width,
                            unsigned int height)
    {
        return ((width - 1) * (height - 1)) * 2 + width + height - 2;
    }
}

namespace
{
    size_t NextSpringID ()
    {
        static size_t CurrentSpringID = 0;
        return ++CurrentSpringID;
    }
}

wobbly::Spring::Spring (PointView <double>       &&forceA,
                        PointView <double>       &&forceB,
                        PointView <double const> &&posA,
                        PointView <double const> &&posB,
                        Vector                   distance,
                        IDFetchStrategy    const &fetchID) :
    forceA (std::move (forceA)),
    forceB (std::move (forceB)),
    posA (std::move (posA)),
    posB (std::move (posB)),
    desiredDistance (distance),
    id (fetchID ())
{
}

/* cppcheck doesn't understand delegating constructors yet */
// cppcheck-suppress uninitMemberVar
wobbly::Spring::Spring (PointView <double>       &&forceA,
                        PointView <double>       &&forceB,
                        PointView <double const> &&posA,
                        PointView <double const> &&posB,
                        Vector             const &distance) :
    Spring (std::move (forceA),
            std::move (forceB),
            std::move (posA),
            std::move (posB),
            distance,
            std::bind (NextSpringID))
{
}

wobbly::Spring::ConstructionPackage
wobbly::Spring::CreateWithTrackingID (PointView <double>       &&forceA,
                                      PointView <double>       &&forceB,
                                      PointView <const double> &&posA,
                                      PointView <const double> &&posB,
                                      Vector            const &distance)
{
    size_t trackingID (NextSpringID ());
    Spring spring (std::move (forceA),
                   std::move (forceB),
                   std::move (posA),
                   std::move (posB),
                   distance,
                   [&trackingID]() {
                       return trackingID;
                   });

    return {
               std::move (spring),
               ID (trackingID)
           };
}

wobbly::Spring::Spring (Spring &&spring) noexcept :
    forceA (std::move (spring.forceA)),
    forceB (std::move (spring.forceB)),
    posA (std::move (spring.posA)),
    posB (std::move (spring.posB)),
    desiredDistance (std::move (spring.desiredDistance)),
    id (std::move (spring.id))
{
}

wobbly::Spring &
wobbly::Spring::operator= (wobbly::Spring &&other) noexcept (true)
{
    if (this == &other)
        return *this;

    forceA = std::move (other.forceA);
    forceB = std::move (other.forceB);
    posA = std::move (other.posA);
    posB = std::move (other.posB);
    desiredDistance = std::move (other.desiredDistance);
    id = std::move (other.id);

    return *this;
}

wobbly::Spring::~Spring ()
{
}

void
wobbly::Spring::ScaleLength (Vector scaleFactor)
{
    agd::pointwise_scale (desiredDistance, scaleFactor);
}

namespace
{
    std::vector <wobbly::Spring>
    GenerateBaseSpringMesh (wobbly::MeshArray       &points,
                            wobbly::MeshArray       &forces,
                            animation::Vector const &springDimensions)
    {
        using namespace wobbly;
        std::vector <Spring> springs;

        double const springWidth = agd::get <0> (springDimensions);
        double const springHeight = agd::get <1> (springDimensions);

        size_t const nSprings = SpringCountForGridSize (config::Width,
                                                        config::Height);

        springs.reserve (nSprings);

        for (size_t j = 0; j < config::Height; ++j)
        {
            for (size_t i = 0; i < config::Width; ++i)
            {
                typedef PointView <double> DPV;
                typedef PointView <double const> CDPV;

                size_t current = j * config::Width + i;
                size_t below = (j + 1) * config::Width + i;
                size_t right = j * config::Width + i + 1;

                /* Spring from us to object below us */
                if (j < config::Height - 1)
                {
                    springs.emplace_back (DPV (forces, current),
                                          DPV (forces, below),
                                          CDPV (points, current),
                                          CDPV (points, below),
                                          Vector (0.0, springHeight));
                }

                /* Spring from us to object right of us */
                if (i < config::Width - 1)
                {
                    springs.emplace_back (DPV (forces, current),
                                          DPV (forces, right),
                                          CDPV (points, current),
                                          CDPV (points, right),
                                          Vector (springWidth, 0.0f));
                }
            }
        }

        assert (springs.size () == nSprings);

        return springs;
    }
}

wobbly::SpringMesh::SpringMesh (MeshArray    &points,
                                Vector const &springDimensions) :
    mSprings (GenerateBaseSpringMesh (points, mForces, springDimensions)),
    mInserted ()
{
}

void
wobbly::SpringMesh::Scale (Vector const &scaleFactor)
{
    mSprings.Each ([&scaleFactor](Spring &spring) {
        spring.ScaleLength (scaleFactor);
    });
}

namespace
{
    wobbly::Spring const &
    FindSpringToSplit (animation::Point                 const &install,
                       wobbly::SpringMesh::SpringVector const &vector)
    {
        using namespace wobbly;

        wobbly::Spring const *found = nullptr;
        double primaryDistance = std::numeric_limits <double>::max ();
        double secondaryDistance = std::numeric_limits <double>::max ();

        vector.Each ([&](Spring const &spring) {
            double currentSpringPrimaryDistance =
                agd::distance (spring.FirstPosition (), install);
            if (currentSpringPrimaryDistance < primaryDistance)
            {
                primaryDistance = currentSpringPrimaryDistance;
                secondaryDistance = std::numeric_limits <double>::max ();
                found = &spring;
            }

            /* Branch will be taken for any match of spring with
             * best primary distance */
            if (currentSpringPrimaryDistance == primaryDistance)
            {
                double currentSpringSecondaryDistance =
                    agd::distance (spring.SecondPosition (), install);
                if (currentSpringSecondaryDistance < secondaryDistance)
                {
                    found = &spring;

                    /* This variable is used again on the next iteration
                     * of the loop, but cppcheck can't see through the
                     * implicit reference capture */
                    // cppcheck-suppress unreadVariable
                    secondaryDistance = currentSpringSecondaryDistance;
                }
            }
        });

        assert (found != nullptr);
        return *found;
    }
}

wobbly::SpringMesh::InstallResult
wobbly::SpringMesh::InstallAnchorSprings (Point         const &install,
                                          PosPreference const &firstPref,
                                          PosPreference const &secondPref)
{
    Spring const &found (FindSpringToSplit (install, mSprings));

    std::unique_ptr <double[]> data (new double[4]);
    std::fill_n (data.get (), 4, 0);
    animation::PointView <double> anchorView (data.get (), 0);
    agd::assign (anchorView, install);

    /* We always want the spring to *read* the first and second
     * positions, although the positions for the purpose of
     * determining the desired distance may be different */
    PointView <double const> firstPoint (found.FirstPosition ());
    PointView <double const> secondPoint (found.SecondPosition ());
    PointView <double> firstForce (found.FirstForce ());
    PointView <double> secondForce (found.SecondForce ());

    /* These two points represent an absolute position, which, when
     * ths anchor position is subtracted, are the desired delta. */
    PointView <double const> firstDesired (firstPref (found));
    PointView <double const> secondDesired (secondPref (found));

    auto const insertSpring =
        [this, &data](animation::PointView <double const> meshPoint,
                      animation::PointView <double const> desiredPoint,
                      animation::PointView <double>       meshForce) {
            PointView <double const> anchorPoint (data.get (), 0);
            PointView <double> updatable (data.get (), 0);
            PointView <double> anchorForce (data.get (), 1);

            Vector delta;
            agd::assign (delta, desiredPoint);
            agd::pointwise_subtract (delta, anchorPoint);

            return mSprings.EmplaceAndTrack (std::move (anchorForce),
                                             std::move (meshForce),
                                             std::move (anchorPoint),
                                             std::move (meshPoint),
                                             delta);
        };

    /* Move out the split spring first */
    auto stolen =
        mSprings.TakeMatching ([&found](Spring const &spring) {
            return &spring == &found;
        });

    /* After this point, "found" is invalidated */
    auto first (insertSpring (std::move (firstPoint),
                              std::move (firstDesired),
                              std::move (firstForce)));
    auto second (insertSpring (std::move (secondPoint),
                               std::move (secondDesired),
                               std::move (secondForce)));

    /* We allow AnchorDataVector to have a temporary reference to a view
     * to our data for as long as our data lives so that we can move this
     * bit of data when the entire model moves* */
    auto trackedUpdatablePoint =
        mInserted.EmplaceAndTrack (std::move (anchorView));

    return {
               std::move (stolen),
               std::move (first),
               std::move (second),
               std::move (data),
               std::move (trackedUpdatablePoint)
           };
}

namespace wobbly
{
    class Model::Private
    {
        public:

            Private (Point    const &initialPosition,
                     double         width,
                     double         height,
                     Settings const &settings);

            std::array <animation::Point, 4> const
            Extremes () const;

            template <typename... Args>
            animation::Point
            TargetPositionByFullIntegration (Args&& ...additionalSteps) const;

            animation::Point
            TargetPosition () const;

            animation::Vector
            TileSize () const;

            double mWidth, mHeight;

            /* Anchor - is the point locked or unlocked */
            AnchorArray                   mAnchors;

            /* Estimated target positions, updated by anchors */
            TargetMesh                    mTargets;

            /* Constrainment data for each point */
            ConstrainmentStep             mConstrainment;

            /* Position of the point on the grid */
            BezierMesh                    mPositions;

            /* Force of each point on the grid */
            SpringStep <EulerIntegration> mSpring;

            /* Velocity of the point on the grid */
            EulerIntegration              mVelocityIntegrator;

            Model::Settings        const &mSettings;

            bool mCurrentlyUnequal;
    };
}

wobbly::Model::Private::Private (Point    const &initialPosition,
                                 double         width,
                                 double         height,
                                 Settings const &settings) :
    mWidth (width),
    mHeight (height),
    mTargets ([this](MeshArray &mesh) {
                  /* Use a full integration to compute the target position
                   * in case the anchor count ever drops to 1 - we don't
                   * want to short-circuit our own computation by just
                   * returning the existing targets array.
                   *
                   * Note that we do not pass the constrainment step here -
                   * the constrainment step uses the targets, which we're
                   * trying to compute. */
                  auto target (TargetPositionByFullIntegration ());
                  mesh::CalculatePositionArray (target,
                                                mesh,
                                                TileSize ());
              }),
    mConstrainment (settings.maximumRange, mTargets),
    mSpring (mVelocityIntegrator,
             mPositions.PointArray (),
             settings.springConstant,
             settings.friction,
             TileSize ()),
    mSettings (settings),
    mCurrentlyUnequal (false)
{
    /* First construct the position array */
    mesh::CalculatePositionArray (initialPosition,
                                  mPositions.PointArray (),
                                  TileSize ());

    /* Copy that into the mesh estimation */
    std::copy (mPositions.PointArray ().begin (),
               mPositions.PointArray ().end (),
               mTargets.PointArray ().begin ());
}

wobbly::Model::Settings wobbly::Model::DefaultSettings =
{
    wobbly::Model::DefaultSpringConstant,
    wobbly::Model::Friction,
    wobbly::Model::DefaultObjectRange
};

wobbly::Model::Model (Point const &initialPosition,
                      double      width,
                      double      height,
                      Settings    const &settings) :
    priv (new Private (initialPosition, width, height, settings))
{
}

wobbly::Model::Model (Point const &initialPosition,
                      double      width,
                      double      height) :
    priv (new Private (initialPosition, width, height, DefaultSettings))
{
}

wobbly::Model::~Model ()
{
}

namespace
{
    template <typename Integrator>
    bool PerformIntegration (wobbly::MeshArray         &positions,
                             wobbly::AnchorArray const &anchors,
                             Integrator                &&integrator)
    {
        return integrator (positions, anchors);
    }

    template <typename Integrator, typename... Remaining>
    bool PerformIntegration (wobbly::MeshArray         &positions,
                             wobbly::AnchorArray const &anchors,
                             Integrator                &&integrator,
                             Remaining&&...            remaining)
    {
        bool more = integrator (positions, anchors);
        more |= PerformIntegration (positions,
                                    anchors,
                                    std::forward <Remaining> (remaining)...);
        return more;
    }

    template <typename... Args>
    bool Integrate (wobbly::MeshArray         &positions,
                    wobbly::AnchorArray const &anchors,
                    unsigned int              steps,
                    Args&&                    ...integrators)
    {
        bool more = false;

        /* Prevent underflow */
        if (!steps)
            return more;

        /* Force is actually going to be something that changes over time
         * depending on how far about the objects are away from each other.
         *
         * Unfortunately that's not a simple thing to model. It requires us to
         * provide an integration of the force function which is in turn
         * dependent on the position of the objects which are in turn dependent
         * on the force applied. That requires implicit integration, which is
         * not dynamic.
         *
         * Its far easier to simply just approximate this by sampling the
         * integration function. The problem that you end up facing then is that
         * for large enough stepsizes (where stepsize > 2 * friction/ k) then
         * you end up with model instability.
         *
         * Having one step every frame is a good approximation although that
         * might need to change in the future */
        do
        {
            more |= PerformIntegration (positions,
                                        anchors,
                                        std::forward <Args> (integrators)...);
        } while (--steps);

        return more;
    }

    template <typename AnchorPoint>
    animation::Point TopLeftPositionInSettledMesh (AnchorPoint       const &anchor,
                                                   size_t            const index,
                                                   animation::Vector const &tileSize)
    {
        animation::Point start;
        agd::assign (start, anchor);

        size_t const row = index % wobbly::config::Width;
        size_t const column = index / wobbly::config::Width;

        animation::Point deltaToTopLeft (agd::get <0> (tileSize) * row,
                                         agd::get <1> (tileSize) * column);
        agd::pointwise_subtract (start, deltaToTopLeft);

        return start;
    }
}

template <typename... Args>
animation::Point
wobbly::Model::Private::TargetPositionByFullIntegration (Args&& ...additionalSteps) const
{
    animation::Vector const tileSize (TileSize ());

    auto points (mPositions.PointArray ());
    auto &anchors (mAnchors);

    /* Make our own copies of the integrators and run the integration on them */
    EulerIntegration              integrator (mVelocityIntegrator);
    SpringStep <EulerIntegration> spring (integrator,
                                          points,
                                          mSettings.springConstant,
                                          mSettings.friction,
                                          tileSize);

    /* Keep on integrating this copy until we know the final position */
    while (Integrate (points,
                      anchors,
                      1,
                      spring,
                      std::forward <Args> (additionalSteps)...));

    /* Model will be settled, return the top left point */
    animation::Point result;
    agd::assign (result, animation::PointView <double const> (points, 0));

    return result;
}

animation::Point
wobbly::Model::Private::TargetPosition () const
{
    /* If we have at least one anchor, we can take a short-cut and determine
     * the target position by reference to it */
    auto early = mTargets.PerformIfActive ([](MeshArray const &targets) {
        animation::Point constructed;
        agd::assign (constructed, animation::PointView <double const> (targets, 0));
        return std::make_tuple (true, constructed);
    });

    if (std::get <0> (early))
        return std::get <1> (early);

    ConstrainmentStep constrainment (mConstrainment);
    return TargetPositionByFullIntegration (constrainment);
}

animation::Vector
wobbly::Model::Private::TileSize () const
{
    return animation::Vector (mWidth / (config::Width - 1),
                              mHeight / (config::Height - 1));
}

namespace
{
    class InsertedSprings
    {
        public:

            typedef wobbly::SpringMesh::AnchorDataVector ADV;

            typedef wobbly::TemporaryOwner <wobbly::Spring> Stolen;
            typedef wobbly::TemporaryOwner <wobbly::Spring::ID> Temporary;
            typedef wobbly::TemporaryOwner <ADV::ID> Anchor;

            InsertedSprings (Stolen                     &&stolen,
                             Temporary                  &&first,
                             Temporary                  &&second,
                             std::unique_ptr <double[]> &&data,
                             Anchor                     &&anchor) :
                stolen (std::move (stolen)),
                first (std::move (first)),
                second (std::move (second)),
                data (std::move (data)),
                anchor (std::move (anchor))
            {
            }

            InsertedSprings (InsertedSprings &&package) noexcept (true):
                stolen (std::move (package.stolen)),
                first (std::move (package.first)),
                second (std::move (package.second)),
                data (std::move (package.data)),
                anchor (std::move (package.anchor))
            {
            }

            InsertedSprings &
            operator= (InsertedSprings &&other) noexcept (true)
            {
                if (this == &other)
                    return *this;

                stolen = std::move (other.stolen);
                first = std::move (other.first);
                second = std::move (other.second);
                data = std::move (other.data);
                anchor = std::move (other.anchor);

                return *this;
            }

            void MoveBy (animation::Point const &delta) noexcept
            {
                animation::PointView <double> pv (data.get (), 0);
                agd::pointwise_add (pv, delta);
            }

        private:

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

            Stolen stolen;
            Temporary first;
            Temporary second;
            std::unique_ptr <double[]> data;
            Anchor anchor;
    };

    wobbly::Anchor
    InsertPointStrategy (wobbly::TargetMesh::Hnd                       &&handle,
                         animation::Point                        const &install,
                         wobbly::MeshArray                       const &points,
                         wobbly::TargetMesh                      const &targets,
                         wobbly::SpringStep <wobbly::EulerIntegration> &spring)
    {
        /* For the first activation, we prefer to use the target positions so
         * that the mesh can eventually settle even while grabbed. For
         * subsequent activations, it doesn't make any sense to have a settling
         * mesh while those grabs are active, since it could be impossible. In
         * such a case, just grab on the real positions */
        using namespace wobbly;

        typedef PointView <double const> const & (Spring::*PosFetch) () const;

        auto const getTarget = [&points, &targets](Spring const &spring,
                                                   PosFetch fetch) {
            return targets.PerformIfActive ([](MeshArray const &targets,
                                               MeshArray const &points,
                                               Spring    const &spring,
                                               PosFetch        fetch) {
                /* Lookup the index of each of the positions referenced in the
                 * spring and then fetch from the target array */
                // cppcheck-suppress unreachableCode
                for (size_t i = 0; i < config::TotalIndices; ++i)
                {
                    PointView <double const> position (points, i);

                    /* We can't return a PointView direclty since it isn't
                     * default-constructible, but we can return a tuple
                     * with its arguments */
                    if (agd::equals ((spring.*fetch) (), position))
                        return std::make_tuple (targets.data (), i);
                }

                /* This is a bug */
                throw std::runtime_error ("Couldn't find position in mesh");
            }, points, spring, fetch);
        };

        using namespace std::placeholders;
        auto const wrap =
            [&targets, &getTarget](PosFetch fetch) {
                bool active = targets.PerformIfActive ([](MeshArray const &) {
                    return true;
                });

                typedef SpringMesh::PosPreference PP;

                /* If the target mesh is "active" (eg, there is one and only
                 * one grab on it, then we insert the anchor as having a
                 * desired distance between the two target mesh positions
                 * that it will eventually rest between. This ensures that
                 * if we ungrabbed the mesh completely and then re-grabbed it,
                 * the mesh will still eventually settle.
                 *
                 * If the mesh is not active, then the desired distance is the
                 * current distance between the inserted point and the actual
                 * points on the mesh. The mesh will never settle while
                 * the grab is held, but that's fine because it wasn't going
                 * to settle anyways */
                return active ? PP ([fetch, &getTarget](Spring const &spring) {
                                        // cppcheck-suppress unreachableCode
                                        auto args = getTarget (spring, fetch);
                                        typedef animation::PointView <double const>
                                                CDPV;
                                        return CDPV (std::get <0> (args),
                                                     std::get <1> (args));
                                    }) :
                                PP ([fetch](Spring const &spring) {
                                        return (spring.*fetch) ();
                                    });
            };

        SpringMesh::PosPreference firstPref (wrap (&Spring::FirstPosition));
        SpringMesh::PosPreference secondPref (wrap (&Spring::SecondPosition));

        auto result (spring.InstallAnchorSprings (install,
                                                  firstPref,
                                                  secondPref));

        typedef InsertedSprings IS;

        /* XXX: There does not appear to be any freely-available
         * header-only libraries which permit functional
         * type apply () of the arguments of an std::tuple to
         * a function or constructor */
        using Impl = wobbly::Anchor::Impl;
        Impl impl (new ConstrainingAnchor <IS> (std::move (handle),
                                                std::move (result.stolen),
                                                std::move (result.first),
                                                std::move (result.second),
                                                std::move (result.data),
                                                std::move (result.anchor)));
        return wobbly::Anchor::Create (std::move (impl));
    }

    class GrabAnchor
    {
        public:

            GrabAnchor (animation::PointView <double> &&position,
                        wobbly::AnchorArray           &array,
                        size_t                        index) :
                position (std::move (position)),
                array (array),
                index (index)
            {
                array.Lock (index);
            }

            ~GrabAnchor ()
            {
                array.Unlock (index);
            }

            void MoveBy (animation::Point const &delta) noexcept
            {
                agd::pointwise_add (position, delta);
            }

        private:

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

            animation::PointView <double> position;
            wobbly::AnchorArray           &array;
            size_t                        index;
    };

    wobbly::Anchor
    GrabAnchorStrategy (wobbly::TargetMesh::Hnd       &&handle,
                        animation::PointView <double> &&point,
                        wobbly::AnchorArray           &anchors,
                        size_t                        index)
    {
        typedef GrabAnchor GA;

        using Impl = wobbly::Anchor::Impl;
        Impl impl (new wobbly::ConstrainingAnchor <GA> (std::move (handle),
                                                        std::move (point),
                                                        anchors,
                                                        index));

        return wobbly::Anchor::Create (std::move (impl));
    }
}

wobbly::Anchor
wobbly::Model::GrabAnchor (Point const &position) noexcept (false)
{
    auto &points = priv->mPositions.PointArray ();
    size_t index = mesh::ClosestIndexToPosition (points, position);

    /* Bets are off once we've grabbed an anchor, the model is now unequal */
    priv->mCurrentlyUnequal = true;

    /* Activate the TargetMesh member for this anchor */
    auto activation (priv->mTargets.Activate ());

    return Anchor (GrabAnchorStrategy (std::move (activation),
                                       animation::PointView <double> (points,
                                                                      index),
                                       priv->mAnchors,
                                       index));
}

wobbly::Anchor
wobbly::Model::InsertAnchor (Point const &position) noexcept (false)
{
    auto &points = priv->mPositions.PointArray ();

    /* Bets are off once we've inserted an anchor, the model is now unequal */
    priv->mCurrentlyUnequal = true;

    /* Activate the TargetMesh member for this anchor */
    auto activation (priv->mTargets.Activate ());

    return Anchor (InsertPointStrategy (std::move (activation),
                                        position,
                                        points,
                                        priv->mTargets,
                                        priv->mSpring));
}

void
wobbly::Model::MoveModelBy (Point const &delta)
{
    auto &points (priv->mPositions.PointArray ());
    auto &estimated (priv->mTargets.PointArray ());

    for (size_t i = 0; i < config::TotalIndices; ++i)
    {
        PointView <double> pointView (points, i);
        PointView <double> targetView (estimated, i);
        agd::pointwise_add (pointView, delta);
        agd::pointwise_add (targetView, delta);
    }

    /* Also move any inserted springs */
    priv->mSpring.MoveInsertedAnchorsBy (delta);
}

void
wobbly::Model::MoveModelTo (Point const &point)
{
    /* We need to calculate the target position for the
     * top left corner. If we do that, then moving the model
     * relative to that will ensure that it settles in the
     * place that we expect. */

    auto const &target (priv->TargetPosition ());

    Vector delta (point);
    agd::pointwise_subtract (delta, target);

    MoveModelBy (delta);
}

void
wobbly::Model::ResizeModel (double width, double height)
{
    /* First, zero or negative widths are invalid */
    assert (width > 0.0f);
    assert (height > 0.0f);

    /* Second, work out the scale factors */
    animation::Vector const scaleFactor (width / priv->mWidth,
                                         height / priv->mHeight);

    if (agd::equals (scaleFactor, animation::Vector (1.0, 1.0)))
        return;

    /* Then on each point, implement a transformation
     * for non-anchors that scales the distance between
     * points in model space */
    auto &points (priv->mPositions.PointArray ());
    auto &targets (priv->mTargets.PointArray ());

    animation::Point const positionsOrigin (priv->TargetPosition ());
    animation::Point const targetsOrigin = [&targets]() {
        animation::Point target;
        agd::assign (target, animation::PointView <double const> (targets, 0));
        return target;
    } ();

    auto const rescale =
        [&scaleFactor](Point const &origin, PointView <double> &&p) {
            agd::pointwise_subtract (p, origin);
            agd::pointwise_scale (p, scaleFactor);
            agd::pointwise_add (p, origin);
        };

    /* Rescale all points and targets */
    for (size_t i = 0; i < config::TotalIndices; ++i)
    {
        rescale (positionsOrigin, PointView <double> (points, i));
        rescale (targetsOrigin, PointView <double> (targets, i));
    }

    /* On each spring, apply the scale factor */
    priv->mSpring.Scale (positionsOrigin, scaleFactor);

    /* Apply width and height changes */
    priv->mWidth = width;
    priv->mHeight = height;
}

wobbly::ConstrainmentStep::ConstrainmentStep (double     const &threshold,
                                              TargetMesh const &targets) :
    threshold (threshold),
    targets (targets)
{
}

bool
wobbly::ConstrainmentStep::operator () (MeshArray         &points,
                                        AnchorArray const &anchors)
{
    /* If an anchor is grabbed, then the model will be considered constrained.
     * The first anchor taking priority - we work out the allowable range for
     * each spring and then apply correction as appropriate before even
     * starting to integrate the model
     */
    return targets.PerformIfActive ([this, &points](MeshArray const &targets) {
        // cppcheck-suppress unreachableCode
        bool ret = false;

        for (size_t i = 0; i < config::TotalIndices; ++i)
        {
            animation::PointView <double const> target (targets, i);
            /* In each position in the main position array we'll work out the
             * pythagorean delta between the ideal positon and current one.
             * If it is outside the maximum range, then we'll shrink the delta
             * and reapply it */
            double const maximumRange = threshold;

            animation::PointView <double> point (points, i);
            double range = agd::distance (target, point);

            if (range < maximumRange)
                continue;

            ret |= true;

            auto sin = (agd::get <1> (target) - agd::get <1> (point)) / range;
            auto cos = (agd::get <0> (target) - agd::get <0> (point)) / range;

            /* Now we want to vectorize range and
             * find our new x and y offsets */
            double const newRange = std::min (maximumRange, range);
            animation::Point newDelta (newRange * cos,
                                       newRange * sin);

            /* Offset from the "target" position */
            agd::assign (point, target);
            agd::pointwise_subtract (point, newDelta);
        }

        return ret;
    });
}

wobbly::EulerIntegration::EulerIntegration ()
{
    velocities.fill (0.0);
}

bool
wobbly::Model::Step (unsigned int time)
{
    bool moreStepsRequired = priv->mCurrentlyUnequal;

    double const FPStepResolution = 16.0f;
    unsigned int steps =
        static_cast <unsigned int> (std::ceil (time / FPStepResolution));

    /* We might not need more steps - set to false initially and then
     * integrate the model to see if we do */
    if (time)
        moreStepsRequired = false;

    moreStepsRequired |= Integrate (priv->mPositions.PointArray (),
                                    priv->mAnchors,
                                    steps,
                                    priv->mConstrainment,
                                    priv->mSpring);

    priv->mCurrentlyUnequal = moreStepsRequired;

    /* If we've settled and have grabbed anchors, snap to the mesh resting
     * point where the cursor is, this ensures exact positioning */
    if (!priv->mCurrentlyUnequal)
    {
        auto       &positions (priv->mPositions.PointArray ());

        priv->mTargets.PerformIfActive ([&positions](MeshArray const &targets) {
            std::copy (targets.begin (), targets.end (), positions.begin ());
        });
    }

    return priv->mCurrentlyUnequal;
}

animation::Point
wobbly::Model::DeformTexcoords (Point const &normalized) const
{
    return priv->mPositions.DeformUnitCoordsToMeshSpace (normalized);
}

std::array <animation::Point, 4> const
wobbly::Model::Extremes () const
{
    return priv->mPositions.Extremes ();
}

wobbly::TargetMesh::TargetMesh (OriginRecalcStrategy const &origin) :
    activationCount (0),
    origin (origin)
{
    mPoints.fill (0);
}

wobbly::TargetMesh::Hnd
wobbly::TargetMesh::Activate () noexcept (true)
{
    /* Recompute where all the targets would be if we have
     * a single anchor. */
    if (++activationCount == 1)
        origin (mPoints);

    Move moveBy = [this](Vector const &delta) {
        if (Active ())
        {
            for (size_t i = 0; i < config::TotalIndices; ++i)
            {
                PointView <double> pv (mPoints, i);
                agd::pointwise_add (pv, delta);
            }
        }
    };

    return Hnd (MakeMoveOnly (std::move (moveBy)),
                [this](MoveOnly <Move> &&handle) {
                    /* Anchor count dropped to 1, but the relevant
                     * anchor could have changed. Recompute where
                     * all the targets are. */
                    if (--activationCount == 1)
                        origin (mPoints);
                });
}

wobbly::BezierMesh::BezierMesh ()
{
    mPoints.fill (0.0);
}

wobbly::BezierMesh::~BezierMesh ()
{
}

namespace
{
    template <typename Point>
    void PointRound (Point &point)
    {
        agd::for_each_coordinate (point, [](auto const &c) {
            return std::round (c);
        });
    }

    template <typename Numeric>
    struct NumericTraits
    {
        typedef Numeric (*Chooser) (Numeric, Numeric);
    };

    template <typename Numeric>
    void SetToExtreme (animation::Point                          &p,
                       Numeric                                   x,
                       typename NumericTraits <Numeric>::Chooser xFinder,
                       Numeric                                   y,
                       typename NumericTraits <Numeric>::Chooser yFinder)
    {
        agd::set <0> (p, xFinder (agd::get <0> (p), x));
        agd::set <1> (p, yFinder (agd::get <1> (p), y));

        /* Round to next integer */
        PointRound (p);
    }

    unsigned int CoordIndex (size_t x,
                             size_t y,
                             unsigned int width)
    {
        return y * width + x;
    }
}

std::array <animation::Point, 4> const
wobbly::BezierMesh::Extremes () const
{
    double const maximum = std::numeric_limits <double>::max ();
    double const minimum = std::numeric_limits <double>::lowest ();

    std::array <animation::Point, 4> extremes =
    {
        {
            animation::Point (maximum, maximum),
            animation::Point (minimum, maximum),
            animation::Point (maximum, minimum),
            animation::Point (minimum, minimum)
        }
    };

    animation::Point &topLeft (extremes[0]);
    animation::Point &topRight (extremes[1]);
    animation::Point &bottomLeft (extremes[2]);
    animation::Point &bottomRight (extremes[3]);

    auto min = [](double lhs, double rhs) -> double {
        double result =  std::min (lhs, rhs);
        return result;
    };

    auto max = [](double lhs, double rhs) -> double {
        double result = std::max (lhs, rhs);
        return result;
    };

    for (size_t i = 0; i < config::Width * config::Height * 2; i += 2)
    {
        double const x = mPoints[i];
        double const y = mPoints[i + 1];

        SetToExtreme (topLeft, x, min, y, min);
        SetToExtreme (topRight, x, max, y, min);
        SetToExtreme (bottomLeft, x, min, y, max);
        SetToExtreme (bottomRight, x, max, y, max);
    }

    return extremes;
}

animation::PointView <double>
wobbly::BezierMesh::PointForIndex (size_t x, size_t y)
{
    return animation::PointView <double> (mPoints,
                                          CoordIndex (x, y, config::Width));
}


text:
module DataAggregation::Index::Controls
  module EventList
    module Write
      def self.call(ending_position=nil, category: nil)
        category ||= StreamName::Category.example random: true

        entity_id = ID::Entity.example
        stream_name = DataAggregation::Index::StreamName.event_list_stream_name entity_id, category

        message_control = Messages::Added

        DataAggregation::Index::Controls::Write.(message_control, ending_position, stream_name: stream_name)

        stream_name
      end
    end
  end
end


text:
A useful tool, to relax our eyes from constant strain by computer screen.The application send a notification which says "blink your eyes" in an interval of 20 minutes.

##How to setup Twenty-Twenty-Notify
1. `ctrl + alt + t` : This opens a terminal in ubuntu.
2. Move to directory where you have clone this repository.
3. Change the directory to the file containg trail.sh.
4. Use this command to add executable permission to trail.sh file.
   `chmod +x trail.sh`
5. Now we will edit the contents of the cronjob file, for this type in the command.
   `crontab -e`
6. Terminal will promt you choose an appropriate editior, if no default editor is set.
7. Copy the location of you trail.sh file, in my case the location is /home/sajal/twenty_twenty/trial.sh.
8. Append the below given line at the end of crontab-e file:
   `*/20 * * * * env DISPLAY=:0 /home/sajal/twenty_twenty/trial.sh`
9. Now sit back,read ebooks or surf the web, now your computer will help you take care of your beautiful eyes.


text:
package de.bwueller.mcgl.nbt.tag;

import java.io.DataOutput;
import java.io.IOException;

public class TagString extends Tag {

    private final String value;

    public TagString(String value) {
        super(Type.STRING);
        this.value = value;
    }

    @Override
    protected void writeNBT(DataOutput out) throws IOException {
        out.writeUTF(value);
    }
}


text:
package java.util;

/**
 * A {@code Map} is a data structure consisting of a set of keys and values
 * in which each key is mapped to a single value.  The class of the objects
 * used as keys is declared when the {@code Map} is declared, as is the
 * class of the corresponding values.
 *

 * A {@code Map} provides helper methods to iterate through all of the
 * keys contained in it, as well as various methods to access and update
 * the key/value pairs.
 */
public interface Map<K,V> {

    /**
     * {@code Map.Entry} is a key/value mapping contained in a {@code Map}.
     */
    public static interface Entry<K,V> {

        /**
         * Returns the key.
         *
         * @return the key
         */
        public K getKey();

        /**
         * Returns the value.
         *
         * @return the value
         */
        public V getValue();

        /**
         * Sets the value of this entry to the specified value, replacing any
         * existing value.
         *
         * @param object
         *            the new value to set.
         * @return object the replaced value of this entry.
         */
        public V setValue(V object);
    };

    /**
     * Removes all elements from this {@code Map}, leaving it empty.
     *
     * @throws UnsupportedOperationException
     *                if removing elements from this {@code Map} is not supported.
     * @see #isEmpty()
     * @see #size()
     */
    public void clear();

    /**
     * Returns whether this {@code Map} contains the specified key.
     *
     * @param key
     *            the key to search for.
     * @return {@code true} if this map contains the specified key,
     *         {@code false} otherwise.
     */
    public boolean containsKey(Object key);

    /**
     * Returns whether this {@code Map} contains the specified value.
     *
     * @param value
     *            the value to search for.
     * @return {@code true} if this map contains the specified value,
     *         {@code false} otherwise.
     */
    public boolean containsValue(Object value);

    /**
     * Returns a {@code Set} containing all of the mappings in this {@code Map}. Each mapping is
     * an instance of {@link Map.Entry}. As the {@code Set} is backed by this {@code Map},
     * changes in one will be reflected in the other.
     *
     * @return a set of the mappings
     */
    public Set<Map.Entry<K,V>> entrySet();

    /**
     * Compares the argument to the receiver, and returns {@code true} if the
     * specified object is a {@code Map} and both {@code Map}s contain the same mappings.
     *
     * @param object
     *            the {@code Object} to compare with this {@code Object}.
     * @return boolean {@code true} if the {@code Object} is the same as this {@code Object}
     *         {@code false} if it is different from this {@code Object}.
     * @see #hashCode()
     * @see #entrySet()
     */
    public boolean equals(Object object);

    /**
     * Returns the value of the mapping with the specified key.
     *
     * @param key
     *            the key.
     * @return the value of the mapping with the specified key, or {@code null}
     *         if no mapping for the specified key is found.
     */
    public V get(Object key);

    /**
     * Returns an integer hash code for the receiver. {@code Object}s which are equal
     * return the same value for this method.
     *
     * @return the receiver's hash.
     * @see #equals(Object)
     */
    public int hashCode();

    /**
     * Returns whether this map is empty.
     *
     * @return {@code true} if this map has no elements, {@code false}
     *         otherwise.
     * @see #size()
     */
    public boolean isEmpty();

    /**
     * Returns a set of the keys contained in this {@code Map}. The {@code Set} is backed by
     * this {@code Map} so changes to one are reflected by the other. The {@code Set} does not
     * support adding.
     *
     * @return a set of the keys.
     */
    public Set<K> keySet();

    /**
     * Maps the specified key to the specified value.
     *
     * @param key
     *            the key.
     * @param value
     *            the value.
     * @return the value of any previous mapping with the specified key or
     *         {@code null} if there was no mapping.
     * @throws UnsupportedOperationException
     *                if adding to this {@code Map} is not supported.
     * @throws ClassCastException
     *                if the class of the key or value is inappropriate for
     *                this {@code Map}.
     * @throws IllegalArgumentException
     *                if the key or value cannot be added to this {@code Map}.
     * @throws NullPointerException
     *                if the key or value is {@code null} and this {@code Map} does
     *                not support {@code null} keys or values.
     */
    public V put(K key, V value);

    /**
     * Copies every mapping in the specified {@code Map} to this {@code Map}.
     *
     * @param map
     *            the {@code Map} to copy mappings from.
     * @throws UnsupportedOperationException
     *                if adding to this {@code Map} is not supported.
     * @throws ClassCastException
     *                if the class of a key or a value of the specified {@code Map} is
     *                inappropriate for this {@code Map}.
     * @throws IllegalArgumentException
     *                if a key or value cannot be added to this {@code Map}.
     * @throws NullPointerException
     *                if a key or value is {@code null} and this {@code Map} does not
     *                support {@code null} keys or values.
     */
    public void putAll(Map<? extends K,? extends V> map);

    /**
     * Removes a mapping with the specified key from this {@code Map}.
     *
     * @param key
     *            the key of the mapping to remove.
     * @return the value of the removed mapping or {@code null} if no mapping
     *         for the specified key was found.
     * @throws UnsupportedOperationException
     *                if removing from this {@code Map} is not supported.
     */
    public V remove(Object key);

    /**
     * Returns the number of mappings in this {@code Map}.
     *
     * @return the number of mappings in this {@code Map}.
     */
    public int size();

    /**
     * Returns a {@code Collection} of the values contained in this {@code Map}. The {@code Collection}
     * is backed by this {@code Map} so changes to one are reflected by the other. The
     * {@code Collection} supports {@link Collection#remove}, {@link Collection#removeAll},
     * {@link Collection#retainAll}, and {@link Collection#clear} operations,
     * and it does not support {@link Collection#add} or {@link Collection#addAll} operations.
     *

     * This method returns a {@code Collection} which is the subclass of
     * {@link AbstractCollection}. The {@link AbstractCollection#iterator} method of this subclass returns a
     * "wrapper object" over the iterator of this {@code Map}'s {@link #entrySet()}. The {@link AbstractCollection#size} method
     * wraps this {@code Map}'s {@link #size} method and the {@link AbstractCollection#contains} method wraps this {@code Map}'s
     * {@link #containsValue} method.
     *

     * The collection is created when this method is called at first time and
     * returned in response to all subsequent calls. This method may return
     * different Collection when multiple calls to this method, since it has no
     * synchronization performed.
     *
     * @return a collection of the values contained in this map.
     */
    public Collection<V> values();
}


text:
<?php

$mess=array(
"CKEditor" => "CKEditor",
"Wysiwyg HTML Editor, requires separate library to be downloaded." => "Editeur HTML Wysiwyg, requiert le téléchargement d'une librairie tierce.",
);


text:
<?php

namespace Shoplo;

class Cart extends Resource
{
	public function retrieve($id = 0, $params = array(), $cache = false)
	{
		if ($id == 0) {
			if (!$cache || !isset($this->bucket['cart'])) {
				$params                   = $this->prepare_params($params);
				$result                   = empty($params) ? $this->send($this->prefix . "carts") : $this->send($this->prefix . "carts?" . $params);
				$this->bucket['cart'] = $this->prepare_result($result);
			}
			return $this->bucket['cart'];
		} else {
			if (!$cache || !isset($this->bucket['cart'][$id])) {
				$result                        = $this->send($this->prefix . "/carts/" . $id);
				$this->bucket['cart'][$id] = $this->prepare_result($result);
			}
			return $this->bucket['cart'][$id];
		}
	}

	public function count($params = array())
	{
		$params = $this->prepare_params($params);
		return empty($params) ? $this->send("cart/count") : $this->send("cart/count?" . $params);
	}

	public function create($fields)
	{
        $fields = array('cart' => $fields);
        return $this->send("carts", 'POST', $fields);
	}

	public function remove($id)
	{
		return $this->send("carts/" . $id, 'DELETE');
	}
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Pucciniosira clemensiae Arthur & Cummins, 1937

### Remarks
null


text:
<script src='/protozoa/js/all.js'></script>

<body>

<script>

var trace2 = function(x) {
	var div = document.createElement('div');
	div.innerHTML = x;
	document.body.appendChild(div);
};

(function(){

	var f = new Form;

	f.link('add', function(){
		alert('add');
	});

	f.render();

})();
</script>


text:
package conn

import (
	"net"
	"time"
)

type Conn struct {
	net.Conn

	readTimeout  time.Duration
	writeTimeout time.Duration
}

func (c *Conn) SetReadTimeout(timeout time.Duration) {
	c.readTimeout = timeout
}

func (c *Conn) SetWriteTimeout(timeout time.Duration) {
	c.writeTimeout = timeout
}

func (c *Conn) SetTimeout(timeout time.Duration) {
	c.readTimeout = timeout
	c.writeTimeout = timeout
}

func (c *Conn) Read(buf []byte) (int, error) {
	e := c.Conn.SetReadDeadline(
		time.Now().Add(c.readTimeout))

	if e != nil {
		return 0, e
	}

	return c.Conn.Read(buf)
}

func (c *Conn) Write(buf []byte) (int, error) {
	e := c.Conn.SetReadDeadline(
		time.Now().Add(c.writeTimeout))

	if e != nil {
		return 0, e
	}

	return c.Conn.Write(buf)
}