text:
class AliAnalysisTaskStrVsMult_BumpStudies : public AliAnalysisTaskSE {
  public:
    AliAnalysisTaskStrVsMult_BumpStudies();
    AliAnalysisTaskStrVsMult_BumpStudies(const char *name, TString lExtraOptions = "");
    virtual ~AliAnalysisTaskStrVsMult_BumpStudies();

    // enum and names.
    enum cutnumb_V0{kV0_DcaV0Daught, kV0_DcaPosToPV, kV0_DcaNegToPV, kV0_V0CosPA, kV0_V0Rad, kV0_y, kV0_etaDaugh, kV0_LeastCRaws, kV0_LeastCRawsOvF, kV0_NSigPID, kV0_PropLifetK0s, kV0_PropLifetLam, kV0_TOFBunchCrossing, kV0cutsnum};
    enum cutnumb_Casc{kCasc_DcaCascDaught, kCasc_CascCosPA, kCasc_CascRad, kCasc_NSigPID, kCasc_LeastCRaws, kCasc_LeastCRawsOvF, kCasc_InvMassLam, kCasc_DcaV0Daught, kCasc_V0CosPA, kCasc_DcaV0ToPV, kCasc_DcaBachToPV, kCasc_TOFBunchCrossing, kCasc_y, kCasc_etaDaugh, kCasc_PropLifetXi, kCasc_PropLifetOm, kCasc_V0Rad, kCasc_DcaMesToPV, kCasc_DcaBarToPV, kCasc_BacBarCosPA, kCasccutsnum}; // kCasc_etaPos, kCasc_etaNeg, kCasc_etaBac, kCasc_kinkidx,
    enum particles{kK0s, kLam, kXi, kOm, knumpart};
    enum signedparticles{kk0s, klam, kalam, kxip, kxim, komp, komm, ksignednumpart};

    virtual void UserCreateOutputObjects();
    virtual void UserExec(Option_t *option);
    virtual void Terminate(Option_t *);

    //cut values setter
    void SetDefOnly(bool);
    void SetCutVal(bool, bool, int, double);

    //binning setters
    void SetCentbinning(int, int, double*);
    void SetMassbinning(int, int, double, double);
    void SetPtbinning(int, int, double*);

    //set and get which particle specie are analysed
    void SetParticleAnalysisStatus(bool, bool, bool, bool);
    bool GetParticleAnalysisStatus(int);

    //MC-related setters and getters
    void SetIsMC(bool IsMC){fisMC = IsMC;};
    void SetIsMCantiassoc(bool IsMCantiassoc){fisMCantiassoc = IsMCantiassoc;};

  private:
    THistManager* fHistos_eve;                                //!
    THistManager* fHistos_K0S;                                //!
    THistManager* fHistos_Lam;                                //!
    THistManager* fHistos_ALam;                               //!
    THistManager* fHistos_XiMin;                              //!
    THistManager* fHistos_XiPlu;                              //!
    THistManager* fHistos_OmMin;                              //!
    THistManager* fHistos_OmPlu;                              //!

    //objects retreived from input handler
    AliPIDResponse *fPIDResponse;                             //!
    UInt_t fTriggerMask;                                      //!

    //MC-realted variables
    bool fisMC;                                               //
    bool fisMCantiassoc;                                          //

    //Default cut configuration
    bool fDefOnly;                                            //
    double fV0_Cuts[kV0cutsnum];                              //
    double fCasc_Cuts[kCasccutsnum];                          //

    //particles to be analysed
    bool fParticleAnalysisStatus[ksignednumpart];             //

    //variables for V0 analysis
    double fV0_DcaV0Daught;                                   //!
    double fV0_DcaPosToPV;                                    //!
    double fV0_DcaNegToPV;                                    //!
    double fV0_V0CosPA;                                       //!
    double fV0_V0Rad;                                         //!
    double fV0_Pt;                                            //!
    double fV0_yK0S;                                          //!
    double fV0_yLam;                                          //!
    double fV0_etaPos;                                        //!
    double fV0_etaNeg;                                        //!
    double fV0_InvMassK0s;                                    //!
    double fV0_InvMassLam;                                    //!
    double fV0_InvMassALam;                                   //!
    double fV0_LeastCRaws;                                    //!
    double fV0_LeastCRawsOvF;                                 //!
    double fV0_NSigPosProton;                                 //!
    double fV0_NSigPosPion;                                   //!
    double fV0_NSigNegProton;                                 //!
    double fV0_NSigNegPion;                                   //!
    double fV0_DistOverTotP;                                  //!
    double fV0_NegTOFBunchCrossing;                           //!
    double fV0_PosTOFBunchCrossing;                           //!
    ULong64_t fV0_NegTrackStatus;                             //!
    ULong64_t fV0_PosTrackStatus;                             //!
    double fV0_kinkidx;                                       //!

    //variables for Cascade analysis
    double fCasc_DcaCascDaught;                               //!
    double fCasc_CascCosPA;                                   //!
    double fCasc_CascRad;                                     //!
    double fCasc_etaPos;                                      //!
    double fCasc_etaNeg;                                      //!
    double fCasc_etaBac;                                      //!
    double fCasc_kinkidx;                                     //!
    double fCasc_NSigPosProton;                               //!
    double fCasc_NSigPosPion;                                 //!
    double fCasc_NSigNegProton;                               //!
    double fCasc_NSigNegPion;                                 //!
    double fCasc_NSigBacPion;                                 //!
    double fCasc_NSigBacKaon;                                 //!
    double fCasc_LeastCRaws;                                  //!
    double fCasc_LeastCRawsOvF;                               //!
    double fCasc_InvMassLam;                                  //!
    double fCasc_DcaV0Daught;                                 //!
    double fCasc_V0CosPA;                                     //!
    double fCasc_DcaV0ToPV;                                   //!
    double fCasc_DcaBachToPV;                                 //!
    double fCasc_PosTOFBunchCrossing;                         //!
    double fCasc_NegTOFBunchCrossing;                         //!
    double fCasc_BacTOFBunchCrossing;                         //!
    double fCasc_yXi;                                         //!
    double fCasc_yOm;                                         //!
    int fCasc_charge;                                         //!
    double fCasc_Pt;                                          //!
    double fCasc_DistOverTotP;                                //!
    double fCasc_InvMassXiMin;                                //!
    double fCasc_InvMassXiPlu;                                //!
    double fCasc_InvMassOmMin;                                //!
    double fCasc_InvMassOmPlu;                                //!
    double fCasc_V0Rad;                                       //!
    double fCasc_DcaPosToPV;                                  //!
    double fCasc_DcaNegToPV;                                  //!
    ULong64_t fCasc_NegTrackStatus;                           //!
    ULong64_t fCasc_PosTrackStatus;                           //!
    ULong64_t fCasc_BacTrackStatus;                           //!
    double fCasc_BacBarCosPA;                                   //!

    //cut values to be set
    double cutval_V0[kV0cutsnum];                             //
    int nvarcut_V0[kV0cutsnum];                               //
    double varlowcut_V0[kV0cutsnum];                          //
    double varhighcut_V0[kV0cutsnum];                         //
    double cutval_Casc[kCasccutsnum];                         //
    int nvarcut_Casc[kCasccutsnum];                           //
    double varlowcut_Casc[kCasccutsnum];                      //
    double varhighcut_Casc[kCasccutsnum];                     //

    //variables to handle binning
    int fncentbins[knumpart];                                 //
    double fcentbinning[knumpart][50];                        //
    int fnmassbins[knumpart];                                 //
    double fmassbinning[knumpart][1000];                      //
    int fnptbins[knumpart];                                   //
    double fptbinning[knumpart][600];                         //

    //functions to allow flushing part of code out of UserExec
    bool ApplyCuts(int);
    void DataPosting();
    void FillHistCutVariations(bool, double, bool, bool*, double);
    //functions to allow the correct streaming of the cut variation
    void SetDefCutVals();
    void SetCutVariation(bool, int, int, double, double);
    void SetDefCutVariations();

    AliAnalysisTaskStrVsMult_BumpStudies(const AliAnalysisTaskStrVsMult_BumpStudies&);            // not implemented
    AliAnalysisTaskStrVsMult_BumpStudies& operator=(const AliAnalysisTaskStrVsMult_BumpStudies&); // not implemented

    ClassDef(AliAnalysisTaskStrVsMult_BumpStudies, 1);
    //version 4: introduced MC handeling
};

#endif

redpajama_set_name: RedPajamaGithub


text:
module Azure::Cosmosdb::Mgmt::V2020_06_01_preview
  module Models
    #
    # An Azure Cosmos DB SQL Role Definition.
    #
    class SqlRoleDefinitionGetResults < ARMProxyResource

      include MsRestAzure

      # @return [String] A user-friendly name for the Role Definition. Must be
      # unique for the database account.
      attr_accessor :role_name

      # @return [RoleDefinitionType] Indicates whether the Role Definition was
      # built-in or user created. Possible values include: 'BuiltInRole',
      # 'CustomRole'
      attr_accessor :sql_role_definition_get_results_type

      # @return [Array<String>] A set of fully qualified Scopes at or below
      # which Role Assignments may be created using this Role Definition. This
      # will allow application of this Role Definition on the entire database
      # account or any underlying Database / Collection. Must have at least one
      # element. Scopes higher than Database account are not enforceable as
      # assignable Scopes. Note that resources referenced in assignable Scopes
      # need not exist.
      attr_accessor :assignable_scopes

      # @return [Array<Permission>] The set of operations allowed through this
      # Role Definition.
      attr_accessor :permissions

      #
      # Mapper for SqlRoleDefinitionGetResults class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'SqlRoleDefinitionGetResults',
          type: {
            name: 'Composite',
            class_name: 'SqlRoleDefinitionGetResults',
            model_properties: {
              id: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              },
              name: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              type: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              },
              role_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.roleName',
                type: {
                  name: 'String'
                }
              },
              sql_role_definition_get_results_type: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.type',
                type: {
                  name: 'Enum',
                  module: 'RoleDefinitionType'
                }
              },
              assignable_scopes: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.assignableScopes',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              },
              permissions: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.permissions',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'PermissionElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'Permission'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//namespace Cosmos.Hardware2.Audio.Devices.Generic.Managers
//{
//    public class UARTManager
//    {
//        //private Cosmos.Hardware2.Audio.Devices.Generic.Components.UARTEntity uartEntity;
//    }
//}


text:
package org.knowhowlab.osgi.networkadapter.utils;

import org.junit.Assert;
import org.junit.Test;

import java.util.Optional;

import static org.hamcrest.CoreMatchers.is;

/**
 * @author dpishchukhin
 */
public class FunctionsTest {
    @Test
    public void ofThrowable_supplier_noError() throws Exception {
        Assert.assertThat(Functions.ofThrowable(() -> "test"), is(Optional.of("test")));
    }

    @Test
    public void ofThrowable_supplier_withError() throws Exception {
        Assert.assertThat(Functions.ofThrowable(() -> {
            throw new Exception("Error");
        }), is(Optional.empty()));
    }

    @Test
    public void ofThrowable_function_noError() throws Exception {
        Assert.assertThat(Functions.ofThrowable(String::valueOf, () -> true), is(Optional.of("true")));
    }

    @Test
    public void ofThrowable_function_withError() throws Exception {
        Assert.assertThat(Functions.ofThrowable(t -> {
            throw new Exception("Error");
        }, () -> true), is(Optional.empty()));
    }

    @Test
    public void cast_noError() throws Exception {
        Assert.assertThat(Functions.cast(Boolean.class::cast, true), is(Optional.of(true)));
        Assert.assertThat(Functions.cast(String.class::cast, "test"), is(Optional.of("test")));
        //noinspection OptionalGetWithoutIsPresent
        Assert.assertArrayEquals(Functions.cast(byte[].class::cast, new byte[] {1, 2}).get(),
            new byte[] {1, 2});
    }

    @Test
    public void cast_withError() throws Exception {
        Assert.assertThat(Functions.cast(Boolean.class::cast, 1), is(Optional.empty()));
    }
}


text:
/*! HTML5 Shiv vpre3.6 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */
;(function(window, document) {

  /** Preset options */
  var options = window.html5 || {};

  /** Used to skip problem elements */
  var reSkip = /^<|^(?:button|form|map|select|textarea|object|iframe|option|optgroup)$/i;

  /** Not all elements can be cloned in IE (this list can be shortend) **/
  var saveClones = /^<|^(?:a|b|button|code|div|fieldset|form|h1|h2|h3|h4|h5|h6|i|iframe|img|input|label|li|link|ol|option|p|param|q|script|select|span|strong|style|table|tbody|td|textarea|tfoot|th|thead|tr|ul)$/i;

  /** Detect whether the browser supports default html5 styles */
  var supportsHtml5Styles;

  /** Detect whether the browser supports unknown elements */
  var supportsUnknownElements;

  (function() {
    var a = document.createElement('a');

    a.innerHTML = '<xyz></xyz>';

    //if the hidden property is implemented we can assume, that the browser supports HTML5 Styles | this fails in Chrome 8
    supportsHtml5Styles = ('hidden' in a);
    //if we are part of Modernizr, we do an additional test to solve the Chrome 8 fail
    if(supportsHtml5Styles && typeof injectElementWithStyles == 'function'){
        injectElementWithStyles('#modernizr{}', function(node){
            node.hidden = true;
            supportsHtml5Styles = (window.getComputedStyle ?
                  getComputedStyle(node, null) :
                  node.currentStyle).display == 'none';
        });
    }

    supportsUnknownElements = a.childNodes.length == 1 || (function() {
      // assign a false positive if unable to shiv
      try {
        (document.createElement)('a');
      } catch(e) {
        return true;
      }
      var frag = document.createDocumentFragment();
      return (
        typeof frag.cloneNode == 'undefined' ||
        typeof frag.createDocumentFragment == 'undefined' ||
        typeof frag.createElement == 'undefined'
      );
    }());

  }());

  /*--------------------------------------------------------------------------*/

  /**
   * Creates a style sheet with the given CSS text and adds it to the document.
   * @private
   * @param {Document} ownerDocument The document.
   * @param {String} cssText The CSS text.
   * @returns {StyleSheet} The style element.
   */
  function addStyleSheet(ownerDocument, cssText) {
    var p = ownerDocument.createElement('p'),
        parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;

    p.innerHTML = 'x<style>' + cssText + '</style>';
    return parent.insertBefore(p.lastChild, parent.firstChild);
  }

  /**
   * Returns the value of `html5.elements` as an array.
   * @private
   * @returns {Array} An array of shived element node names.
   */
  function getElements() {
    var elements = html5.elements;
    return typeof elements == 'string' ? elements.split(' ') : elements;
  }

  /**
   * Shivs the `createElement` and `createDocumentFragment` methods of the document.
   * @private
   * @param {Document|DocumentFragment} ownerDocument The document.
   */
  function shivMethods(ownerDocument) {
    var cache = {},
        docCreateElement = ownerDocument.createElement,
        docCreateFragment = ownerDocument.createDocumentFragment,
        frag = docCreateFragment();

    ownerDocument.createElement = function(nodeName) {
      //abort shiv
      if(!html5.shivMethods){
          return docCreateElement(nodeName);
      }

      var node;

      if(cache[nodeName]){
          node = cache[nodeName].cloneNode();
      } else if(saveClones.test(nodeName)){
           node = (cache[nodeName] = docCreateElement(nodeName)).cloneNode();
      } else {
          node = docCreateElement(nodeName);
      }

      // Avoid adding some elements to fragments in IE < 9 because
      // * Attributes like `name` or `type` cannot be set/changed once an element
      //   is inserted into a document/fragment
      // * Link elements with `src` attributes that are inaccessible, as with
      //   a 403 response, will cause the tab/window to crash
      // * Script elements appended to fragments will execute when their `src`
      //   or `text` property is set

      return node.canHaveChildren && !reSkip.test(nodeName) ? frag.appendChild(node) : node;
    };

    ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
      'var n=f.cloneNode(),c=n.createElement;' +
      'h.shivMethods&&(' +
        // unroll the `createElement` calls
        getElements().join().replace(/\w+/g, function(nodeName) {
          docCreateElement(nodeName);
          frag.createElement(nodeName);
          return 'c("' + nodeName + '")';
        }) +
      ');return n}'
    )(html5, frag);
  }

  /*--------------------------------------------------------------------------*/

  /**
   * Shivs the given document.
   * @memberOf html5
   * @param {Document} ownerDocument The document to shiv.
   * @returns {Document} The shived document.
   */
  function shivDocument(ownerDocument) {
    var shived;
    if (ownerDocument.documentShived) {
      return ownerDocument;
    }
    if (html5.shivCSS && !supportsHtml5Styles) {
      shived = !!addStyleSheet(ownerDocument,
        // corrects block display not defined in IE6/7/8/9
        'article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}' +
        // corrects audio display not defined in IE6/7/8/9
        'audio{display:none}' +
        // corrects canvas and video display not defined in IE6/7/8/9
        'canvas,video{display:inline-block;*display:inline;*zoom:1}' +
        // corrects 'hidden' attribute and audio[controls] display not present in IE7/8/9
        '[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}' +
        // adds styling not present in IE6/7/8/9
        'mark{background:#FF0;color:#000}'
      );
    }
    if (!supportsUnknownElements) {
      shived = !shivMethods(ownerDocument);
    }
    if (shived) {
      ownerDocument.documentShived = shived;
    }
    return ownerDocument;
  }

  /*--------------------------------------------------------------------------*/

  /**
   * The `html5` object is exposed so that more elements can be shived and
   * existing shiving can be detected on iframes.
   * @type Object
   * @example
   *
   * // options can be changed before the script is included
   * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
   */
  var html5 = {

    /**
     * An array or space separated string of node names of the elements to shiv.
     * @memberOf html5
     * @type Array|String
     */
    'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video',

    /**
     * A flag to indicate that the HTML5 style sheet should be inserted.
     * @memberOf html5
     * @type Boolean
     */
    'shivCSS': !(options.shivCSS === false),

    /**
     * A flag to indicate that the document's `createElement` and `createDocumentFragment`
     * methods should be overwritten.
     * @memberOf html5
     * @type Boolean
     */
    'shivMethods': !(options.shivMethods === false),

    /**
     * A string to describe the type of `html5` object ("default" or "default print").
     * @memberOf html5
     * @type String
     */
    'type': 'default',

    // shivs the document according to the specified `html5` object options
    'shivDocument': shivDocument
  };

  /*--------------------------------------------------------------------------*/

  // expose html5
  window.html5 = html5;

  // shiv the document
  shivDocument(document);

  /*------------------------------- Print Shiv -------------------------------*/

  /** Used to filter media types */
  var reMedia = /^$|\b(?:all|print)\b/;

  /** Used to namespace printable elements */
  var shivNamespace = 'html5shiv';

  /** Detect whether the browser supports shivable style sheets */
  var supportsShivableSheets = !supportsUnknownElements && (function() {
    // assign a false negative if unable to shiv
    var docEl = document.documentElement;
    return !(
      typeof document.namespaces == 'undefined' ||
      typeof document.parentWindow == 'undefined' ||
      typeof docEl.applyElement == 'undefined' ||
      typeof docEl.removeNode == 'undefined' ||
      typeof window.attachEvent == 'undefined'
    );
  }());

  /*--------------------------------------------------------------------------*/

  /**
   * Wraps all HTML5 elements in the given document with printable elements.
   * (eg. the "header" element is wrapped with the "html5shiv:header" element)
   * @private
   * @param {Document} ownerDocument The document.
   * @returns {Array} An array wrappers added.
   */
  function addWrappers(ownerDocument) {
    var node,
        nodes = ownerDocument.getElementsByTagName('*'),
        index = nodes.length,
        reElements = RegExp('^(?:' + getElements().join('|') + ')$', 'i'),
        result = [];

    while (index--) {
      node = nodes[index];
      if (reElements.test(node.nodeName)) {
        result.push(node.applyElement(createWrapper(node)));
      }
    }
    return result;
  }

  /**
   * Creates a printable wrapper for the given element.
   * @private
   * @param {Element} element The element.
   * @returns {Element} The wrapper.
   */
  function createWrapper(element) {
    var node,
        nodes = element.attributes,
        index = nodes.length,
        wrapper = element.ownerDocument.createElement(shivNamespace + ':' + element.nodeName);

    // copy element attributes to the wrapper
    while (index--) {
      node = nodes[index];
      node.specified && wrapper.setAttribute(node.nodeName, node.nodeValue);
    }
    // copy element styles to the wrapper
    wrapper.style.cssText = element.style.cssText;
    return wrapper;
  }

  /**
   * Shivs the given CSS text.
   * (eg. header{} becomes html5shiv\:header{})
   * @private
   * @param {String} cssText The CSS text to shiv.
   * @returns {String} The shived CSS text.
   */
  function shivCssText(cssText) {
    var pair,
        parts = cssText.split('{'),
        index = parts.length,
        reElements = RegExp('(^|[\\s,>+~])(' + getElements().join('|') + ')(?=[[\\s,>+~#.:]|$)', 'gi'),
        replacement = '$1' + shivNamespace + '\\:$2';

    while (index--) {
      pair = parts[index] = parts[index].split('}');
      pair[pair.length - 1] = pair[pair.length - 1].replace(reElements, replacement);
      parts[index] = pair.join('}');
    }
    return parts.join('{');
  }

  /**
   * Removes the given wrappers, leaving the original elements.
   * @private
   * @params {Array} wrappers An array of printable wrappers.
   */
  function removeWrappers(wrappers) {
    var index = wrappers.length;
    while (index--) {
      wrappers[index].removeNode();
    }
  }

  /*--------------------------------------------------------------------------*/

  /**
   * Shivs the given document for print.
   * @memberOf html5
   * @param {Document} ownerDocument The document to shiv.
   * @returns {Document} The shived document.
   */
  function shivPrint(ownerDocument) {
    var shivedSheet,
        wrappers,
        namespaces = ownerDocument.namespaces,
        ownerWindow = ownerDocument.parentWindow;

    if (!supportsShivableSheets || ownerDocument.printShived) {
      return ownerDocument;
    }
    if (typeof namespaces[shivNamespace] == 'undefined') {
      namespaces.add(shivNamespace);
    }

    ownerWindow.attachEvent('onbeforeprint', function() {
      var imports,
          length,
          sheet,
          collection = ownerDocument.styleSheets,
          cssText = [],
          index = collection.length,
          sheets = Array(index);

      // convert styleSheets collection to an array
      while (index--) {
        sheets[index] = collection[index];
      }
      // concat all style sheet CSS text
      while ((sheet = sheets.pop())) {
        // IE does not enforce a same origin policy for external style sheets...
        // but has trouble with some dynamically created stylesheets
        if (!sheet.disabled && reMedia.test(sheet.media)) {

          try {
            imports = sheet.imports;
            length = imports.length;
          } catch(er){
            length = 0;
          }

          for (index = 0; index < length; index++) {
            sheets.push(imports[index]);
          }

          try {
            cssText.push(sheet.cssText);
          } catch(er){}
        }
      }
      // wrap all HTML5 elements with printable elements and add the shived style sheet
      cssText = shivCssText(cssText.reverse().join(''));
      wrappers = addWrappers(ownerDocument);
      shivedSheet = addStyleSheet(ownerDocument, cssText);
    });

    ownerWindow.attachEvent('onafterprint', function() {
      // remove wrappers, leaving the original elements, and remove the shived style sheet
      removeWrappers(wrappers);
      shivedSheet.removeNode(true);
    });

    ownerDocument.printShived = true;
    return ownerDocument;
  }

  /*--------------------------------------------------------------------------*/

  // expose API
  html5.type += ' print';
  html5.shivPrint = shivPrint;

  // shiv for print
  shivPrint(document);

}(this, document));


text:
// USER STORIES

//SUM
/*
Pseudocode:
define a function that takes an array as an argument
declare a variable sum and set it to 0.
Iterate through the array
WHILE
  add the value of the current index to the sum.
END
return the sum
*/

// As a user, I want to be able to sum parts, or the whole of an array

// As a user I want to be able to sum an array that has an odd length

// As a user I want to be able to sum an array that has an even length

// Initial Code:
/*
function sum(array) {
  var sum = 0;
  for (var i=0; i < array.length; i++) {
    sum += array[i];
  }
  return sum
}
*/
// Refactored Code:
function sum(array) {
  var sum = 0;
  for (var i = 0; i < array.length; i++) {
    sum += array[i];
  }
  return sum
}

//AVERAGE
/*
Pseudocode:
define a function that takes an array as an argument
declare a variable sum and set it to 0
Iterate through the array
WHILE
  add the value of the current index to the sum.
END
return the sum divided by the length of the array
*/

// As a user, I want to be able to get the average of all the elements in an array

// As a user I want to be able to get the average of an array that has an odd length

// As a user I want to be able to get the average of an array that has an even length
// Initial Code:
/*
function average(array) {
  var sum_of_array = sum(array);
  return sum_of_array/array.length;
}
*/
// Refactored Code:
function mean(array) {
  return sum(array) / array.length;
}

//MEDIAN

/*
Pseudocode:
define a function that takes an array as an argument
sort the array
declare a variable at the middle index and floor it
IF odd length
  return the array at the middle index
ELSE
  return the array at the middle index plus the array at the middle index minus 1 and divide that by 2
END
*/

// As a user, I want to be able to find the median of all the elements in an array

// As a user I want to be able to find the median of an array that has an odd length

// As a user I want to be able to find the median of an array that has an even length
// Initial Code
/*
function median(array) {
  var len = array.length;
  array.sort();
  if (len % 2 == 0) {
    console.log(array);
    return average([array[len/2-1], array[len/2]]);
  } else {
    return array[Math.floor(array.length/2)];
  }
}
*/
// Refactored Code

function median(array) {
  var len = array.length;
  array.sort();
  if (len % 2 == 0) {
    return mean([array[len / 2 - 1], array[len / 2]]);
  } else {
    return array[Math.floor(array.length / 2)];
  }
}

//__________________________________________
// Tests:  Do not alter code below this line.

oddLengthArray  = [1, 2, 3, 4, 5, 5, 7]
evenLengthArray = [4, 4, 5, 5, 6, 6, 6, 7]

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

// tests for sum
assert(
  (sum instanceof Function),
  "sum should be a Function.",
  "1. "
)

assert(
  sum(oddLengthArray) === 27,
  "sum should return the sum of all elements in an array with an odd length.",
  "2. "
)

assert(
  sum(evenLengthArray) === 43,
  "sum should return the sum of all elements in an array with an even length.",
  "3. "
)

// tests for mean
assert(
  (mean instanceof Function),
  "mean should be a Function.",
  "4. "
)

assert(
  mean(oddLengthArray) === 3.857142857142857,
  "mean should return the average of all elements in an array with an odd length.",
  "5. "
)

assert(
  mean(evenLengthArray) === 5.375,
  "mean should return the average of all elements in an array with an even length.",
  "6. "
)

// tests for median
assert(
  (median instanceof Function),
  "median should be a Function.",
  "7. "
)

assert(
  median(oddLengthArray) === 4,
  "median should return the median value of all elements in an array with an odd length.",
  "8. "
)

assert(
  median(evenLengthArray) === 5.5,
  "median should return the median value of all elements in an array with an even length.",
  "9. "
)


text:
<?php

/**
 * @see Zend_Filter_Interface
 */
require_once 'Zend/Filter/Interface.php';

/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_PregReplace implements Zend_Filter_Interface
{
    /**
     * Pattern to match
     * @var mixed
     */
    protected $_matchPattern = null;

    /**
     * Replacement pattern
     * @var mixed
     */
    protected $_replacement = '';

    /**
     * Is unicode enabled?
     *
     * @var bool
     */
    static protected $_unicodeSupportEnabled = null;

    /**
     * Is Unicode Support Enabled Utility function
     *
     * @return bool
     */
    static public function isUnicodeSupportEnabled()
    {
        if (self::$_unicodeSupportEnabled === null) {
            self::_determineUnicodeSupport();
        }

        return self::$_unicodeSupportEnabled;
    }

    /**
     * Method to cache the regex needed to determine if unicode support is available
     *
     * @return bool
     */
    static protected function _determineUnicodeSupport()
    {
        self::$_unicodeSupportEnabled = (@preg_match('/\pL/u', 'a')) ? true : false;
    }

    /**
     * Constructor
     *
     * @param  string $match
     * @param  string $replace
     * @return void
     */
    public function __construct($matchPattern = null, $replacement = null)
    {
        if ($matchPattern) {
            $this->setMatchPattern($matchPattern);
        }

        if ($replacement) {
            $this->setReplacement($replacement);
        }
    }

    /**
     * Set the match pattern for the regex being called within filter()
     *
     * @param mixed $match - same as the first argument of preg_replace
     * @return Zend_Filter_PregReplace
     */
    public function setMatchPattern($match)
    {
        $this->_matchPattern = $match;
        return $this;
    }

    /**
     * Get currently set match pattern
     *
     * @return string
     */
    public function getMatchPattern()
    {
        return $this->_matchPattern;
    }

    /**
     * Set the Replacement pattern/string for the preg_replace called in filter
     *
     * @param mixed $replacement - same as the second argument of preg_replace
     * @return Zend_Filter_PregReplace
     */
    public function setReplacement($replacement)
    {
        $this->_replacement = $replacement;
        return $this;
    }

    /**
     * Get currently set replacement value
     *
     * @return string
     */
    public function getReplacement()
    {
        return $this->_replacement;
    }

    /**
     * Perform regexp replacement as filter
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        if ($this->_matchPattern == null) {
            require_once 'Zend/Filter/Exception.php';
            throw new Zend_Filter_Exception(get_class($this) . ' does not have a valid MatchPattern set.');
        }

        return preg_replace($this->_matchPattern, $this->_replacement, $value);
    }

}


text:
package org.fortiss.smg.actuatorclient.sunny.impl.jsonrpc;

public class JsonRPCCommunicator {

}


text:
// Copyright 2017 The Nomulus Authors. 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.

package google.registry.flows.domain;

import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatabaseHelper.assertBillingEvents;
import static google.registry.testing.DatabaseHelper.deleteTestDomain;
import static google.registry.testing.DatabaseHelper.getPollMessages;
import static google.registry.testing.DatabaseHelper.persistResource;
import static google.registry.testing.DomainSubject.assertAboutDomains;
import static google.registry.testing.EppExceptionSubject.assertAboutEppExceptions;
import static org.junit.jupiter.api.Assertions.assertThrows;

import google.registry.flows.EppException;
import google.registry.flows.FlowUtils.NotLoggedInException;
import google.registry.flows.ResourceFlowUtils.BadAuthInfoForResourceException;
import google.registry.flows.ResourceFlowUtils.ResourceDoesNotExistException;
import google.registry.flows.exceptions.NoTransferHistoryToQueryException;
import google.registry.flows.exceptions.NotAuthorizedToViewTransferException;
import google.registry.model.contact.ContactAuthInfo;
import google.registry.model.domain.Domain;
import google.registry.model.domain.DomainAuthInfo;
import google.registry.model.eppcommon.AuthInfo.PasswordAuth;
import google.registry.model.reporting.HistoryEntry;
import google.registry.model.transfer.TransferStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/** Unit tests for {@link DomainTransferQueryFlow}. */
class DomainTransferQueryFlowTest
    extends DomainTransferFlowTestCase<DomainTransferQueryFlow, Domain> {

  @BeforeEach
  void beforeEach() {
    setEppInput("domain_transfer_query.xml");
    setRegistrarIdForFlow("NewRegistrar");
    setupDomainWithPendingTransfer("example", "tld");
  }

  private void doSuccessfulTest(
      String commandFilename, String expectedXmlFilename, int numPollMessages) throws Exception {
    setEppInput(commandFilename);
    // Replace the ROID in the xml file with the one generated in our test.
    eppLoader.replaceAll("JD1234-REP", contact.getRepoId());
    // Setup done; run the test.
    assertTransactionalFlow(false);
    runFlowAssertResponse(loadFile(expectedXmlFilename));
    assertAboutDomains()
        .that(domain)
        .hasOneHistoryEntryEachOfTypes(
            HistoryEntry.Type.DOMAIN_CREATE, HistoryEntry.Type.DOMAIN_TRANSFER_REQUEST);
    assertBillingEvents(
        getBillingEventForImplicitTransfer(),
        getGainingClientAutorenewEvent(),
        getLosingClientAutorenewEvent());
    // Look in the future and make sure the poll messages for implicit ack are there.
    assertThat(getPollMessages("NewRegistrar", clock.nowUtc().plusYears(1)))
        .hasSize(numPollMessages);
    assertThat(getPollMessages("TheRegistrar", clock.nowUtc().plusYears(1))).hasSize(1);
  }

  private void doFailingTest(String commandFilename) throws Exception {
    setEppInput(commandFilename);
    // Replace the ROID in the xml file with the one generated in our test.
    eppLoader.replaceAll("JD1234-REP", contact.getRepoId());
    // Setup done; run the test.
    assertTransactionalFlow(false);
    runFlow();
  }

  @Test
  void testNotLoggedIn() {
    sessionMetadata.setRegistrarId(null);
    EppException thrown = assertThrows(NotLoggedInException.class, this::runFlow);
    assertAboutEppExceptions().that(thrown).marshalsToXml();
  }

  @Test
  void testSuccess() throws Exception {
    doSuccessfulTest("domain_transfer_query.xml", "domain_transfer_query_response.xml", 1);
  }

  @Test
  void testSuccess_sponsoringClient() throws Exception {
    setRegistrarIdForFlow("TheRegistrar");
    doSuccessfulTest("domain_transfer_query.xml", "domain_transfer_query_response.xml", 1);
  }

  @Test
  void testSuccess_domainAuthInfo() throws Exception {
    setRegistrarIdForFlow("ClientZ");
    doSuccessfulTest(
        "domain_transfer_query_domain_authinfo.xml", "domain_transfer_query_response.xml", 1);
  }

  @Test
  void testSuccess_contactAuthInfo() throws Exception {
    setRegistrarIdForFlow("ClientZ");
    doSuccessfulTest(
        "domain_transfer_query_contact_authinfo.xml", "domain_transfer_query_response.xml", 1);
  }

  @Test
  void testSuccess_clientApproved() throws Exception {
    changeTransferStatus(TransferStatus.CLIENT_APPROVED);
    doSuccessfulTest(
        "domain_transfer_query.xml", "domain_transfer_query_response_client_approved.xml", 1);
  }

  @Test
  void testSuccess_clientRejected() throws Exception {
    changeTransferStatus(TransferStatus.CLIENT_REJECTED);
    doSuccessfulTest(
        "domain_transfer_query.xml", "domain_transfer_query_response_client_rejected.xml", 1);
  }

  @Test
  void testSuccess_clientCancelled() throws Exception {
    changeTransferStatus(TransferStatus.CLIENT_CANCELLED);
    doSuccessfulTest(
        "domain_transfer_query.xml", "domain_transfer_query_response_client_cancelled.xml", 1);
  }

  @Test
  void testSuccess_serverApproved() throws Exception {
    changeTransferStatus(TransferStatus.SERVER_APPROVED);
    doSuccessfulTest(
        "domain_transfer_query.xml", "domain_transfer_query_response_server_approved.xml", 1);
  }

  @Test
  void testSuccess_serverCancelled() throws Exception {
    changeTransferStatus(TransferStatus.SERVER_CANCELLED);
    doSuccessfulTest(
        "domain_transfer_query.xml", "domain_transfer_query_response_server_cancelled.xml", 1);
  }

  @Test
  void testSuccess_tenYears() throws Exception {
    // Extend registration by 9 years here; with the extra 1 year from the transfer, we should
    // hit the 10-year capping.
    domain =
        persistResource(
            domain
                .asBuilder()
                .setRegistrationExpirationTime(domain.getRegistrationExpirationTime().plusYears(9))
                .build());
    doSuccessfulTest("domain_transfer_query.xml", "domain_transfer_query_response_10_years.xml", 1);
  }

  @Test
  void testFailure_pendingDeleteDomain() throws Exception {
    changeTransferStatus(TransferStatus.SERVER_CANCELLED);
    domain =
        persistResource(domain.asBuilder().setDeletionTime(clock.nowUtc().plusDays(1)).build());
    doSuccessfulTest(
        "domain_transfer_query.xml", "domain_transfer_query_response_server_cancelled.xml", 1);
  }

  @Test
  void testFailure_badContactPassword() {
    // Change the contact's password so it does not match the password in the file.
    contact =
        persistResource(
            contact
                .asBuilder()
                .setAuthInfo(ContactAuthInfo.create(PasswordAuth.create("badpassword")))
                .build());
    EppException thrown =
        assertThrows(
            BadAuthInfoForResourceException.class,
            () -> doFailingTest("domain_transfer_query_contact_authinfo.xml"));
    assertAboutEppExceptions().that(thrown).marshalsToXml();
  }

  @Test
  void testFailure_badDomainPassword() {
    // Change the domain's password so it does not match the password in the file.
    domain =
        persistResource(
            domain
                .asBuilder()
                .setAuthInfo(DomainAuthInfo.create(PasswordAuth.create("badpassword")))
                .build());
    EppException thrown =
        assertThrows(
            BadAuthInfoForResourceException.class,
            () -> doFailingTest("domain_transfer_query_domain_authinfo.xml"));
    assertAboutEppExceptions().that(thrown).marshalsToXml();
  }

  @Test
  void testFailure_neverBeenTransferred() {
    changeTransferStatus(null);
    EppException thrown =
        assertThrows(
            NoTransferHistoryToQueryException.class,
            () -> doFailingTest("domain_transfer_query.xml"));
    assertAboutEppExceptions().that(thrown).marshalsToXml();
  }

  @Test
  void testFailure_unrelatedClient() {
    setRegistrarIdForFlow("ClientZ");
    EppException thrown =
        assertThrows(
            NotAuthorizedToViewTransferException.class,
            () -> doFailingTest("domain_transfer_query.xml"));
    assertAboutEppExceptions().that(thrown).marshalsToXml();
  }

  @Test
  void testFailure_deletedDomain() throws Exception {
    domain =
        persistResource(domain.asBuilder().setDeletionTime(clock.nowUtc().minusDays(1)).build());
    ResourceDoesNotExistException thrown =
        assertThrows(
            ResourceDoesNotExistException.class, () -> doFailingTest("domain_transfer_query.xml"));
    assertThat(thrown).hasMessageThat().contains(String.format("(%s)", getUniqueIdFromCommand()));
  }

  @Test
  void testFailure_nonexistentDomain() throws Exception {
    deleteTestDomain(domain, clock.nowUtc());
    ResourceDoesNotExistException thrown =
        assertThrows(
            ResourceDoesNotExistException.class, () -> doFailingTest("domain_transfer_query.xml"));
    assertThat(thrown).hasMessageThat().contains(String.format("(%s)", getUniqueIdFromCommand()));
  }

  @Test
  void testIcannActivityReportField_getsLogged() throws Exception {
    runFlow();
    assertIcannReportingActivityFieldLogged("srs-dom-transfer-query");
    assertTldsFieldLogged("tld");
  }

  @Test
  void testSuccess_serverApproved_afterAutorenews() throws Exception {
    // Set the clock to just past the extended registration time.  We'd expect the domain to have
    // auto-renewed once, but the transfer query response should be the same.
    clock.setTo(EXTENDED_REGISTRATION_EXPIRATION_TIME.plusMillis(1));
    assertThat(domain.cloneProjectedAtTime(clock.nowUtc()).getRegistrationExpirationTime())
        .isEqualTo(EXTENDED_REGISTRATION_EXPIRATION_TIME.plusYears(1));
    doSuccessfulTest(
        "domain_transfer_query.xml", "domain_transfer_query_response_server_approved.xml", 2);
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MonetaryAmount (JSR 354 (Money and Currency API) 1.0.1 API)</title>
<meta name="date" content="2016-11-06">
<meta name="keywords" content="javax.money.MonetaryAmount interface">
<meta name="keywords" content="getContext()">
<meta name="keywords" content="query()">
<meta name="keywords" content="with()">
<meta name="keywords" content="getFactory()">
<meta name="keywords" content="isGreaterThan()">
<meta name="keywords" content="isGreaterThanOrEqualTo()">
<meta name="keywords" content="isLessThan()">
<meta name="keywords" content="isLessThanOrEqualTo()">
<meta name="keywords" content="isEqualTo()">
<meta name="keywords" content="isNegative()">
<meta name="keywords" content="isNegativeOrZero()">
<meta name="keywords" content="isPositive()">
<meta name="keywords" content="isPositiveOrZero()">
<meta name="keywords" content="isZero()">
<meta name="keywords" content="signum()">
<meta name="keywords" content="add()">
<meta name="keywords" content="subtract()">
<meta name="keywords" content="multiply()">
<meta name="keywords" content="divide()">
<meta name="keywords" content="remainder()">
<meta name="keywords" content="divideAndRemainder()">
<meta name="keywords" content="divideToIntegralValue()">
<meta name="keywords" content="scaleByPowerOfTen()">
<meta name="keywords" content="abs()">
<meta name="keywords" content="negate()">
<meta name="keywords" content="plus()">
<meta name="keywords" content="stripTrailingZeros()">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.money

Interface MonetaryAmount

All Superinterfaces:

Comparable<MonetaryAmount>, CurrencySupplier, NumberSupplier

public interface MonetaryAmount
extends CurrencySupplier, NumberSupplier, Comparable<MonetaryAmount>

Interface defining a monetary amount. The effective format representation of an amount may vary
 depending on the implementation used. JSR 354 explicitly supports different types of monetary
 amounts to be implemented and used. Reason behind is that the requirements to an implementation
 heavily vary for different usage scenarios. E.g. product calculations may require high precision
 and scale, whereas low latency order and trading systems require high calculation performance for
 algorithmic operations.

 Each instance of an amount provides additional meta-data in form of a MonetaryContext.
 This context contains detailed information on the numeric capabilities, e.g. the supported
 precision and maximal scale, as well as the common implementation flavor.

 Also a MonetaryAmount provides a NumberValue, which allows easily to extract the
 numeric value, of the amount. And finally getFactory() provides a
 MonetaryAmountFactory, which allows to of instances of MonetaryAmount based
 on the same numeric implementation.

 This JSR additionally recommends to consider the following aspects:

Arithmetic operations should throw an ArithmeticException, if performing arithmetic
 operations between amounts exceeds the capabilities of the numeric representation type used. Any
 implicit truncating, that would lead to complete invalid and useless results, should be avoided.
 This recommendation does not affect format rounding, as required by the format numeric
 representation of a monetary amount.

Monetary amounts should allow numbers as argument for arithmetic operations like division and
 multiplication. Adding or subtracting of amounts must only be possible by passing instances of
 MonetaryAmount.

Nevertheless numeric truncation is also explicitly supported when calling
 NumberValue.numberValue(Class), whereas the exact counterpart,
 NumberValue.numberValueExact(Class), works similar to
 BigDecimal.longValueExact().

Since implementations are recommended to be immutable, an operation should never change any
 format state of an instance. Given an instance, all operations are required to be fully
 reproducible.

Finally the result of calling with(MonetaryOperator) must be of the same type as
 type on which with was called. The with method also defines additional
 interoperability requirements that are important to enable this invariant.

To enable further interoperability a static method from(MonetaryAmount) is
 recommended to be implemented on each implementation class, that allows conversion of a
 MonetaryAmount to a concrete instance. E.g.a class MyMoney extends MonetaryAmount
 would contain the following method:

 public final class MyMoney implements MonetaryAmount{
   ...
   public static MyMoney from(MonetaryAmount amount)(...)
 }

Implementation specification

 Implementations of this interface must be

thread-safe

 Implementations of this interface should be

final

serializable, hereby writing the numeric value, the MonetaryContext and a serialized
 CurrencyUnit.

 Implementations of this interface must be

thread-safe

immutable

comparable

must implement equals/hashCode, hereby considering

Implementation type

CurrencyUnit

Numeric value.

 This also means that two different implementations types with the same currency and numeric value
 are NOT equal.

Version:

0.8.2

Author:

Anatole Tresch, Werner Keil

See Also:

with(MonetaryOperator)

Method Summary

All Methods Instance Methods Abstract Methods Default Methods

Modifier and Type
Method and Description

MonetaryAmount
abs()

Returns a MonetaryAmount whose value is the absolute value of this
 MonetaryAmount, and whose scale is this.scale().

MonetaryAmount
add(MonetaryAmount amount)

Returns a MonetaryAmount whose value is this + amount, and whose scale is max(this.scale(),
 amount.scale().

MonetaryAmount
divide(double divisor)

Returns a MonetaryAmount whose value is this /
 divisor, and whose preferred scale is this.scale() -
 divisor.scale(); if the exact quotient cannot be represented an ArithmeticException
 is thrown.

MonetaryAmount
divide(long divisor)

Returns a MonetaryAmount whose value is this /
 divisor, and whose preferred scale is this.scale() -
 divisor.scale(); if the exact quotient cannot be represented an ArithmeticException
 is thrown.

MonetaryAmount
divide(Number divisor)

Returns a MonetaryAmount whose value is this /
 divisor, and whose preferred scale is this.scale() -
 divisor.scale(); if the exact quotient cannot be represented an ArithmeticException
 is thrown.

MonetaryAmount[]
divideAndRemainder(double divisor)

Returns a two-element MonetaryAmount array containing the result of
 divideToIntegralValue followed by the result of remainder on the two
 operands.

MonetaryAmount[]
divideAndRemainder(long divisor)

Returns a two-element MonetaryAmount array containing the result of
 divideToIntegralValue followed by the result of remainder on the two
 operands.

MonetaryAmount[]
divideAndRemainder(Number divisor)

Returns a two-element MonetaryAmount array containing the result of
 divideToIntegralValue followed by the result of remainder on the two
 operands.

MonetaryAmount
divideToIntegralValue(double divisor)

Returns a MonetaryAmount whose value is the integer part of the quotient
 this / divisor rounded down.

MonetaryAmount
divideToIntegralValue(long divisor)

Returns a MonetaryAmount whose value is the integer part of the quotient
 this / divisor rounded down.

MonetaryAmount
divideToIntegralValue(Number divisor)

Returns a MonetaryAmount whose value is the integer part of the quotient
 this / divisor rounded down.

MonetaryContext
getContext()

Returns the MonetaryContext of this MonetaryAmount.

MonetaryAmountFactory<? extends MonetaryAmount>
getFactory()

Creates a new MonetaryAmountFactory, returning the same implementation type Hereby
 this given amount is used as a template, so reusing the CurrencyUnit, its numeric
 value, the algorithmic implementation as well as the current MonetaryContext.

boolean
isEqualTo(MonetaryAmount amount)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

boolean
isGreaterThan(MonetaryAmount amount)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

boolean
isGreaterThanOrEqualTo(MonetaryAmount amount)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

boolean
isLessThan(MonetaryAmount amount)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

boolean
isLessThanOrEqualTo(MonetaryAmount amt)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

default boolean
isNegative()

Checks if a MonetaryAmount is negative.

default boolean
isNegativeOrZero()

Checks if a MonetaryAmount is negative or zero.

default boolean
isPositive()

Checks if a MonetaryAmount is positive.

default boolean
isPositiveOrZero()

Checks if a MonetaryAmount is positive or zero.

default boolean
isZero()

Checks if an MonetaryAmount is zero.

MonetaryAmount
multiply(double multiplicand)

Returns a MonetaryAmount whose value is <tt>(this ×
 multiplicand)</tt>, and whose scale is this.scale() +
 multiplicand.scale().

MonetaryAmount
multiply(long multiplicand)

Returns a MonetaryAmount whose value is <tt>(this ×
 multiplicand)</tt>, and whose scale is this.scale() +
 multiplicand.scale().

MonetaryAmount
multiply(Number multiplicand)

Returns a MonetaryAmount whose value is <tt>(this ×
 multiplicand)</tt>, and whose scale is this.scale() +
 multiplicand.scale().

MonetaryAmount
negate()

Returns a MonetaryAmount whose value is -this, and whose scale is
 this.scale().

MonetaryAmount
plus()

Returns a MonetaryAmount whose value is +this, with rounding according to
 the context settings.

default <R> R
query(MonetaryQuery<R> query)

Queries this monetary amount for a value.

MonetaryAmount
remainder(double divisor)

Returns a MonetaryAmount whose value is this % divisor.

MonetaryAmount
remainder(long divisor)

Returns a MonetaryAmount whose value is this % divisor.

MonetaryAmount
remainder(Number divisor)

Returns a MonetaryAmount whose value is this % divisor.

MonetaryAmount
scaleByPowerOfTen(int power)

Returns a MonetaryAmount whose numerical value is equal to ( this *
 10n).

int
signum()

Returns the signum function of this MonetaryAmount.

MonetaryAmount
stripTrailingZeros()

Returns a MonetaryAmount which is numerically equal to this one but with any trailing
 zeros removed from the representation.

MonetaryAmount
subtract(MonetaryAmount amount)

Returns a MonetaryAmount whose value is this -
 amount, and whose scale is max(this.scale(),
 subtrahend.scale().

default MonetaryAmount
with(MonetaryOperator operator)

Returns an operated object of the same type as this object with the operation made.

Methods inherited from interface javax.money.CurrencySupplier

getCurrency

Methods inherited from interface javax.money.NumberSupplier

getNumber

Methods inherited from interface java.lang.Comparable

compareTo

Method Detail

getContext

MonetaryContext getContext()

Returns the MonetaryContext of this MonetaryAmount. The
 MonetaryContext provides additional information about the numeric representation and
 the numeric capabilities. This information can be used by code to determine situations where
 MonetaryAmount instances must be converted to avoid implicit truncation, which can
 lead to invalid results.

Returns:

the MonetaryContext of this MonetaryAmount, never null .

query

default <R> R query(MonetaryQuery<R> query)

Queries this monetary amount for a value.

 This queries this amount using the specified query strategy object.

 Implementations must ensure that no observable state is altered when this read-only method is
 invoked.

Type Parameters:

R - the type of the result

Parameters:

query - the query to invoke, not null

Returns:

the query result, null may be returned (defined by the query)

with

default MonetaryAmount with(MonetaryOperator operator)

Returns an operated object of the same type as this object with the operation made.
 Hereby returning an instannce of the same type is very important to prevent
 uncontrolled mixup of implementations. Switching between implementations is still easily
 possible, e.g. by using according MonetaryAmountFactory instances:

 // converting from Money to MyMoney
 Money m = ...;
 MonetartyAmountFactory<MyMoney> f = Monetary.queryAmountFactory(MyMoney.class);
 MyMoney myMoney = f.setAmount(m).of();

 This converts this monetary amount according to the rules of the specified operator. A
 typical operator will change the amount and leave the currency unchanged. A more complex
 operator might also change the currency.

 Some example code indicating how and why this method is used:

 MonetaryAmount money = money.with(amountMultipliedBy(2));
 money = money.with(amountRoundedToNearestWholeUnit());

 Hereby also the method signature on the implementation type must return the concrete type, to
 enable a fluent API, e.g.

 public final class MyMoney implements MonetaryAmount{
   ...
   public MyMoney with(MonetaryOperator operator){
     ...
   }

   ...
 }

Parameters:

operator - the operator to use, not null

Returns:

an object of the same type with the specified conversion made, not null

getFactory

MonetaryAmountFactory<? extends MonetaryAmount> getFactory()

Creates a new MonetaryAmountFactory, returning the same implementation type Hereby
 this given amount is used as a template, so reusing the CurrencyUnit, its numeric
 value, the algorithmic implementation as well as the current MonetaryContext.

 This method is used for creating a new amount result after having done calculations that are
 not directly mappable to the default monetary arithmetics, e.g. currency conversion.

Returns:

the new MonetaryAmountFactory with the given MonetaryAmount as its
 default values.

isGreaterThan

boolean isGreaterThan(MonetaryAmount amount)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

Parameters:

amount - the MonetaryAmount to be compared with this instance.

Returns:

true if amount > this.

Throws:

MonetaryException - if the amount's currency is not equals to the currency of this instance.

isGreaterThanOrEqualTo

boolean isGreaterThanOrEqualTo(MonetaryAmount amount)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

Parameters:

amount - the MonetaryAmount to be compared with this instance.

Returns:

true if amount >= this.

Throws:

MonetaryException - if the amount's currency is not equals to the currency of this instance.

isLessThan

boolean isLessThan(MonetaryAmount amount)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

Parameters:

amount - the MonetaryAmount to be compared with this instance.

Returns:

true if amount < this.

Throws:

MonetaryException - if the amount's currency is not equals to the currency of this instance.

isLessThanOrEqualTo

boolean isLessThanOrEqualTo(MonetaryAmount amt)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

Parameters:

amt - the MonetaryAmount to be compared with this instance.

Returns:

true if amount <= this.

Throws:

MonetaryException - if the amount's currency is not equals to the currency of this instance.

isEqualTo

boolean isEqualTo(MonetaryAmount amount)

Compares two instances of MonetaryAmount, hereby ignoring non significant trailing
 zeroes and different numeric capabilities.

Parameters:

amount - the MonetaryAmount to be compared with this instance.

Returns:

true if amount == this.

Throws:

MonetaryException - if the amount's currency is not equals to the currency of this instance.

isNegative

default boolean isNegative()

Checks if a MonetaryAmount is negative.

Returns:

true if signum() < 0.

isNegativeOrZero

default boolean isNegativeOrZero()

Checks if a MonetaryAmount is negative or zero.

Returns:

true if signum() <= 0.

isPositive

default boolean isPositive()

Checks if a MonetaryAmount is positive.

Returns:

true if signum() > 0.

isPositiveOrZero

default boolean isPositiveOrZero()

Checks if a MonetaryAmount is positive or zero.

Returns:

true if signum() >= 0.

isZero

default boolean isZero()

Checks if an MonetaryAmount is zero.

Returns:

true if signum() == 0.

signum

int signum()

Returns the signum function of this MonetaryAmount.

Returns:

-1, 0, or 1 as the value of this MonetaryAmount is negative, zero, or
 positive.

add

MonetaryAmount add(MonetaryAmount amount)

Returns a MonetaryAmount whose value is this + amount, and whose scale is max(this.scale(),
 amount.scale().

Parameters:

amount - value to be added to this MonetaryAmount.

Returns:

this + amount

Throws:

ArithmeticException - if the result exceeds the numeric capabilities of this implementation class, i.e.
                             the MonetaryContext cannot be adapted as required.

subtract

MonetaryAmount subtract(MonetaryAmount amount)

Returns a MonetaryAmount whose value is this -
 amount, and whose scale is max(this.scale(),
 subtrahend.scale().

Parameters:

amount - value to be subtracted from this MonetaryAmount.

Returns:

this - amount

Throws:

ArithmeticException - if the result exceeds the numeric capabilities of this implementation class, i.e.
                             the MonetaryContext cannot be adapted as required.

multiply

MonetaryAmount multiply(long multiplicand)

Returns a MonetaryAmount whose value is <tt>(this ×
 multiplicand)</tt>, and whose scale is this.scale() +
 multiplicand.scale().

Parameters:

multiplicand - value to be multiplied by this MonetaryAmount.

Returns:

this * multiplicand

Throws:

ArithmeticException - if the result exceeds the numeric capabilities of this implementation class, i.e.
                             the MonetaryContext cannot be adapted as required.

multiply

MonetaryAmount multiply(double multiplicand)

Returns a MonetaryAmount whose value is <tt>(this ×
 multiplicand)</tt>, and whose scale is this.scale() +
 multiplicand.scale().
 By default the input value's scale will be rounded to
 accommodate the format capabilities, and no ArithmeticException
 is thrown if the input number's scale exceeds the capabilities.

Parameters:

multiplicand - value to be multiplied by this MonetaryAmount. If the multiplicand's scale exceeds
                     the
                     capabilities of the implementation, it may be rounded implicitly.

Returns:

this * multiplicand

Throws:

ArithmeticException - if the result exceeds the numeric capabilities of this implementation class, i.e.
                             the MonetaryContext cannot be adapted as required.

multiply

MonetaryAmount multiply(Number multiplicand)

Returns a MonetaryAmount whose value is <tt>(this ×
 multiplicand)</tt>, and whose scale is this.scale() +
 multiplicand.scale().

Parameters:

multiplicand - value to be multiplied by this MonetaryAmount. If the multiplicand's scale exceeds
                     the
                     capabilities of the implementation, it may be rounded implicitly.

Returns:

this * multiplicand

Throws:

ArithmeticException - if the result exceeds the numeric capabilities of this implementation class, i.e.
                             the MonetaryContext cannot be adapted as required.

divide

MonetaryAmount divide(long divisor)

Returns a MonetaryAmount whose value is this /
 divisor, and whose preferred scale is this.scale() -
 divisor.scale(); if the exact quotient cannot be represented an ArithmeticException
 is thrown.

Parameters:

divisor - value by which this MonetaryAmount is to be divided.

Returns:

this / divisor

Throws:

ArithmeticException - if the exact quotient does not have a terminating decimal expansion, or if the
                             result exceeds the numeric capabilities of this implementation class, i.e. the
                             MonetaryContext cannot be adapted as required.

divide

MonetaryAmount divide(double divisor)

Returns a MonetaryAmount whose value is this /
 divisor, and whose preferred scale is this.scale() -
 divisor.scale(); if the exact quotient cannot be represented an ArithmeticException
 is thrown.

Parameters:

divisor - value by which this MonetaryAmount is to be divided.

Returns:

this / divisor

Throws:

ArithmeticException - if the exact quotient does not have a terminating decimal expansion, or if the
                             result exceeds the numeric capabilities of this implementation class, i.e. the
                             MonetaryContext cannot be adapted as required.

divide

MonetaryAmount divide(Number divisor)

Returns a MonetaryAmount whose value is this /
 divisor, and whose preferred scale is this.scale() -
 divisor.scale(); if the exact quotient cannot be represented an ArithmeticException
 is thrown.

Parameters:

divisor - value by which this MonetaryAmount is to be divided.

Returns:

this / divisor

Throws:

ArithmeticException - if the exact quotient does not have a terminating decimal expansion, or if the
                             result exceeds the numeric capabilities of this implementation class, i.e. the
                             MonetaryContext cannot be adapted as required.

remainder

MonetaryAmount remainder(long divisor)

Returns a MonetaryAmount whose value is this % divisor.

 The remainder is given by
 this.subtract(this.divideToIntegralValue(divisor).multiply(divisor) . Note that this
 is not the modulo operation (the result can be negative).

Parameters:

divisor - value by which this MonetaryAmount is to be divided.

Returns:

this % divisor.

Throws:

ArithmeticException - if divisor==0, or if the result exceeds the numeric capabilities of this
                             implementation class, i.e. the MonetaryContext cannot be adapted as
                             required.

remainder

MonetaryAmount remainder(double divisor)

Returns a MonetaryAmount whose value is this % divisor.

 The remainder is given by
 this.subtract(this.divideToIntegralValue(divisor).multiply(divisor) . Note that this
 is not the modulo operation (the result can be negative).

Parameters:

divisor - value by which this MonetaryAmount is to be divided.

Returns:

this % divisor.

Throws:

ArithmeticException - if divisor==0, or if the result exceeds the numeric capabilities of this
                             implementation class, i.e. the MonetaryContext cannot be adapted as
                             required.

remainder

MonetaryAmount remainder(Number divisor)

Returns a MonetaryAmount whose value is this % divisor.

 The remainder is given by
 this.subtract(this.divideToIntegralValue(divisor).multiply(divisor) . Note that this
 is not the modulo operation (the result can be negative).

Parameters:

divisor - value by which this MonetaryAmount is to be divided.

Returns:

this % divisor.

Throws:

ArithmeticException - if divisor==0, or if the result exceeds the numeric capabilities of this
                             implementation class, i.e. the MonetaryContext cannot be adapted as
                             required.

divideAndRemainder

MonetaryAmount[] divideAndRemainder(long divisor)

Returns a two-element MonetaryAmount array containing the result of
 divideToIntegralValue followed by the result of remainder on the two
 operands.

 Note that if both the integer quotient and remainder are needed, this method is faster than
 using the divideToIntegralValue and remainder methods separately because the
 division need only be carried out once.

Parameters:

divisor - value by which this MonetaryAmount is to be divided, and the remainder
                computed.

Returns:

a two element MonetaryAmount array: the quotient (the result of
 divideToIntegralValue) is the initial element and the remainder is the final
 element.

Throws:

ArithmeticException - if divisor==0, or if the result exceeds the numeric capabilities of this
                             implementation class, i.e. the MonetaryContext cannot be adapted as
                             required.

See Also:

divideToIntegralValue(long),
remainder(long)

divideAndRemainder

MonetaryAmount[] divideAndRemainder(double divisor)

Returns a two-element MonetaryAmount array containing the result of
 divideToIntegralValue followed by the result of remainder on the two
 operands.

 Note that if both the integer quotient and remainder are needed, this method is faster than
 using the divideToIntegralValue and remainder methods separately because the
 division need only be carried out once.

Parameters:

divisor - value by which this MonetaryAmount is to be divided, and the remainder
                computed.

Returns:

a two element MonetaryAmount array: the quotient (the result of
 divideToIntegralValue) is the initial element and the remainder is the final
 element.

Throws:

ArithmeticException - if divisor==0, or if the result exceeds the numeric capabilities of this
                             implementation class, i.e. the MonetaryContext cannot be adapted as
                             required.

See Also:

divideToIntegralValue(double),
remainder(double)

divideAndRemainder

MonetaryAmount[] divideAndRemainder(Number divisor)

Returns a two-element MonetaryAmount array containing the result of
 divideToIntegralValue followed by the result of remainder on the two
 operands.

 Note that if both the integer quotient and remainder are needed, this method is faster than
 using the divideToIntegralValue and remainder methods separately because the
 division need only be carried out once.

Parameters:

divisor - value by which this MonetaryAmount is to be divided, and the remainder
                computed.

Returns:

a two element MonetaryAmount array: the quotient (the result of
 divideToIntegralValue) is the initial element and the remainder is the final
 element.

Throws:

ArithmeticException - if divisor==0, or if the result exceeds the numeric capabilities of this
                             implementation class, i.e. the MonetaryContext cannot be adapted as
                             required.

See Also:

divideToIntegralValue(Number),
remainder(Number)

divideToIntegralValue

MonetaryAmount divideToIntegralValue(long divisor)

Returns a MonetaryAmount whose value is the integer part of the quotient
 this / divisor rounded down. The preferred scale of the result is
 this.scale() -
 divisor.scale().

Parameters:

divisor - value by which this BigDecimal is to be divided.

Returns:

The integer part of this / divisor.

Throws:

ArithmeticException - if divisor==0

See Also:

BigDecimal.divideToIntegralValue(java.math.BigDecimal)

divideToIntegralValue

MonetaryAmount divideToIntegralValue(double divisor)

Returns a MonetaryAmount whose value is the integer part of the quotient
 this / divisor rounded down. The preferred scale of the result is
 this.scale() - divisor.scale().

Parameters:

divisor - value by which this BigDecimal is to be divided.

Returns:

The integer part of this / divisor.

Throws:

ArithmeticException - if divisor==0

See Also:

BigDecimal.divideToIntegralValue(java.math.BigDecimal)

divideToIntegralValue

MonetaryAmount divideToIntegralValue(Number divisor)

Returns a MonetaryAmount whose value is the integer part of the quotient
 this / divisor rounded down. The preferred scale of the result is
 this.scale() -
 divisor.scale().

Parameters:

divisor - value by which this BigDecimal is to be divided.

Returns:

The integer part of this / divisor.

Throws:

ArithmeticException - if divisor==0

See Also:

BigDecimal.divideToIntegralValue(java.math.BigDecimal)

scaleByPowerOfTen

MonetaryAmount scaleByPowerOfTen(int power)

Returns a MonetaryAmount whose numerical value is equal to ( this *
 10n). The scale of the result is this.scale() - n.

Parameters:

power - the power.

Returns:

the calculated amount value.

Throws:

ArithmeticException - if the scale would be outside the range of a 32-bit integer, or if the result
                             exceeds the numeric capabilities of this implementation class, i.e. the
                             MonetaryContext cannot be adapted as required.

abs

MonetaryAmount abs()

Returns a MonetaryAmount whose value is the absolute value of this
 MonetaryAmount, and whose scale is this.scale().

Returns:

abs(this

negate

MonetaryAmount negate()

Returns a MonetaryAmount whose value is -this, and whose scale is
 this.scale().

Returns:

-this.

plus

MonetaryAmount plus()

Returns a MonetaryAmount whose value is +this, with rounding according to
 the context settings.

Returns:

this, rounded as necessary. A zero result will have a scale of 0.

Throws:

ArithmeticException - if rounding fails.

See Also:

BigDecimal.plus()

stripTrailingZeros

MonetaryAmount stripTrailingZeros()

Returns a MonetaryAmount which is numerically equal to this one but with any trailing
 zeros removed from the representation. For example, stripping the trailing zeros from the
 MonetaryAmount value CHF 600.0, which has [BigInteger, scale]
 components equals to [6000, 1], yields 6E2 with [ BigInteger, scale]
 components equals to [6, -2]

Returns:

a numerically equal MonetaryAmount with any trailing zeros removed.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2012–2016 JSR 354 - Expert Group. All rights reserved.


text:
#ifndef GUITDRV_ADS7846_H            /* Make sure we only include it once */
#define GUITDRV_ADS7846_H

#include "GUI_Type.h"

#if defined(__cplusplus)
extern "C" {     /* Make sure we have C-declarations in C++ programs */
#endif

/*********************************************************************
*
*       Types
*
**********************************************************************
*/

typedef struct {
  //
  // Function pointer (1)
  //
  void     (* pfSendCmd)   (U8 Data);     // Sends a 8-bit command to the peripheral
  U16      (* pfGetResult) (void);        // Retrieves the result of the AD conversion. 4 dummy bytes have to be shifted out to the left.
  char     (* pfGetBusy)   (void);        // Retrieves the status of the busy line. 0: Not busy; 1: Busy
  void     (* pfSetCS)     (char OnOff);  // Set chip select line. OnOff == 1 means peripheral selected
  //
  // Configuration (2)
  //
  unsigned Orientation;
  int      xLog0;
  int      xLog1;
  int      xPhys0;
  int      xPhys1;
  int      yLog0;
  int      yLog1;
  int      yPhys0;
  int      yPhys1;
  //
  // Optional, touch recognition via PENIRQ line (3)
  //
  char     (* pfGetPENIRQ) (void);        // Retrieves the status of the PENIRQ line to detect a touch event.
  //
  // Optional, touch recognition via touch pressure measurement (4)
  //
  int      PressureMin;                   // Minimum pressure threshold. A measured pressure below this value means we do not have a valid touch event.
  int      PressureMax;                   // Maximum pressure threshold. A measured pressure above this value means we do not have a valid touch event.
  int      PlateResistanceX;              // Resistance of the X-plate of the touch screen. This value is needed for calculation of the touch pressure.
} GUITDRV_ADS7846_CONFIG;

typedef struct {
  int      xPhys;     // Last measured x value
  int      yPhys;     // Last measured y value
  int      z1Phys;    // Last measured z1 value
  int      z2Phys;    // Last measured z2 value
  int      PENIRQ;    // Last sampled PENIRQ state if PENIRQ callback has been set
  int      Pressure;  // Last measured touch pressure if touch pressure measurement is enabled
} GUITDRV_ADS7846_LAST_VAL;

/*********************************************************************
*
*       Prototypes
*
**********************************************************************
*/

void GUITDRV_ADS7846_Config    (GUITDRV_ADS7846_CONFIG * pConfig);
char GUITDRV_ADS7846_Exec      (void);
void GUITDRV_ADS7846_GetLastVal(GUITDRV_ADS7846_LAST_VAL * p);

#if defined(__cplusplus)
}                /* Make sure we have C-declarations in C++ programs */
#endif

#endif   /* GUITDRV_ADS7846_H */

/*************************** End of file ****************************/


text:
jest.mock('hapi');
const Hapi = require('hapi');
const honeycombServer = require('../../lib/');

describe('honeycomb-server', () => {
  let server;

  beforeEach(() => {
    server = {
      connection: jest.fn(),
      register: jest.fn(),
      start: jest.fn(() => new Promise((resolve) => { resolve(); })),
      stop: jest.fn(),
      info: {
        uri: 'http://honeycomb.example.com:3000',
      },
    };

    Hapi.Server.mockImplementation(() => server);

    console.info = jest.fn(); // eslint-disable-line no-console
    console.error = jest.fn(); // eslint-disable-line no-console
  });

  afterEach(() => {
    jest.resetAllMocks();
  });

  test('has expected "start" export function', () => {
    expect(Object.keys(honeycombServer)).toEqual(['start']);
  });

  describe('start', () => {
    test('is an instance of function', () => {
      expect(honeycombServer.start).toBeInstanceOf(Function);
    });

    test('has been called with expected options', () => {
      honeycombServer.start();
      expect(Hapi.Server).toHaveBeenCalledWith({});
    });

    test('has been called with expected server options', () => {
      const options = { load: { sampleInterval: 1000 } };
      honeycombServer.start({ server: options });
      expect(Hapi.Server).toHaveBeenCalledWith(options);
    });

    test('has been called server.start()', () => {
      honeycombServer.start();
      expect(server.start).toHaveBeenCalled();
    });

    test('has been called server.connection()', () => {
      honeycombServer.start();
      expect(server.connection).toHaveBeenCalled();
    });

    test('has been called server.register()', () => {
      honeycombServer.start({ plugins: [{ module: 'inert' }] });
      expect(server.register).toHaveBeenCalled();
    });

    test('returns a Promise', () => {
      expect(honeycombServer.start().constructor.name).toBe('Promise');
    });

    test('returns the server', () => (
      honeycombServer.start()
        .then((serverInstance) => {
          expect(server).toEqual(serverInstance);
        })
    ));

    test('has been called console.info()', () => (
      honeycombServer.start()
        .then(() => {
          // eslint-disable-next-line no-console
          expect(console.info).toBeCalledWith(
            'Server running at:', 'http://honeycomb.example.com:3000'
          );
        })
    ));
  });

  describe('connection', () => {
    test('has been called with expected connections options', () => {
      const options = {
        connections: [{
          host: 'honeycomb.example.com',
          address: '127.0.0.1',
          port: 3003,
        }],
      };

      honeycombServer.start(options);

      expect(server.connection.mock.calls[0][0].port).toBe(options.connections[0].port);
      expect(server.connection.mock.calls[0][0].address).toBe(options.connections[0].address);
      expect(server.connection.mock.calls[0][0].host).toBe(options.connections[0].host);
    });

    test('has expected default port', () => {
      honeycombServer.start();
      expect(server.connection.mock.calls[0][0].port).toBe(3000);
    });

    test('has expected port by process.env.PORT', () => {
      process.env.PORT = 3003;
      honeycombServer.start();
      expect(server.connection.mock.calls[0][0].port).toBe(3003);
    });

    test('has expected default address', () => {
      honeycombServer.start();
      expect(server.connection.mock.calls[0][0].address).toBe('0.0.0.0');
    });

    test('has expected address by process.env.HOST_IP', () => {
      process.env.HOST_IP = '127.0.0.1';
      honeycombServer.start();
      expect(server.connection.mock.calls[0][0].address).toBe('127.0.0.1');
    });

    test('has expected default host', () => {
      honeycombServer.start();
      expect(server.connection.mock.calls[0][0].host).toBe(undefined);
    });

    test('has expected host by process.env.HOST', () => {
      process.env.HOST = 'honeycomb.example.com';
      honeycombServer.start();
      expect(server.connection.mock.calls[0][0].host).toBe('honeycomb.example.com');
    });
  });

  describe('error', () => {
    let myServer;

    beforeEach(() => {
      server.start = jest.fn(() => new Promise((resolve, reject) => { reject(); }));
      Hapi.Server.mockImplementation(() => server);

      myServer = honeycombServer.start({
        server: {
          cache: {
            engine: {
              start: callback => (callback(new Error('oops'))),
            },
          },
        },
      });
    });

    test('has been called console.error()', () => (
      myServer.then(() => {
        // eslint-disable-next-line no-console
        expect(console.error).toBeCalledWith(
          'There was an error starting the server'
        );
      })
    ));

    test('has been called server.stop()', () => (
      myServer.then(() => expect(server.stop).toHaveBeenCalled())
    ));
  });
});


text:
package com.att.research.xacmlatt.pdp.policy.dom;

import java.io.File;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.att.research.xacml.api.XACML3;
import com.att.research.xacml.std.dom.DOMStructureException;
import com.att.research.xacml.std.dom.DOMUtil;
import com.att.research.xacmlatt.pdp.policy.PolicyDef;
import com.att.research.xacmlatt.pdp.policy.PolicySet;

/**
 * DOMPolicyDef extends {@link com.att.research.xacmlatt.pdp.policy.PolicyDef} with methods for loading them from a File.
 *
 * @author car
 * @version $Revision: 1.2 $
 */
public abstract class DOMPolicyDef {
	protected DOMPolicyDef() {
	}

	protected static PolicyDef newInstance(Document document, PolicySet policySetParent) throws DOMStructureException {
		PolicyDef policyDef	= null;
		try {
			Node rootNode	= document.getFirstChild();
			if (rootNode == null) {
				throw new Exception("No child in document");
			}

			// Process comments
			while (true) {
				if (rootNode.getNodeType() != Node.COMMENT_NODE) {
					break;
				}
				rootNode = rootNode.getNextSibling();
				if (rootNode == null) {
					throw new Exception("Only comments encountered in document");
				}
			}
			if (DOMUtil.isInNamespace(rootNode, XACML3.XMLNS)) {
				if (XACML3.ELEMENT_POLICY.equals(rootNode.getLocalName())) {
					policyDef	= DOMPolicy.newInstance(rootNode, policySetParent, null);
					if (policyDef == null) {
						throw new DOMStructureException("Failed to parse Policy");
					}
				} else if (XACML3.ELEMENT_POLICYSET.equals(rootNode.getLocalName())) {
					policyDef	= DOMPolicySet.newInstance(rootNode, policySetParent, null);
					if (policyDef == null) {
						throw new DOMStructureException("Failed to parse PolicySet");
					}
				} else {
					throw DOMUtil.newUnexpectedElementException(rootNode);
				}
			} else {
				throw DOMUtil.newUnexpectedElementException(rootNode);
			}
		} catch (Exception ex) {
			throw new DOMStructureException("Exception parsing Policy: " + ex.getMessage(), ex);
		}
		return policyDef;
	}

	public static PolicyDef load(InputStream inputStream) throws DOMStructureException {
		/*
		 * Get the DocumentBuilderFactory
		 */
		DocumentBuilderFactory documentBuilderFactory	= DocumentBuilderFactory.newInstance();
		if (documentBuilderFactory == null) {
			throw new DOMStructureException("No XML DocumentBuilderFactory configured");
		}
		documentBuilderFactory.setNamespaceAware(true);

		/*
		 * Get the DocumentBuilder
		 */
		DocumentBuilder documentBuilder	= null;
		try {
			documentBuilder	= documentBuilderFactory.newDocumentBuilder();
		} catch (Exception ex) {
			throw new DOMStructureException("Exception creating DocumentBuilder: " + ex.getMessage(), ex);
		}

		/*
		 * Parse the XML file
		 */
		PolicyDef policyDef	= null;
		try {
			Document document	= documentBuilder.parse(inputStream);
			if (document == null) {
				throw new Exception("Null document returned");
			}
			policyDef	= newInstance(document, null);
		} catch (Exception ex) {
			throw new DOMStructureException("Exception loading Policy from input stream: " + ex.getMessage(), ex);
		}
		return policyDef;
	}

	/**
	 * Creates a new PolicyDef derived object by loading the given File containing a XACML 3.0
	 * Policy or PolicySet.
	 *
	 * @param filePolicy the File containing the XACML Policy or PolicySet
	 * @return the newly created PolicyDef
	 * @throws DOMStructureException if there is an error loading the PolicyDef
	 */
	public static PolicyDef load(File filePolicy) throws DOMStructureException {
		/*
		 * Parse the XML file
		 */
		PolicyDef policyDef	= null;
		try {
			Document document	= DOMUtil.loadDocument(filePolicy);
			if (document == null) {
				throw new Exception("Null document returned");
			}
			policyDef	= newInstance(document, null);
		} catch (Exception ex) {
			throw new DOMStructureException("Exception loading Policy file \"" + filePolicy.getAbsolutePath() + "\": " + ex.getMessage(), ex);
		}
		return policyDef;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<VerticalScroll>useIfNecessary</VerticalScroll>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
		<ChildItems>
			<Button name="ОбновитьДанныеСправочника" id="10">
				<Type>CommandBarButton</Type>
				<CommandName>Form.Command.ОбновитьДанныеСправочника</CommandName>
				<Parameter xsi:nil="true"/>
				<ExtendedTooltip name="ОбновитьДанныеСправочникаExtendedTooltip" id="15"/>
			</Button>
		</ChildItems>
	</AutoCommandBar>
	<Events>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
	</Events>
	<ChildItems>

			<CommandBarLocation>None</CommandBarLocation>
			<ReadOnly>true</ReadOnly>
			<DefaultItem>true</DefaultItem>
			<ChangeRowSet>false</ChangeRowSet>
			false
			<HorizontalLines>false</HorizontalLines>
			<UseAlternationRowColor>true</UseAlternationRowColor>
			<InitialTreeView>ExpandTopLevel</InitialTreeView>
			<EnableStartDrag>true</EnableStartDrag>
			<DataPath>Список</DataPath>
			<RowPictureDataPath>Список.DefaultPicture</RowPictureDataPath>
			<SearchStringLocation>None</SearchStringLocation>
			<ViewStatusLocation>None</ViewStatusLocation>
			<SearchControlLocation>None</SearchControlLocation>
			<AutoRefresh>false</AutoRefresh>
			<AutoRefreshPeriod>60</AutoRefreshPeriod>
			<Period xsi:type="v8:StandardPeriod">
				<v8:variant xsi:type="v8:StandardPeriodVariant">Custom</v8:variant>
				<v8:startDate>0001-01-01T00:00:00</v8:startDate>
				<v8:endDate>0001-01-01T00:00:00</v8:endDate>
			</Period>
			<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
			<RestoreCurrentRow>false</RestoreCurrentRow>
			<TopLevelParent xsi:nil="true"/>
			<ShowRoot>false</ShowRoot>
			<AllowRootChoice>false</AllowRootChoice>
			<UpdateOnDataChange>Auto</UpdateOnDataChange>
			<ContextMenu name="СписокКонтекстноеМеню" id="2"/>
			<AutoCommandBar name="СписокКоманднаяПанель" id="3">
				<Autofill>false</Autofill>
			</AutoCommandBar>
			<ExtendedTooltip name="СписокExtendedTooltip" id="16"/>
			<SearchStringAddition name="СписокSearchString" id="17">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>0</lf:additionId>
				</Source>
				<ContextMenu name="СписокSearchStringContextMenu" id="18"/>
				<ExtendedTooltip name="СписокSearchStringExtendedTooltip" id="19"/>
			</SearchStringAddition>
			<ViewStatusAddition name="СписокViewStatus" id="20">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>1</lf:additionId>
				</Source>
				<ContextMenu name="СписокViewStatusContextMenu" id="21"/>
				<ExtendedTooltip name="СписокViewStatusExtendedTooltip" id="22"/>
			</ViewStatusAddition>
			<SearchControlAddition name="СписокSearchControl" id="23">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>2</lf:additionId>
				</Source>
				<ContextMenu name="СписокSearchControlContextMenu" id="24"/>
				<ExtendedTooltip name="СписокSearchControlExtendedTooltip" id="25"/>
			</SearchControlAddition>
			<Events>
				<Event name="ValueChoice">СписокВыборЗначения</Event>
			</Events>
			<ChildItems>
				<LabelField name="Синоним" id="4">
					<DataPath>Список.Синоним</DataPath>
					<DefaultItem>true</DefaultItem>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Синоним</v8:content>
						</v8:item>
					</Title>
					<ContextMenu name="СинонимКонтекстноеМеню" id="5"/>
					<ExtendedTooltip name="СинонимExtendedTooltip" id="26"/>
				</LabelField>
				<LabelField name="ПолноеИмя" id="13">
					<DataPath>Список.ПолноеИмя</DataPath>
					<UserVisible>
						<xr:Common>false</xr:Common>
					</UserVisible>
					<ContextMenu name="ПолноеИмяКонтекстноеМеню" id="14"/>
					<ExtendedTooltip name="ПолноеИмяExtendedTooltip" id="27"/>
				</LabelField>
			</ChildItems>

	</ChildItems>
	<Attributes>
		<Attribute name="Список" id="1">
			<Type>
				<v8:Type>cfg:DynamicList</v8:Type>
			</Type>
			<MainAttribute>true</MainAttribute>
			<UseAlways>
				<Field>Список.Description</Field>
				<Field>1/28</Field>
				<Field>1/53</Field>
				<Field>Список.Parent</Field>
			</UseAlways>
			<Settings xsi:type="DynamicList">
				<ManualQuery>true</ManualQuery>
				<DynamicDataRead>true</DynamicDataRead>
				<QueryText>ВЫБРАТЬ
	Идентификаторы.Ссылка,
	Идентификаторы.ВерсияДанных,
	Идентификаторы.ПометкаУдаления,
	ВЫБОР
		КОГДА ПОДСТРОКА(Идентификаторы.Имя, 0, 7) = "Удалить"
			ТОГДА ИСТИНА
		ИНАЧЕ ЛОЖЬ
	КОНЕЦ КАК ПометкаБудущегоУдаления,
	Идентификаторы.Предопределенный,
	Идентификаторы.Родитель,
	Идентификаторы.Наименование,
	Идентификаторы.ПорядокКоллекции,
	Идентификаторы.Имя,
	Идентификаторы.Синоним,
	Идентификаторы.ПолноеИмя,
	Идентификаторы.ПолныйСиноним,
	Идентификаторы.БезДанных,
	Идентификаторы.ЗначениеПустойСсылки,
	Идентификаторы.КлючОбъектаМетаданных
ИЗ
	Справочник.ИдентификаторыОбъектовМетаданных КАК Идентификаторы</QueryText>
				<MainTable>Catalog.ИдентификаторыОбъектовМетаданных</MainTable>
				<ListSettings>
					<dcsset:filter>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>dfcece9d-5077-440b-b6b3-45a5cb4538eb</dcsset:userSettingID>
					</dcsset:filter>
					<dcsset:order>
						<dcsset:item xsi:type="dcsset:OrderItemField">
							<dcsset:field>ПометкаУдаления</dcsset:field>
							<dcsset:orderType>Desc</dcsset:orderType>
						</dcsset:item>
						<dcsset:item xsi:type="dcsset:OrderItemField">
							<dcsset:field>ПорядокКоллекции</dcsset:field>
							<dcsset:orderType>Asc</dcsset:orderType>
						</dcsset:item>
						<dcsset:item xsi:type="dcsset:OrderItemField">
							<dcsset:field>Родитель</dcsset:field>
							<dcsset:orderType>Asc</dcsset:orderType>
						</dcsset:item>
						<dcsset:item xsi:type="dcsset:OrderItemField">
							<dcsset:field>Синоним</dcsset:field>
							<dcsset:orderType>Asc</dcsset:orderType>
						</dcsset:item>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>88619765-ccb3-46c6-ac52-38e9c992ebd4</dcsset:userSettingID>
					</dcsset:order>
					<dcsset:conditionalAppearance>
						<dcsset:item>
							<dcsset:selection>
								<dcsset:item>
									<dcsset:field>Синоним</dcsset:field>
								</dcsset:item>
								<dcsset:item>
									<dcsset:field>ПолноеИмя</dcsset:field>
								</dcsset:item>
							</dcsset:selection>
							<dcsset:filter>
								<dcsset:item xsi:type="dcsset:FilterItemComparison">
									<dcsset:left xsi:type="dcscor:Field">ПометкаБудущегоУдаления</dcsset:left>
									<dcsset:comparisonType>Equal</dcsset:comparisonType>
									<dcsset:right xsi:type="xs:boolean">true</dcsset:right>
								</dcsset:item>
							</dcsset:filter>
							<dcsset:appearance>
								<dcscor:item xsi:type="dcsset:SettingsParameterValue">
									<dcscor:parameter>TextColor</dcscor:parameter>
									<dcscor:value xsi:type="v8ui:Color">web:DarkGray</dcscor:value>
								</dcscor:item>
							</dcsset:appearance>
						</dcsset:item>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>b75fecce-942b-4aed-abc9-e6a02e460fb3</dcsset:userSettingID>
					</dcsset:conditionalAppearance>
				</ListSettings>
			</Settings>
		</Attribute>
		<Attribute name="ВыбиратьГруппыОбъектовМетаданных" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Выбирать группы объектов метаданных</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
	</Attributes>
	<Commands>
		<Command name="ОбновитьДанныеСправочника" id="1">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Обновить данные справочника</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Обновить данные справочника по метаданным конфигурации</v8:content>
				</v8:item>
			</ToolTip>
			<Action>ОбновитьДанныеСправочника</Action>
		</Command>
	</Commands>
	<Parameters>
		<Parameter name="ВыбиратьГруппыОбъектовМетаданных">
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Parameter>
	</Parameters>
</Form>


text:
import sys
import IPython
import numpy
import scipy
import matplotlib
import networkx
import shapely
import doctest
import sphere
import SimPy
import pandas

b = eval(IPython.sys_info())
for k in b:
    print k, b[k]
print 'Python   : '   + str(sys.version)
print 'numpy    : '   + str(numpy.__version__)
print 'scipy    : '   + str(scipy.__version__)
print 'matplotlib : ' + str(matplotlib.__version__)
print 'networkx : '   + str(networkx.__version__)
print 'SImPy : '   + str(SimPy.__version__)
print 'Pandas : '   + str(pandas.__version__)