text:
"""
This module contains functionality for saving the output of RMG jobs to output
files.
"""

import os.path
import logging
import re

################################################################################

class OutputError(Exception):
    """
    This exception is raised whenever an error occurs while saving output
    information. Pass a string describing the circumstances of the exceptional
    behavior.
    """
    pass

################################################################################

def saveOutputHTML(path, reactionModel, partCoreEdge='core'):
    """
    Save the current set of  species and reactions of `reactionModel` to
    an HTML file `path` on disk. As part of this process, drawings of all
    species are created in the species folder (if they don't already exist)
    using the :mod:`rmgpy.molecule.draw` module. The :mod:`jinja`
    package is used to generate the HTML; if this package is not found, no
    HTML will be generated (but the program will carry on).
    """

    from model import PDepReaction

    from rmgpy.molecule.draw import MoleculeDrawer
    from rmgpy.chemkin import getSpeciesIdentifier

    try:
        import jinja2
    except ImportError:
        logging.warning("jinja2 package not found; HTML output will not be saved.")
        return

    path = os.path.abspath(path)
    dirname = os.path.dirname(path)

    # Prepare parameters to pass to jinja template
    title = 'RMG Output'

    if partCoreEdge == 'core':
        species = reactionModel.core.species[:] + reactionModel.outputSpeciesList
        if not os.path.isdir(os.path.join(dirname,'species')):
            os.makedirs(os.path.join(dirname,'species'))
    elif partCoreEdge == 'edge':
        species = reactionModel.edge.species[:] + reactionModel.outputSpeciesList
        if not os.path.isdir(os.path.join(dirname,'species_edge')):
            os.makedirs(os.path.join(dirname,'species_edge'))

    re_index_search = re.compile(r'\((\d+)\)$').search

    for spec in species:
        # if the species dictionary came from an RMG-Java job, make them prettier
        # We use the presence of a trailing index on the label to discern this
        # (A single open parenthesis is not enough (e.g. when using SMILES strings as labels!)
        match = re_index_search(spec.label)
        if match:
            spec.index = int(match.group(0)[1:-1])
            spec.label = spec.label[0:match.start()]
        # Draw molecules if necessary
        if partCoreEdge == 'core':
            fstr = os.path.join(dirname, 'species', '{0}.png'.format(spec))
        elif partCoreEdge == 'edge':
            fstr = os.path.join(dirname, 'species_edge', '{0}.png'.format(spec))
        if not os.path.exists(fstr):
            try:
                MoleculeDrawer().draw(spec.molecule[0], 'png', fstr)
            except IndexError:
                raise OutputError("{0} species could not be drawn because it did not contain a molecular structure. Please recheck your files.".format(getSpeciesIdentifier(spec)))

    # We want to keep species sorted in the original order in which they were added to the RMG core.
    # Rather than ordered by index
#    species.sort(key=lambda x: x.index)

    if partCoreEdge == 'core':
        reactions = [rxn for rxn in reactionModel.core.reactions ] + reactionModel.outputReactionList
    elif partCoreEdge == 'edge':
        reactions = [rxn for rxn in reactionModel.edge.reactions ] + reactionModel.outputReactionList

    # We want to keep reactions sorted in original order in which they were added to core
    # rather than ordered by index
    #reactions.sort(key=lambda x: x.index)

    familyCount = {}
    for rxn in reactions:

        if isinstance(rxn, PDepReaction):
            family = "PDepNetwork"
        else:
            family = rxn.getSource().label
        if family in familyCount:
            familyCount[family] += 1
        else:
            familyCount[family] = 1
    families = familyCount.keys()
    families.sort()

    ## jinja2 filters etc.
    to_remove_from_css_names = re.compile('[/.\-+,]')
    def csssafe(input):
        "Replace unsafe CSS class name characters with an underscore."
        return to_remove_from_css_names.sub('_',input)

    environment = jinja2.Environment()
    environment.filters['csssafe'] = csssafe

    # Make HTML file
    if partCoreEdge == 'core':
        template = environment.from_string(
"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <title>{{ title }}</title>

{{ title }}

Species ({{ species|length }})

Index	Structure	Label	Mol. Wt. (g/mol)

    {% for spec in species %}

        {{ spec.index }}.

        {{ spec.label }}
        {{ "%.2f"|format(spec.molecule[0].getMolecularWeight() * 1000) }}

    {% if spec.thermo %}

                    H298
                    S298
                    Cp300
                    Cp500
                    Cp1000
                    Cp1500

                    {% if spec.thermo.Tmin.value_si <= 298 %}
                    {{ "%.2f"|format(spec.thermo.getEnthalpy(298) / 4184) }}
                    {% endif %}
                    {% if spec.thermo.Tmin.value_si <= 298 %}
                    {{ "%.2f"|format(spec.thermo.getEntropy(298) / 4.184) }}
                    {% endif %}
                    {{ "%.2f"|format(spec.thermo.getHeatCapacity(300) / 4.184) }}
                    {{ "%.2f"|format(spec.thermo.getHeatCapacity(500) / 4.184) }}
                    {{ "%.2f"|format(spec.thermo.getHeatCapacity(1000) / 4.184) }}
                    {{ "%.2f"|format(spec.thermo.getHeatCapacity(1500) / 4.184) }}

        {% endif %}
    {% endfor %}

Reactions ({{ reactions|length }})

<form id='familySelector' action="">

Reaction families:

{% for family in families %}    <input type="checkbox" id="{{ family|csssafe }}" name="family" value="{{ family|csssafe }}" checked="checked" onclick="updateFamily(this);">{{ family }} ({{ familyCount[family] }} rxn{{ 's' if familyCount[family] != 1 }})

{% endfor %}
    check all     uncheck all

Reaction Details:

    <input type="checkbox" id="kinetics" name="detail" value="kinetics" onclick="updateDetails(this);">Kinetics

    <input type="checkbox" id="comment" name="detail" value="comment" onclick="updateDetails(this);">Comments

    <input type="checkbox" id="chemkin" name="detail" value="chemkin" onclick="updateDetails(this);">Chemkin strings

    check all     uncheck all
</form>

Reaction List:

Index	Reaction	Family

    {% for rxn in reactions %}

        {{ rxn.index }}.
        {% for reactant in rxn.reactants %}{% if not loop.last %} + {% endif %}{% endfor %}
        {% if rxn.reversible %}⇔{% else %}→{% endif %}
        {% for product in rxn.products %}{% if not loop.last %} + {% endif %}{% endfor %}
        {{ rxn.getSource().label }}

        {{ rxn.kinetics.toHTML() }}

        {{ rxn.toChemkin(species) }}

        {{ rxn.kinetics.comment }}

    {% endfor %}

""")
    elif partCoreEdge == 'edge':
        template = environment.from_string(
"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <title>{{ title }}</title>

{{ title }}

Species ({{ species|length }})

Index	Structure	Label	Mol. Wt. (g/mol)

    {% for spec in species %}

        {{ spec.index }}.

        {{ spec.label }}
        {{ "%.2f"|format(spec.molecule[0].getMolecularWeight() * 1000) }}

    {% if spec.thermo %}

                    H298
                    S298
                    Cp300
                    Cp500
                    Cp1000
                    Cp1500

                    {% if spec.thermo.Tmin.value_si <= 298 %}
                    {{ "%.2f"|format(spec.thermo.getEnthalpy(298) / 4184) }}
                    {% endif %}
                    {% if spec.thermo.Tmin.value_si <= 298 %}
                    {{ "%.2f"|format(spec.thermo.getEntropy(298) / 4.184) }}
                    {% endif %}
                    {{ "%.2f"|format(spec.thermo.getHeatCapacity(300) / 4.184) }}
                    {{ "%.2f"|format(spec.thermo.getHeatCapacity(500) / 4.184) }}
                    {{ "%.2f"|format(spec.thermo.getHeatCapacity(1000) / 4.184) }}
                    {{ "%.2f"|format(spec.thermo.getHeatCapacity(1500) / 4.184) }}

        {% endif %}
    {% endfor %}

Reactions ({{ reactions|length }})

<form id='familySelector' action="">

Reaction families:

{% for family in families %}    <input type="checkbox" id="{{ family|csssafe }}" name="family" value="{{ family|csssafe }}" checked="checked" onclick="updateFamily(this);">{{ family }} ({{ familyCount[family] }} rxn{{ 's' if familyCount[family] != 1 }})

{% endfor %}
    check all     uncheck all

Reaction Details:

    <input type="checkbox" id="kinetics" name="detail" value="kinetics" onclick="updateDetails(this);">Kinetics

    <input type="checkbox" id="comment" name="detail" value="comment" onclick="updateDetails(this);">Comments

    <input type="checkbox" id="chemkin" name="detail" value="chemkin" onclick="updateDetails(this);">Chemkin strings

    check all     uncheck all
</form>

Reaction List:

Index	Reaction	Family

    {% for rxn in reactions %}

        {{ rxn.index }}.
        {% for reactant in rxn.reactants %}{% if not loop.last %} + {% endif %}{% endfor %}
        {% if rxn.reversible %}⇔{% else %}→{% endif %}
        {% for product in rxn.products %}{% if not loop.last %} + {% endif %}{% endfor %}
        {{ rxn.getSource().label }}

        {{ rxn.kinetics.toHTML() }}

        {{ rxn.toChemkin(species) }}

        {{ rxn.kinetics.comment }}

    {% endfor %}

""")

    f = open(path, 'w')
    f.write(template.render(title=title, species=species, reactions=reactions, families=families, familyCount=familyCount))
    f.close()

def saveDiffHTML(path, commonSpeciesList, speciesList1, speciesList2, commonReactions, uniqueReactions1, uniqueReactions2):
    """
    This function outputs the species and reactions on an HTML page
    for the comparison of two RMG models.
    """
    from model import PDepReaction
    from rmgpy.kinetics import Arrhenius, MultiArrhenius, MultiPDepArrhenius

    from rmgpy.molecule.draw import MoleculeDrawer
    try:
        import jinja2
    except ImportError:
        logging.warning("jinja package not found; HTML output will not be saved.")
        return

    path = os.path.abspath(path)
    dirname = os.path.dirname(path)

    # Prepare parameters to pass to jinja template
    title = 'RMG Model Comparison'

    speciesList = [spec1 for spec1, spec2 in commonSpeciesList] + [spec2 for spec1, spec2 in commonSpeciesList] + speciesList1 + speciesList2
    re_index = re.compile(r'\((\d+)\)$')

    if not os.path.isdir(os.path.join(dirname,'species1')):
        os.makedirs(os.path.join(dirname,'species1'))

    if not os.path.isdir(os.path.join(dirname,'species2')):
        os.makedirs(os.path.join(dirname,'species2'))

    for spec1, spec2 in commonSpeciesList:
        # if the species dictionary came from an RMG-Java job, make them prettier
        # We use the presence of a trailing index on the label to discern this
        # (A single open parenthesis is not enough (e.g. when using SMILES strings as labels!)
        match1 = re_index.search(spec1.label)
        if match1:
            spec1.index = int(match1.group(0)[1:-1])
            spec1.label = spec1.label[0:match1.start()]

        match2 = re_index.search(spec2.label)
        if match2:
            spec2.index = int(match2.group(0)[1:-1])
            spec2.label = spec2.label[0:match2.start()]

        # Draw molecules if necessary
        fstr = os.path.join(dirname, 'species1', '{0}.png'.format(spec1))
        if not os.path.exists(fstr):
            try:
                MoleculeDrawer().draw(spec1.molecule[0], 'png', fstr)
            except IndexError:
                raise OutputError('{0} species could not be drawn because it did not contain a molecular structure. Please recheck your files.'.format(getSpeciesIdentifier(spec1)))

        fstr = os.path.join(dirname, 'species2', '{0}.png'.format(spec2))
        if not os.path.exists(fstr):
            try:
                MoleculeDrawer().draw(spec2.molecule[0], 'png', fstr)
            except IndexError:
                raise OutputError('{0} species could not be drawn because it did not contain a molecular structure. Please recheck your files.'.format(getSpeciesIdentifier(spec2)))

    for spec in speciesList1:
        match = re_index.search(spec.label)
        if match:
            spec.index = int(match.group(0)[1:-1])
            spec.label = spec.label[0:match.start()]
        # Draw molecules if necessary
        fstr = os.path.join(dirname, 'species1', '{0}.png'.format(spec))
        if not os.path.exists(fstr):
            try:
                MoleculeDrawer().draw(spec.molecule[0], 'png', fstr)
            except IndexError:
                raise OutputError('{0} species could not be drawn because it did not contain a molecular structure. Please recheck your files.'.format(getSpeciesIdentifier(spec)))

    for spec in speciesList2:
        match = re_index.search(spec.label)
        if match:
            spec.index = int(match.group(0)[1:-1])
            spec.label = spec.label[0:match.start()]
        # Draw molecules if necessary
        fstr = os.path.join(dirname, 'species2', '{0}.png'.format(spec))
        if not os.path.exists(fstr):
            try:
                MoleculeDrawer().draw(spec.molecule[0], 'png', fstr)
            except IndexError:
                raise OutputError('{0} species could not be drawn because it did not contain a molecular structure. Please recheck your files.'.format(getSpeciesIdentifier(spec)))

    familyCount1 = {}
    familyCount2 = {}
    for rxn1, rxn2 in commonReactions:
        if isinstance(rxn2.kinetics, (MultiArrhenius,MultiPDepArrhenius)):
            rxn2.duplicate = True
        if isinstance(rxn1, PDepReaction):
            family = "PDepNetwork"
        else:
            family = rxn1.getSource().label
        if family in familyCount1:
            familyCount1[family] += 1
            familyCount2[family] += 1
        else:
            familyCount1[family] = 1
            familyCount2[family] = 1

    for rxn in uniqueReactions1:
        if isinstance(rxn, PDepReaction):
            family = "PDepNetwork"
        else:
            family = rxn.getSource().label
        if family in familyCount1:
            familyCount1[family] += 1
        else:
            familyCount1[family] = 1

    for rxn in uniqueReactions2:
        if isinstance(rxn, PDepReaction):
            family = "PDepNetwork"
        else:
            family = rxn.getSource().label
        if family in familyCount2:
            familyCount2[family] += 1
        else:
            familyCount2[family] = 1

    families1 = familyCount1.keys()
    families2 = familyCount2.keys()
    families1.sort()
    families2.sort()

    ## jinja2 filters etc.
    to_remove_from_css_names = re.compile('[/.\-+,]')
    def csssafe(input):
        "Replace unsafe CSS class name characters with an underscore."
        return to_remove_from_css_names.sub('_',input)

    environment = jinja2.Environment()
    environment.filters['csssafe'] = csssafe

# Make HTML file
    template = environment.from_string(
"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <title>{{ title }}</title>

{{ title }}

Common Species ({{ commonSpecies|length }})

    {% for spec1, spec2 in commonSpecies %}

                    {{ spec1.label }}

                    {{ "%.2f"|format(spec1.molecule[0].getMolecularWeight() * 1000) }}

    {% if spec1.thermo and spec2.thermo %}
    {% if spec1.thermo.isIdenticalTo(spec2.thermo) %}

IDENTICAL THERMO WAS FOUND FOR THIS SPECIES.

    {% elif spec1.thermo.isSimilarTo(spec2.thermo) %}

SIMILAR THERMO WAS FOUND FOR THIS SPECIES.

    {% else %}

DIFFERENT THERMO WAS FOUND FOR THIS SPECIES.

    {% endif%}

        {{ spec1.index }}.

                    H300
                    S300
                    Cp300
                    Cp500
                    Cp1000
                    Cp1500

                    {% if spec1.thermo.Tmin.value_si <= 300 %}
                    {{ "%.2f"|format(spec1.thermo.getEnthalpy(300) / 4184) }}
                    {% endif %}

                    {% if spec1.thermo.Tmin.value_si <= 300 %}
                    {{ "%.2f"|format(spec1.thermo.getEntropy(300) / 4.184) }}
                    {% endif %}
                    {{ "%.2f"|format(spec1.thermo.getHeatCapacity(300) / 4.184) }}
                    {{ "%.2f"|format(spec1.thermo.getHeatCapacity(500) / 4.184) }}
                    {{ "%.2f"|format(spec1.thermo.getHeatCapacity(1000) / 4.184) }}
                    {{ "%.2f"|format(spec1.thermo.getHeatCapacity(1500) / 4.184) }}

        {{ spec2.index }}.

                    H300
                    S300
                    Cp300
                    Cp500
                    Cp1000
                    Cp1500

                    {% if spec2.thermo.Tmin.value_si <= 300 %}
                    {{ "%.2f"|format(spec2.thermo.getEnthalpy(300) / 4184) }}
                    {% endif %}
                    {% if spec2.thermo.Tmin.value_si <= 300 %}
                    {{ "%.2f"|format(spec2.thermo.getEntropy(300) / 4.184) }}
                    {% endif %}
                    {{ "%.2f"|format(spec2.thermo.getHeatCapacity(300) / 4.184) }}
                    {{ "%.2f"|format(spec2.thermo.getHeatCapacity(500) / 4.184) }}
                    {{ "%.2f"|format(spec2.thermo.getHeatCapacity(1000) / 4.184) }}
                    {{ "%.2f"|format(spec2.thermo.getHeatCapacity(1500) / 4.184) }}

    {% endif %}

    {% endfor %}

Model 1: Unique Species ({{ speciesList1|length }})

Index	Structure	Label	Mol. Wt. (g/mol)

    {% for spec in speciesList1 %}

        {{ spec.index }}.

        {{ spec.label }}
        {{ "%.2f"|format(spec.molecule[0].getMolecularWeight() * 1000) }}

    {% endfor %}

Model 2: Unique Species ({{ speciesList2|length }})

Index	Structure	Label	Mol. Wt. (g/mol)

    {% for spec in speciesList2 %}

        {{ spec.index }}.

        {{ spec.label }}
        {{ "%.2f"|format(spec.molecule[0].getMolecularWeight() * 1000) }}

    {% endfor %}

Model 1 Reactions ({{ commonReactions|length + uniqueReactions1|length}})

<form id='familySelector' action="">

Reaction families:

{% for family in families1 %}    <input type="checkbox" id="{{ family|csssafe }}" name="family" value="{{ family|csssafe }}" checked="checked" onclick="updateFamily(this);">{{ family }} ({{ familyCount1[family] }} rxn{{ 's' if familyCount1[family] != 1 }})

{% endfor %}
    check all     uncheck all

Reaction Details:

    <input type="checkbox" id="kinetics" name="detail" value="kinetics" onclick="updateDetails(this);">Kinetics

    <input type="checkbox" id="comment" name="detail" value="comment" onclick="updateDetails(this);">Comments

    <input type="checkbox" id="chemkin" name="detail" value="chemkin" onclick="updateDetails(this);">Chemkin strings

    check all     uncheck all
</form>

Model 2 Reactions ({{ commonReactions|length +uniqueReactions2|length}})

<form id='familySelector' action="">

Reaction families:

{% for family in families2 %}    <input type="checkbox" id="{{ family|csssafe }}" name="family" value="{{ family|csssafe }}" checked="checked" onclick="updateFamily(this);">{{ family }} ({{ familyCount2[family] }} rxn{{ 's' if familyCount2[family] != 1 }})

{% endfor %}
    check all     uncheck all

Reaction Details:

    <input type="checkbox" id="kinetics" name="detail" value="kinetics" onclick="updateDetails(this);">Kinetics

    <input type="checkbox" id="comment" name="detail" value="comment" onclick="updateDetails(this);">Comments

    <input type="checkbox" id="chemkin" name="detail" value="chemkin" onclick="updateDetails(this);">Chemkin strings

    check all     uncheck all
</form>

Common Reactions ({{ commonReactions|length}})

Index.	Family	Index.	Family

    {% for rxn1, rxn2 in commonReactions %}

    {% for reactant in rxn1.reactants %}{% if not loop.last %} + {% endif %}{% endfor %}
    {% if rxn1.reversible %}⇔{% else %}→{% endif %}
    {% for product in rxn1.products %}{% if not loop.last %} + {% endif %}{% endfor %}

{% if rxn1.kinetics.isIdenticalTo(rxn2.kinetics) %}

IDENTICAL KINETICS WERE FOUND FOR THIS REACTION.

{% elif rxn1.kinetics.isSimilarTo(rxn2.kinetics) %}

SIMILAR KINETICS WERE FOUND FOR THIS REACTION.

{% else %}

DIFFERENT KINETICS WERE FOUND FOR THIS REACTION.

{% endif%}

     {{ rxn1.index }}.
     {{ rxn1.getSource().label }}

     {{ rxn2.index }}.
     {{ rxn2.getSource().label }}

{% if not rxn1.isIsomorphic(rxn2, eitherDirection=False) %}

* Reaction was found in reverse

{% if not rxn2.duplicate %}

Fitted Reverse Kinetics:
{% if not rxn2.kinetics.isPressureDependent() %}
{{rxn2.generateReverseRateCoefficient().toHTML() }}
{% else %} Pressure dependent
{% endif %}
{% endif %}

Original Kinetics:
{% endif %}

     {{ rxn1.kinetics.toHTML() }}

     {{ rxn2.kinetics.toHTML() }}

    {{ rxn1.toChemkin(speciesList) }}
    {{ rxn2.toChemkin(speciesList) }}

    {{ rxn1.kinetics.comment }}
    {{ rxn2.kinetics.comment }}

{% endfor %}

Model 1: Unique Reactions ({{ uniqueReactions1|length}})

Index	Reaction	Family

    {% for rxn in uniqueReactions1 %}

        {{ rxn.index }}.
        {% for reactant in rxn.reactants %}{% if not loop.last %} + {% endif %}{% endfor %}
        {% if rxn.reversible %}⇔{% else %}→{% endif %}
        {% for product in rxn.products %}{% if not loop.last %} + {% endif %}{% endfor %}
        {{ rxn.getSource().label }}

        {{ rxn.kinetics.toHTML() }}

        {{ rxn.toChemkin(species) }}

        {{ rxn.kinetics.comment }}

    {% endfor %}

Model 2: Unique Reactions ({{ uniqueReactions2|length}})

Index	Reaction	Family

    {% for rxn in uniqueReactions2 %}

        {{ rxn.index }}.
        {% for reactant in rxn.reactants %}{% if not loop.last %} + {% endif %}{% endfor %}
        {% if rxn.reversible %}⇔{% else %}→{% endif %}
        {% for product in rxn.products %}{% if not loop.last %} + {% endif %}{% endfor %}
        {{ rxn.getSource().label }}

        {{ rxn.kinetics.toHTML() }}

        {{ rxn.toChemkin(species) }}

        {{ rxn.kinetics.comment }}

    {% endfor %}

""")
    f = open(path, 'w')
    f.write(template.render(title=title, commonSpecies=commonSpeciesList, speciesList1=speciesList1, speciesList2 = speciesList2, commonReactions=commonReactions, uniqueReactions1=uniqueReactions1, uniqueReactions2=uniqueReactions2, families1=families1, families2=families2, familyCount1=familyCount1,familyCount2=familyCount2, speciesList=speciesList))
    f.close()


text:
<?php

namespace Google\Service\CloudSearch;

class ListQuerySourcesResponse extends \Google\Collection
{
  protected $collection_key = 'sources';
  /**
   * @var string
   */
  public $nextPageToken;
  protected $sourcesType = QuerySource::class;
  protected $sourcesDataType = 'array';

  /**
   * @param string
   */
  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  /**
   * @return string
   */
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
  /**
   * @param QuerySource[]
   */
  public function setSources($sources)
  {
    $this->sources = $sources;
  }
  /**
   * @return QuerySource[]
   */
  public function getSources()
  {
    return $this->sources;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ListQuerySourcesResponse::class, 'Google_Service_CloudSearch_ListQuerySourcesResponse');

redpajama_set_name: RedPajamaGithub


text:
//
// $Id$
//
// Wiggle - a 2D game development library - http://code.google.com/p/wiggle/
// Copyright 2008-2010 Michael Bayne
// Distributed under the "Simplified BSD License" in LICENSE.txt

package wiggle.util

/**
 * Encapsulates a function that interpolates between two values.
 */
trait Interpolator
{
  /** Interpolates between two values.
   *
   *  @param start the starting value.
   *  @param range the difference between the ending value and the starting value.
   *  @param dt the amount of time that has elapsed.
   *  @param t the total amount of time for the interpolation.
   */
  def apply (start :Float, range :Float, dt :Float, t :Float) :Float
}

/**
 * Provides convenience functions for creating various interpolators.
 */
object Interpolator
{
  /** An interpolator that always returns the starting position. */
  val noop = new Interpolator {
    def apply (start :Float, range :Float, dt :Float, t :Float) = start
  }

  /** A linear interpolator. */
  val linear = new Interpolator {
    def apply (start :Float, range :Float, dt :Float, t :Float) = start + range * dt / t
  }

  /** An interpolator that starts to change slowly and ramps up to full speed. */
  val easeIn = new Interpolator {
    def apply (start :Float, range :Float, dt :Float, t :Float) = {
      val dtt = dt / t
      start + range * dtt * dtt * dtt
    }
  }

  /** An interpolator that starts to change quickly and eases into the final value. */
  val easeOut = new Interpolator {
    def apply (start :Float, range :Float, dt :Float, t :Float) = {
      val dtt = dt / t - 1
      start + range * (1 + dtt * dtt * dtt)
    }
  }

  /** An interpolator that eases away from the starting value, speeds up, then eases into the final
   *  value. */
  val easeInOut = new Interpolator {
    def apply (start :Float, range :Float, dt :Float, t :Float) = {
      val hdtt = dt / (t/2)
      if (hdtt < 1) start + range/2 * hdtt * hdtt * hdtt
      else {
        val nhdtt = hdtt - 2
        start + range/2 * (2 + nhdtt * nhdtt * nhdtt)
      }
    }
  }
}


text:
package com.box.sdk;

/**
 * Defines the role of the signer in the sign request. Signers will need to sign the document,
 * Approvers may just approve the document.
 * Finally, FinalCopyReader will only receive the finished sign request with a sign log.
 */
public enum BoxSignRequestSignerRole {

    /**
     * Signer role. Needs to sign the document.
     */
    Signer("signer"),

    /**
     * Approver role. Approves the document.
     */
    Approver("approver"),

    /**
     * Final copy reader role. Receives finished sign request with sign log.
     */
    FinalCopyReader("final_copy_reader");

    private final String jsonValue;

    BoxSignRequestSignerRole(String jsonValue) {
        this.jsonValue = jsonValue;
    }

    static BoxSignRequestSignerRole fromJSONString(String jsonValue) {
        if ("signer".equals(jsonValue)) {
            return Signer;
        } else if ("approver".equals(jsonValue)) {
            return Approver;
        } else if ("final_copy_reader".equals(jsonValue)) {
            return FinalCopyReader;
        }
        throw new IllegalArgumentException("The provided JSON value isn't a valid BoxSignRequestSignerRole.");
    }
}


text:
package com.muatik.repository;

import com.muatik.model.MyEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by muatik on 12/31/16.
 */
@Repository
public interface MyEntityRepository extends CrudRepository<MyEntity, Long>{
}


text:
#* version.rb - The version string for fOOrth.
module XfOOrth
  #The version string for fOOrth.
  VERSION = "0.6.11"
end


text:
<?php

namespace Intrepion\JsonApi\Request\HttpVerbs;

/**
 * Delete
 */
class Delete
{
    /**
     * @var string
     */
    protected $resourceName;

    /**
     * Set resourceName
     *
     * @param string $resourceName
     * @return Delete
     */
    public function setResourceName($resourceName)
    {
        if (!is_string($resourceName)) {
            throw new \InvalidArgumentException('resourceName should be a string');
        }
        $this->resourceName = $resourceName;

        return $this;
    }

    /**
     * Get resourceName
     *
     * @return string
     */
    public function getResourceName()
    {
        return $this->resourceName;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <LINK REL="icon" HREF="favicon.ico" TYPE="image/x-icon" />
    <LINK REL="shortcut icon" HREF="favicon.ico" TYPE="image/x-icon" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <meta name="verify-v1" content="z8vVELTm0H3D4W5YQEVBgflrASmGnaJO4X3sQ7yPB8I=" />

	<meta name="description" content="BikeBingle, Bicycle accident tracking"/>
    <meta name="keywords" content="BikeBingle, Bicycle, accident, tracking, collision, cyclist, safety"/>

    <title>BikeBingle</title>

        FAQ
        Credits
        Introduction


text:
package blended.security.scep.standalone

import java.io.File
import java.io.FileReader
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

import blended.security.ssl.internal.PasswordHasher
import blended.util.logging.Logger
import de.tototec.cmdoption.CmdlineParser
import org.bouncycastle.cert.X509CertificateHolder
import org.bouncycastle.openssl.PEMEncryptedKeyPair
import org.bouncycastle.openssl.PEMKeyPair
import org.bouncycastle.openssl.PEMParser
import org.bouncycastle.pkcs.PKCS10CertificationRequest

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.Failure
import scala.util.Success
import scala.util.control.NonFatal

object ScepClientApp {

  private[this] val log = Logger[ScepClientApp.type]

  /**
    * Entry point of the scep client app.
    * The app logic is done by [[run()]] which throws an [[ExitAppException]] to signal the exit code.
    * This will stop the running VM with [[java.lang.System#exit]]
    */
  def main(args: Array[String]): Unit = {
    try {
      run(args)
      // default to 0
      // throw new ExitAppException(0)
    } catch {
      case e: ExitAppException =>
        e.errMsg.foreach { m =>
          Console.err.println(m)
        }
        Logger[ScepClientApp.type].debug(e)(s"About to exit VM from main-method with exit code [${e.exitCode}]")
        System.exit(e.exitCode) // ! Hard exit !
      case NonFatal(e) =>
        Logger[ScepClientApp.type].error(e)(s"An unexepected error occured. Exiting the application with exit code [2]\nReason: ${e.getMessage()}")
        System.exit(2) // ! Hard exit !
    }
  }

  /**
    * Run the scep client app.
    *
    * @param args
    * @throws ExitAppException The signal the exit code of the application
    */
  def run(args: Array[String]): Unit = {
    val cmdline = new Cmdline()
    val cp = new CmdlineParser(cmdline)
    cp.setProgramName("java -jar scep-client.jar")
    cp.setAboutLine("Standalone SCEP client, which can create and update Java key stores from a remote SCEP server.")
    cp.parse(args: _*)

    if (cmdline.help || args.isEmpty) {
      cp.usage()
      throw new ExitAppException(0)
    }

    val salt = cmdline.salt.getOrElse("scep-client")

    cmdline.password.foreach { pass =>
      println(new PasswordHasher(salt).password(pass))
    }

    cmdline.infoFile.foreach { infoFile =>
      readInfoFile(infoFile)
    }

    cmdline.csrFile.foreach { csrFile =>
      readCsrFile(csrFile)
    }

    if (cmdline.refreshCerts) {
      refreshCert(salt, timeout = Duration(5, TimeUnit.SECONDS))
    }

  }

  def readInfoFile(infoFileName: String): Unit = {
    val file = new File(infoFileName).getAbsoluteFile()
    if (!file.exists() || !file.isFile()) {
      throw new RuntimeException(s"File does not exists: ${file}")
    }
    log.debug(s"About to parse file ${file}")
    val reader = new FileReader(file)
    val parser = new PEMParser(reader)
    val readObject = parser.readObject()
    log.debug(s"Parsed object [${readObject}]")
    readObject match {
      case encKeyPair: PEMEncryptedKeyPair =>
        log.debug(s"Got an encrypted key pair - need a password to decrypt")
      case keyPair: PEMKeyPair =>
        log.debug(s"Got an (unencrypted) key pair - no password needed")
      case cert: X509CertificateHolder =>
        log.debug(s"Got an certificate holder. subject [${cert.getSubject()}], version [${cert.getVersionNumber()}], extensions [${cert.getExtensions()}]")
      case csr: PKCS10CertificationRequest =>
        log.debug(s"Got a CSR. subject [${csr.getSubject()}], " +
          s"attributes [${csr.getAttributes().map(a => s"Attribute(type [${a.getAttrType()}], values [${a.getAttrValues}])").mkString(", ")}]")
    }
  }

  def readCsrFile(csrFile: String): Unit = {
    val file = new File(csrFile).getAbsoluteFile()
    if (!file.exists() || !file.isFile()) {
      throw new RuntimeException(s"File does not exists: ${file}")
    }
    log.debug(s"About to parse file ${file}")
    val reader = new FileReader(file)
    val parser = new PEMParser(reader)
    val readObject = parser.readObject()
    log.debug(s"Parsed object [${readObject}]")
    readObject match {

      case csr: PKCS10CertificationRequest =>
        val subjectPublicKeyInfo = csr.getSubjectPublicKeyInfo()
        val details = Seq(
          "subject" -> csr.getSubject(),
          "attributes" -> csr.getAttributes().toList,
          "signature" -> csr.getSignature().toList,
          "signatureAlgorithm" -> csr.getSignatureAlgorithm(),
          "subjectPublicKeyInfo" -> subjectPublicKeyInfo,
          "subjectPublicKeyInfo.algorithm" -> subjectPublicKeyInfo.getAlgorithm(),
          "subjectPublicKeyInfo.algorithm.algorithm" -> subjectPublicKeyInfo.getAlgorithm().getAlgorithm(),
          "subjectPublicKeyInfo.algorithm.parameters" -> subjectPublicKeyInfo.getAlgorithm().getParameters(),
          "subjectPublicKeyInfo.publicKeyData" -> subjectPublicKeyInfo.getPublicKeyData()
        )

        log.debug(s"Got a CSR. Info:\n  ${details.map(t => s"${t._1}: ${t._2}").mkString("\n  ")}")

      case other =>
        val msg = s"File [${csrFile}] has no supported CSR file format"
        log.error(msg)
        throw new ExitAppException(1, Some(msg))
    }
  }

  def refreshCert(salt: String, timeout: Duration): Unit = {
    implicit val executionContext = scala.concurrent.ExecutionContext.global
    val refresher = new CertRefresher(salt)
    val checking = refresher.checkCert()

    try {
      Await.ready(checking, atMost = timeout).value.get match {
        case Success(r) =>
          println(s"Successfully refreshed certificates")
          refresher.stop()
          throw new ExitAppException(
            exitCode = 0,
            errMsg = Some(s"Successfully refreshed certificates")
          )

        case Failure(e) =>
          refresher.stop()
          throw new ExitAppException(
            exitCode = 1,
            errMsg = Some(s"Error: Could not refresh certificates.\nReason: ${e.getMessage()}\nSee log file for details."),
            cause = e
          )
      }
    } catch {
      case e: TimeoutException =>
        refresher.stop()
        throw new ExitAppException(
          exitCode = 1,
          errMsg = Some(s"Error: Could not refresh certificates.\nReason: Timeout after [${timeout}]\nSee log file for details."),
          cause = e
        )
    }
  }
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Duracellko.PlanningPoker.E2ETest.Browser;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;

namespace Duracellko.PlanningPoker.E2ETest
{
    [TestClass]
    public class ScrumMasterTest : E2ETestBase
    {
        [DataTestMethod]
        [EnvironmentDataSource]
        public async Task ScrumMaster_Should_Be_Able_To_Estimate(bool serverSide, BrowserType browserType, bool useHttpClient)
        {
            Contexts.Add(new BrowserTestContext(
                nameof(ScrumMasterTest),
                nameof(ScrumMaster_Should_Be_Able_To_Estimate),
                browserType,
                serverSide,
                useHttpClient));

            await StartServer();
            StartClients();

            string team = "My team";
            string scrumMaster = "Test ScrumMaster";
            string deckText = "0, 0.5, 1, 2, 3, 5, 8, 13, 20, 40, 100";

            await ClientTest.OpenApplication();
            TakeScreenshot("01-Loading");
            ClientTest.AssertIndexPage();
            TakeScreenshot("02-Index");
            ClientTest.FillCreateTeamForm(team, scrumMaster, "Standard", deckText);
            TakeScreenshot("03-CreateTeamForm");
            ClientTest.SubmitCreateTeamForm();
            ClientTest.AssertPlanningPokerPage("My%20team", "Test%20ScrumMaster");
            TakeScreenshot("04-PlanningPoker");
            ClientTest.AssertTeamName(team, scrumMaster);
            ClientTest.AssertScrumMasterInTeam(scrumMaster);
            ClientTest.AssertMembersInTeam();
            ClientTest.AssertObserversInTeam();
            ClientTest.StartEstimation();
            TakeScreenshot("05-EstimationStarted");
            ClientTest.AssertAvailableEstimations();
            ClientTest.SelectEstimation("1");
            await Task.Delay(500);
            TakeScreenshot("06-Estimated");
            ClientTest.AssertSelectedEstimation(new KeyValuePair<string, string>(scrumMaster, "1"));
            ClientTest.Disconnect();
            TakeScreenshot("07-Disconnected");
        }

        [DataTestMethod]
        [EnvironmentDataSource]
        public async Task ScrumMaster_Can_Select_Estimation_Deck(bool serverSide, BrowserType browserType, bool useHttpClient)
        {
            Contexts.Add(new BrowserTestContext(
                nameof(ScrumMasterTest),
                nameof(ScrumMaster_Can_Select_Estimation_Deck),
                browserType,
                serverSide,
                useHttpClient));

            await StartServer();
            StartClients();

            string team = "RPSLS";
            string scrumMaster = "Initiator";
            string deckText = "Rock, Paper, Scissors, Lizard, Spock";
            var availableEstimations = new string[]
            {
                "\uD83D\uDC8E", // Rock
                "\uD83D\uDCDC", // Paper
                "\u2702", // Scissors
                "\uD83E\uDD8E", // Lizard
                "\uD83D\uDD96", // Spock
            };

            await ClientTest.OpenApplication();
            TakeScreenshot("01-Loading");
            ClientTest.AssertIndexPage();
            TakeScreenshot("02-Index");
            ClientTest.FillCreateTeamForm(team, scrumMaster, "RockPaperScissorsLizardSpock", deckText);
            TakeScreenshot("03-CreateTeamForm");
            ClientTest.SubmitCreateTeamForm();
            ClientTest.AssertPlanningPokerPage("RPSLS", "Initiator");
            TakeScreenshot("04-PlanningPoker");
            ClientTest.AssertTeamName(team, scrumMaster);
            ClientTest.AssertScrumMasterInTeam(scrumMaster);
            ClientTest.AssertMembersInTeam();
            ClientTest.AssertObserversInTeam();
            ClientTest.StartEstimation();
            TakeScreenshot("05-EstimationStarted");
            ClientTest.AssertAvailableEstimations(availableEstimations);
            ClientTest.SelectEstimation(1);
            await Task.Delay(500);
            TakeScreenshot("06-Estimated");
            ClientTest.AssertSelectedEstimation(new KeyValuePair<string, string>(scrumMaster, availableEstimations[1]));
            ClientTest.Disconnect();
            TakeScreenshot("07-Disconnected");
        }

        [DataTestMethod]
        [EnvironmentDataSource]
        public async Task Shows_Error_When_Creating_Empty_Team(bool serverSide, BrowserType browserType, bool useHttpClient)
        {
            Contexts.Add(new BrowserTestContext(
                nameof(ScrumMasterTest),
                nameof(Shows_Error_When_Creating_Empty_Team),
                browserType,
                serverSide,
                useHttpClient));

            await StartServer();
            StartClients();

            await ClientTest.OpenApplication();
            TakeScreenshot("01-Loading");
            ClientTest.AssertIndexPage();
            TakeScreenshot("02-Index");
            ClientTest.SubmitCreateTeamForm();
            ClientTest.AssertIndexPage();
            TakeScreenshot("03-RequiredError");

            Assert.IsNotNull(ClientTest.CreateTeamForm);
            var input = ClientTest.CreateTeamForm.FindElement(By.Id("createTeam$teamName"));
            var required = input.FindElement(By.XPath("../span"));
            Assert.AreEqual("Required", required.Text);

            input = ClientTest.CreateTeamForm.FindElement(By.Id("createTeam$scrumMasterName"));
            required = input.FindElement(By.XPath("../span"));
            Assert.AreEqual("Required", required.Text);
        }

        [DataTestMethod]
        [EnvironmentDataSource]
        public async Task Shows_Error_When_Joining_Not_Existing_Team(bool serverSide, BrowserType browserType, bool useHttpClient)
        {
            Contexts.Add(new BrowserTestContext(
                nameof(ScrumMasterTest),
                nameof(Shows_Error_When_Joining_Not_Existing_Team),
                browserType,
                serverSide,
                useHttpClient));

            await StartServer();
            StartClients();

            string team = "My team";
            string member = "Test Member";

            await ClientTest.OpenApplication();
            TakeScreenshot("01-Loading");
            ClientTest.AssertIndexPage();
            TakeScreenshot("02-Index");
            ClientTest.FillJoinTeamForm(team, member);
            TakeScreenshot("03-JoinTeamForm");
            ClientTest.SubmitJoinTeamForm();
            await Task.Delay(500);
            ClientTest.AssertIndexPage();
            TakeScreenshot("04-Error");
            ClientTest.AssertMessageBox("Scrum Team \"My team\" does not exist. (Parameter 'teamName')");
        }
    }
}


text:
package reporter

import (
	"context"
	"fmt"
	"log"

	v1alpha1 "github.com/kubernetes-sigs/wg-policy-prototypes/policy-report/api/v1alpha1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/client-go/rest"
	"k8s.io/kubectl/pkg/scheme"
)

// PolicyReporter creates the policyreport object
type PolicyReporter struct {
	policy        v1alpha1.PolicyReport
	testSummaries []*TestSummary
}

// NewPolicyReporter returns the pointer of PolicyReporter
func NewPolicyReporter() *PolicyReporter {
	policyName := "policyreport-" + string(uuid.NewUUID())[0:4]
	return &PolicyReporter{
		policy: v1alpha1.PolicyReport{
			TypeMeta: metav1.TypeMeta{
				Kind:       "PolicyReport",
				APIVersion: "policy.kubernetes.io/v1alpha1",
			},
			ObjectMeta: metav1.ObjectMeta{
				Name: policyName,
			},
		},
	}
}

// SuiteWillBegin prints banner and total benchmarks to be run
func (p *PolicyReporter) SuiteWillBegin(suiteSummary *SuiteSummary) {

}

// TestWillRun prints each test status
func (p *PolicyReporter) TestWillRun(testSummary *TestSummary) {
	var status v1alpha1.PolicyStatus
	if testSummary.Validation && testSummary.Test {
		status = "Pass"
	} else if testSummary.Validation && !testSummary.Test {
		status = "Fail"
	} else if !testSummary.Validation {
		status = "Error"
	} else {
		status = "Skip"
	}
	p.policy.Results = append(p.policy.Results, &v1alpha1.PolicyReportResult{
		Policy: testSummary.Benchmark.Title,
		Status: status,
		Scored: true,
	})
}

// SuiteDidEnd prints end result summary of benchmark suite
func (p *PolicyReporter) SuiteDidEnd(suiteSummary *SuiteSummary) {
	p.policy.Summary = v1alpha1.PolicyReportSummary{
		Pass:  suiteSummary.NumberOfPassedTests,
		Fail:  suiteSummary.NumberOfFailedTests,
		Skip:  suiteSummary.NumberOfSkippedTests,
		Error: suiteSummary.NumberOfFailedValidations,
	}

	CreatePolicy(suiteSummary.Namespace, p.policy)
}

// CreatePolicy creates the policy object
func CreatePolicy(namespace string, policy v1alpha1.PolicyReport) {
	kubecfgFlags := genericclioptions.NewConfigFlags(false)

	config, err := kubecfgFlags.ToRESTConfig()
	if err != nil {
		errExit("", err)
	}

	v1alpha1.AddToScheme(scheme.Scheme)

	crdConfig := *config
	crdConfig.ContentConfig.GroupVersion = &v1alpha1.GroupVersion
	crdConfig.APIPath = "/apis"
	crdConfig.NegotiatedSerializer = serializer.NewCodecFactory(scheme.Scheme)
	crdConfig.UserAgent = rest.DefaultKubernetesUserAgent()

	c, err := rest.RESTClientFor(&crdConfig)
	if err != nil {
		panic(err)
	}

	result := v1alpha1.PolicyReport{}
	err = c.
		Post().
		Namespace(namespace).
		Resource("policyreports").
		Body(&policy).
		Do(context.TODO()).
		Into(&result)
	if err != nil {
		fmt.Println(err.Error(), "\nTry installing the policyreport CRD following the link https://github.com/kubernetes-sigs/wg-policy-prototypes/tree/master/policy-report#installing")
	} else {
		writer.Println(0, writer.Colorize(boldStyle, "Policy Reporter"))
		writer.PrintBanner(writer.Colorize(defaultStyle, "%s is Created in %s namespace.", result.ObjectMeta.Name, namespace), "=")
	}
}

func errExit(msg string, err error) {
	if err != nil {
		log.Fatalf("%s: %#v", msg, err)
	}
}


text:
<launch>
	<param name="/use_sim_time" value="true"/>
  <node pkg="stage_ros" type="stageros" name="world" args="$(find hnt_launch)/2d_sim/b3ia.world"/>

	<!--<node pkg="rviz" type="rviz" name="rviz" args="-d $(find hnt_launch)/2d_sim/2d.vcg" respawn="true"/>-->

	<!--<include file="$(find p2os_urdf)/launch/pioneer3dx_urdf.launch"/>-->
  <node pkg="point_map" type="point_map" name="point_map" args="$(find hnt_launch)/2d_sim/simple_room.yaml"/>

  <!--<group ns="b3ia">
    <node pkg="stage_adapt" type="stage-adapt" name="stage_adapter">
      <remap from="people_tracker_measurements" to="/people_tracker_measurements"/>

      <!- -<remap to="/b3ia/des_vel" from="/robot/cmd_vel"/>- ->
    </node>
    <node pkg="obstacle_avoidance" type="obs" name="obs" output="screen"/>
  </group>-->

</launch>