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

using Microsoft.Azure.Commands.Network.Models;
using System;
using System.Management.Automation;
using MNM = Microsoft.Azure.Management.Network.Models;

namespace Microsoft.Azure.Commands.Network
{
    [Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "IpsecPolicy"), OutputType(typeof(PSIpsecPolicy))]
    public class NewAzureRmIpsecPolicyCommand : NetworkBaseCmdlet
    {
        [Parameter(
            Mandatory = false,
            HelpMessage = "The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds")]
        [ValidateRange(300, 172799)]
        public int SALifeTimeSeconds { get; set; }

        [Parameter(
            Mandatory = false,
            HelpMessage = "The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB")]
        [ValidateRange(1024, int.MaxValue)]
        public int SADataSizeKilobytes { get; set; }

        [Parameter(
            Mandatory = true,
            HelpMessage = "The IPSec encryption algorithm (IKE Phase 1)")]
        [ValidateNotNullOrEmpty]
        [ValidateSet(
            MNM.IpsecEncryption.None,
            MNM.IpsecEncryption.DES,
            MNM.IpsecEncryption.DES3,
            MNM.IpsecEncryption.AES128,
            MNM.IpsecEncryption.AES192,
            MNM.IpsecEncryption.AES256,
            MNM.IpsecEncryption.GCMAES128,
            MNM.IpsecEncryption.GCMAES192,
            MNM.IpsecEncryption.GCMAES256,
            IgnoreCase = false)]
        public string IpsecEncryption { get; set; }

        [Parameter(
            Mandatory = true,
            HelpMessage = "The IPSec integrity algorithm (IKE Phase 1)")]
        [ValidateNotNullOrEmpty]
        [ValidateSet(
            MNM.IpsecIntegrity.MD5,
            MNM.IpsecIntegrity.SHA1,
            MNM.IpsecIntegrity.SHA256,
            MNM.IpsecEncryption.GCMAES128,
            MNM.IpsecEncryption.GCMAES192,
            MNM.IpsecEncryption.GCMAES256,
            IgnoreCase = false)]
        public string IpsecIntegrity { get; set; }

        [Parameter(
            Mandatory = true,
            HelpMessage = "The IKE encryption algorithm (IKE Phase 2)")]
        [ValidateNotNullOrEmpty]
        [ValidateSet(
            MNM.IkeEncryption.DES,
            MNM.IkeEncryption.DES3,
            MNM.IkeEncryption.AES128,
            MNM.IkeEncryption.AES192,
            MNM.IkeEncryption.AES256,
            IgnoreCase = false)]
        public string IkeEncryption { get; set; }

        [Parameter(
            Mandatory = true,
            HelpMessage = "The IKE integrity algorithm (IKE Phase 2)")]
        [ValidateNotNullOrEmpty]
        [ValidateSet(
            MNM.IkeIntegrity.MD5,
            MNM.IkeIntegrity.SHA1,
            MNM.IkeIntegrity.SHA256,
            MNM.IkeIntegrity.SHA384,
            IgnoreCase = false)]
        public string IkeIntegrity { get; set; }

        [Parameter(
            Mandatory = true,
            HelpMessage = "The DH Groups used in IKE Phase 1 for initial SA")]
        [ValidateNotNullOrEmpty]
        [ValidateSet(
            MNM.DhGroup.None,
            MNM.DhGroup.DHGroup1,
            MNM.DhGroup.DHGroup14,
            MNM.DhGroup.DHGroup2,
            MNM.DhGroup.DHGroup2048,
            MNM.DhGroup.DHGroup24,
            MNM.DhGroup.ECP256,
            MNM.DhGroup.ECP384,
            IgnoreCase = false)]
        public string DhGroup { get; set; }

        [Parameter(
            Mandatory = true,
            HelpMessage = "The DH Groups used in IKE Phase 2 for new child SA")]
        [ValidateNotNullOrEmpty]
        [ValidateSet(
            MNM.PfsGroup.None,
            MNM.PfsGroup.PFS1,
            MNM.PfsGroup.PFS2,
            MNM.PfsGroup.PFS2048,
            MNM.PfsGroup.PFS24,
            MNM.PfsGroup.ECP256,
            MNM.PfsGroup.ECP384,
            IgnoreCase = false)]
        public string PfsGroup { get; set; }

        public override void Execute()
        {
            base.Execute();
            var ipsecPolicy = new PSIpsecPolicy();

            // default SA values
            ipsecPolicy.SALifeTimeSeconds = (!this.MyInvocation.BoundParameters.ContainsKey("SALifeTimeSeconds")) ? 27000 : this.SALifeTimeSeconds;
            ipsecPolicy.SADataSizeKilobytes = (!this.MyInvocation.BoundParameters.ContainsKey("SADataSizeKilobytes")) ? 102400000 : this.SADataSizeKilobytes;

            // GCM matching check
            if ((this.IpsecEncryption.Contains("GCM") || this.IpsecIntegrity.Contains("GCM")) && this.IpsecEncryption != this.IpsecIntegrity)
            {
                throw new ArgumentException("IpsecEncryption and IpsecIntegrity must use matching GCM algorithms");
            }

            ipsecPolicy.IpsecEncryption = this.IpsecEncryption;
            ipsecPolicy.IpsecIntegrity = this.IpsecIntegrity;
            ipsecPolicy.IkeEncryption = this.IkeEncryption;
            ipsecPolicy.IkeIntegrity = this.IkeIntegrity;
            ipsecPolicy.DhGroup = this.DhGroup;
            ipsecPolicy.PfsGroup = this.PfsGroup;

            WriteObject(ipsecPolicy);
        }
    }
}


text:
def dictToObject(d):
    """
    Accepts a dictionary and returns an object with properties
    matching the keys and values from the original dict. If the
    key is not in the dict, returns the default given to the
    constructor (defaults to None).
    """
    class Container(object):

        def __init__(self, d, default=None):
            self._d = d
            self._default = None

        def __getitem__(self, *args, **kwargs):
            return object.__getattribute__(self, '_d')\
                    .__getitem__(*args, **kwargs)

        def __getattribute__(self, key, context=None):
            if key in [
                    'keys', 'iterkeys',
                    'values', 'itervalues'
                    'items', 'iteritems',
                    '__len__', '__eq__']:
                return getattr(object.__getattribute__(self, '_d'), key)

            value = object \
                .__getattribute__(self, context or '_d') \
                .get(
                    key,
                    object.__getattribute__(self, '_default')
                )
            if value and type(value) == type({}):
                return Container(value)
            return value

    return Container(d)

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var assert       = require( 'chai' ).assert,
    sinon        = require( 'sinon' ),
    BrowserSniff = require( '../lib/browser-detect' ),
    sniffer, emitterStub, success, failure;

suite( 'Browser Detection ::', function () {

    suiteSetup( function ( done ){
        sniffer     = new BrowserSniff();
        emitterStub = sinon.stub( sniffer , 'emit' );
        // success     = sinon.spy();
        // failure     = sinon.spy();

        emitterStub.withArgs( sniffer.events.success ).returns( [] );
        emitterStub.withArgs( sniffer.events.fail ).returns( false );

        done();
    });

    // setup( function ( done ){done();});

    // teardown( function ( done ){done();});

    suiteTeardown( function ( done ){
        emitterStub.restore();

        done();
    });

    test( 'Module has events exposed', function ( done ) {

        assert.isObject( sniffer.events , 'events is publicly exposed' );

        done();
    });

    test( 'Module has public methods to retrieve browser list', function ( done ) {

        assert.isFunction( sniffer.getBrowserData , 'getBrowserData is publicly exposed' );

        done();
    });

    test( 'Module has public methods to retrieve selected browser data', function ( done ) {

        assert.isFunction( sniffer.getBrowsers , 'getBrowsers is publicly exposed' );

        done();
    });

    test( 'Retuns browsers array on success', function ( done ) {

        assert.isArray( emitterStub( sniffer.events.success ) , 'success returns array');

        done();
    });

    // test( 'Returns error on fail', function ( done ) {
    //     // write tests
    //     done();
    // });
});

// public api:
//     events
//     getBrowserData
//     getBrowsers


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Reactive.Disposables;
using System.Reactive.Linq;

#if WINDOWS8
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif

namespace Microsoft.Reactive.Testing
{
    /// <summary>
    /// Helper class to write asserts in unit tests for applications and libraries built using Reactive Extensions.
    /// </summary>
    public static class ReactiveAssert
    {
        static string Message<T>(IEnumerable<T> actual, IEnumerable<T> expected)
        {
            var sb = new StringBuilder();
            sb.AppendLine();
            sb.Append("Expected: [");
            sb.Append(string.Join(", ", expected.Select(x => x.ToString()).ToArray()));
            sb.Append("]");
            sb.AppendLine();
            sb.Append("Actual..: [");
            sb.Append(string.Join(", ", actual.Select(x => x.ToString()).ToArray()));
            sb.Append("]");
            sb.AppendLine();
            return sb.ToString();
        }

        /// <summary>
        /// Asserts that both enumerable sequences have equal length and equal elements.
        /// </summary>
        /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
        /// <param name="expected">Expected sequence.</param>
        /// <param name="actual">Actual sequence to compare against the expected one.</param>
        /// <exception cref="ArgumentNullException"><paramref name="expected"/> or <paramref name="actual"/> is null.</exception>
        public static void AreElementsEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual)
        {
            if (expected == null)
                throw new ArgumentNullException("expected");
            if (actual == null)
                throw new ArgumentNullException("actual");

            if (!expected.SequenceEqual(actual))
                Assert.Fail(Message(actual, expected));
        }

        /// <summary>
        /// Asserts that both enumerable sequences have equal length and equal elements.
        /// </summary>
        /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
        /// <param name="expected">Expected sequence.</param>
        /// <param name="actual">Actual sequence to compare against the expected one.</param>
        /// <param name="message">Error message for assert failure.</param>
        /// <exception cref="ArgumentNullException"><paramref name="expected"/> or <paramref name="actual"/> is null.</exception>
        public static void AreElementsEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, string message)
        {
            if (expected == null)
                throw new ArgumentNullException("expected");
            if (actual == null)
                throw new ArgumentNullException("actual");

            if (!expected.SequenceEqual(actual))
                Assert.Fail(message);
        }

        /// <summary>
        /// Asserts that both observable sequences have equal length and equal notifications.
        /// </summary>
        /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
        /// <param name="expected">Expected sequence.</param>
        /// <param name="actual">Actual sequence to compare against the expected one.</param>
        /// <exception cref="ArgumentNullException"><paramref name="expected"/> or <paramref name="actual"/> is null.</exception>
        public static void AreElementsEqual<T>(IObservable<T> expected, IObservable<T> actual)
        {
            if (expected == null)
                throw new ArgumentNullException("expected");
            if (actual == null)
                throw new ArgumentNullException("actual");

            AreElementsEqual(expected.Materialize().ToEnumerable(), actual.Materialize().ToEnumerable());
        }

        /// <summary>
        /// Asserts that both observable sequences have equal length and equal elements.
        /// </summary>
        /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
        /// <param name="expected">Expected sequence.</param>
        /// <param name="actual">Actual sequence to compare against the expected one.</param>
        /// <param name="message">Error message for assert failure.</param>
        /// <exception cref="ArgumentNullException"><paramref name="expected"/> or <paramref name="actual"/> is null.</exception>
        public static void AreElementsEqual<T>(IObservable<T> expected, IObservable<T> actual, string message)
        {
            if (expected == null)
                throw new ArgumentNullException("expected");
            if (actual == null)
                throw new ArgumentNullException("actual");

            AreElementsEqual(expected.Materialize().ToEnumerable(), actual.Materialize().ToEnumerable(), message);
        }

        /// <summary>
        /// Asserts that the given action throws an exception of the type specified in the generic parameter, or a subtype thereof.
        /// </summary>
        /// <typeparam name="TException">Type of the exception to check for.</typeparam>
        /// <param name="action">Action to run.</param>
        /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
        public static void Throws<TException>(Action action) where TException : Exception
        {
            if (action == null)
                throw new ArgumentNullException("action");

            var failed = false;
            try
            {
                action();
                failed = true;
            }
            catch (TException)
            {
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format(CultureInfo.CurrentCulture, "Expected {0} threw {1}.\r\n\r\nStack trace:\r\n{2}", typeof(TException).Name, ex.GetType().Name, ex.StackTrace));
            }

            if (failed)
                Assert.Fail(string.Format(CultureInfo.CurrentCulture, "Expected {0}.", typeof(TException).Name));
        }

        /// <summary>
        /// Asserts that the given action throws an exception of the type specified in the generic parameter, or a subtype thereof.
        /// </summary>
        /// <typeparam name="TException">Type of the exception to check for.</typeparam>
        /// <param name="action">Action to run.</param>
        /// <param name="message">Error message for assert failure.</param>
        /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
        public static void Throws<TException>(Action action, string message) where TException : Exception
        {
            if (action == null)
                throw new ArgumentNullException("action");

            var failed = false;
            try
            {
                action();
                failed = true;
            }
            catch (TException)
            {
            }
            catch
            {
                Assert.Fail(message);
            }

            if (failed)
                Assert.Fail(message);
        }

        /// <summary>
        /// Asserts that the given action throws the specified exception.
        /// </summary>
        /// <typeparam name="TException">Type of the exception to check for.</typeparam>
        /// <param name="exception">Exception to assert being thrown.</param>
        /// <param name="action">Action to run.</param>
        /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
        public static void Throws<TException>(TException exception, Action action) where TException : Exception
        {
            if (action == null)
                throw new ArgumentNullException("action");

            var failed = false;
            try
            {
                action();
                failed = true;
            }
            catch (TException ex)
            {
                Assert.AreSame(exception, ex);
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format(CultureInfo.CurrentCulture, "Expected {0} threw {1}.\r\n\r\nStack trace:\r\n{2}", typeof(TException).Name, ex.GetType().Name, ex.StackTrace));
            }

            if (failed)
                Assert.Fail(string.Format(CultureInfo.CurrentCulture, "Expected {0}.", typeof(TException).Name));
        }

        /// <summary>
        /// Asserts that the given action throws the specified exception.
        /// </summary>
        /// <typeparam name="TException">Type of the exception to check for.</typeparam>
        /// <param name="exception">Exception to assert being thrown.</param>
        /// <param name="action">Action to run.</param>
        /// <param name="message">Error message for assert failure.</param>
        /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
        public static void Throws<TException>(TException exception, Action action, string message) where TException : Exception
        {
            if (action == null)
                throw new ArgumentNullException("action");

            var failed = false;
            try
            {
                action();
                failed = true;
            }
            catch (TException ex)
            {
                Assert.AreSame(exception, ex);
            }
            catch
            {
                Assert.Fail(message);
            }

            if (failed)
                Assert.Fail(message);
        }

        /// <summary>
        /// Asserts that both enumerable sequences have equal length and equal elements.
        /// </summary>
        /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
        /// <param name="actual">Actual sequence to compare against the expected one.</param>
        /// <param name="expected">Expected sequence.</param>
        /// <exception cref="ArgumentNullException"><paramref name="expected"/> or <paramref name="actual"/> is null.</exception>
        public static void AssertEqual<T>(this IEnumerable<T> actual, IEnumerable<T> expected)
        {
            if (actual == null)
                throw new ArgumentNullException("actual");
            if (expected == null)
                throw new ArgumentNullException("expected");

            ReactiveAssert.AreElementsEqual(expected, actual);
        }

        /// <summary>
        /// Asserts the enumerable sequence has the expected elements.
        /// </summary>
        /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
        /// <param name="actual">Actual sequence to compare against the expected elements.</param>
        /// <param name="expected">Expected elements.</param>
        /// <exception cref="ArgumentNullException"><paramref name="expected"/> or <paramref name="actual"/> is null.</exception>
        public static void AssertEqual<T>(this IEnumerable<T> actual, params T[] expected)
        {
            if (actual == null)
                throw new ArgumentNullException("actual");
            if (expected == null)
                throw new ArgumentNullException("expected");

            ReactiveAssert.AreElementsEqual(expected, actual);
        }

        /// <summary>
        /// Asserts that both observable sequences have equal length and equal notifications.
        /// </summary>
        /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
        /// <param name="actual">Actual sequence to compare against the expected one.</param>
        /// <param name="expected">Expected sequence.</param>
        /// <exception cref="ArgumentNullException"><paramref name="expected"/> or <paramref name="actual"/> is null.</exception>
        public static void AssertEqual<T>(this IObservable<T> actual, IObservable<T> expected)
        {
            if (actual == null)
                throw new ArgumentNullException("actual");
            if (expected == null)
                throw new ArgumentNullException("expected");

            ReactiveAssert.AreElementsEqual(expected, actual);
        }
    }
}


text:
class Protor
  class Entry
    attr_reader :name, :type, :value, :labels, :additional
    attr_writer :value

    VALID_NAME        = /^[a-zA-Z_:][a-zA-Z0-9_:]+$/
    VALID_TYPE        = [:c, :g, :h]
    VALID_LABEL_NAME  = /^[a-zA-Z_][a-zA-Z0-9_]*$/
    VALID_LABEL_VALUE = /^[^;|=]+$/

    def initialize(name, type, value, labels = nil, additional = nil)
      @name       = name.to_s
      @type       = type
      @value      = value
      @labels     = labels || {}
      @additional = additional || []

      verify
    end

    private

    def verify
      raise InvalidNameError, name unless name =~ VALID_NAME
      raise InvalidTypeError, type unless VALID_TYPE.include?(type)
      labels.each do |k, v|
        raise InvalidLabelNameError, labels unless k =~ VALID_LABEL_NAME
        raise InvalidLabelValueError, labels unless v =~ VALID_LABEL_VALUE
      end
      additional.each do |a|
        raise InvalidAdditionalError, additional unless a.is_a?(Numeric)
      end
    end

  end

  class InvalidNameError < StandardError
    def initialize(message)
      super("Invalid name #{message}, please satisfy /^[a-zA-Z_:][a-zA-Z0-9_:]+$/")
    end
  end

  class InvalidTypeError < StandardError
    def initialize(message)
      super("Invalid type #{message}, allowed types are [c, g, h]")
    end
  end

  class InvalidLabelNameError < StandardError
    def initialize(message)
      super("Invalid label name #{message}, please satisfy /^[a-zA-Z_][a-zA-Z0-9_]*$/")
    end
  end

  class InvalidLabelValueError < StandardError
    def initialize(message)
      super("Invalid label value #{message}, please satisfy /^[^;|=\s]+$/")
    end
  end

  class InvalidAdditionalError < StandardError
    def initialize(message)
      super("Invalid additional {message}, additional must be numbers")
    end
  end
end


text:
#region License Header

#endregion License Header

using System;

namespace Quantler.Indicators
{
    /// <summary>
    /// Produces a Hull Moving Average as explained at http://www.alanhull.com/hull-moving-average/
    /// and derived from the instructions for the Excel VBA code at http://finance4traders.blogspot.com/2009/06/how-to-calculate-hull-moving-average.html
    /// </summary>
    public class HullMovingAverage : IndicatorBase<IndicatorDataPoint>
    {
        #region Private Fields

        private readonly LinearWeightedMovingAverage _fastWma;
        private readonly LinearWeightedMovingAverage _hullMa;
        private readonly LinearWeightedMovingAverage _slowWma;

        #endregion Private Fields

        #region Public Constructors

        /// <summary>
        /// A Hull Moving Average
        /// </summary>
        /// <param name="name">string - a name for the indicator</param>
        /// <param name="period">int - the number of periods to calculate the HMA - the period of the slower LWMA</param>
        public HullMovingAverage(string name, int period)
            : base(name)
        {
            if (period < 2) throw new ArgumentException("The Hull Moving Average period should be greater or equal to 2", "period");
            _slowWma = new LinearWeightedMovingAverage(period);
            _fastWma = new LinearWeightedMovingAverage((int)Math.Round(period * 1d / 2));
            var k = (int)Math.Round(Math.Sqrt(period));
            _hullMa = new LinearWeightedMovingAverage(k);
        }

        /// <summary>
        /// A Hull Moving Average.
        /// </summary>
        /// <param name="period">int - the number of periods over which to calculate the HMA - the length of the slower LWMA</param>
        public HullMovingAverage(int period)
            : this("HMA" + period, period)
        {
        }

        #endregion Public Constructors

        #region Public Properties

        /// <summary>
        /// Gets a flag indicating when this indicator is ready and fully initialized
        /// </summary>
        public override bool IsReady =>
            _hullMa.IsReady;

        #endregion Public Properties

        #region Public Methods

        /// <summary>
        /// Resets this indicator to its initial state
        /// </summary>
        public override void Reset()
        {
            base.Reset();
            _slowWma.Reset();
            _fastWma.Reset();
            _hullMa.Reset();
        }

        #endregion Public Methods

        #region Protected Methods

        /// <summary>
        /// Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>
        /// A new value for this indicator
        /// </returns>
        protected override decimal ComputeNextValue(IndicatorDataPoint input)
        {
            _fastWma.Update(input);
            _slowWma.Update(input);
            _hullMa.Update(new IndicatorDataPoint(input.Occured, input.TimeZone, 2 * _fastWma.Current.Price - _slowWma.Current.Price));
            return _hullMa.Current.Price;
        }

        #endregion Protected Methods
    }
}


text:
require_relative "../ec2-ruby-example-get-all-instance-info"

describe "#list_instance_ids_states" do
  let(:ec2_client) do
    Aws::EC2::Client.new(
      stub_responses: {
        describe_instances: {
          reservations: [
            instances: [
              { instance_id: "i-abc123-1", state: { name: "running" } },
              { instance_id: "i-abc123-2", state: { name: "running" } },
              { instance_id: "i-abc123-3", state: { name: "running" } }
            ]
          ]
        }
      }
    )
  end
  let(:ec2_resource) { Aws::EC2::Resource.new(client: ec2_client) }

  it "lists instance IDs and states" do
    expect { list_instance_ids_states(ec2_resource) }.not_to raise_error
  end
end


text:
babeljs
interntjs
systemjs
gulpjs# 5to6-learing


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revue mycol. , Toulouse 1: 9 (1879)

#### Original name
Xerocarpus cinereus var. cervinus Thüm.

### Remarks
null


text:
/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

/** @file
    		GUI Edit Box Management.
    @author	Eric Espie
    @version	$Id: guiedit.cpp,v 1.2.2.2 2008/12/31 03:53:55 berniw Exp $
    @ingroup	gui
*/

#include <stdlib.h>
#ifdef WIN32
#include <windows.h>
#endif
#include <tgfclient.h>
#include "gui.h"
#include "guifont.h"

void
gfuiEditboxInit(void)
{
}

/** Add a editbox to a screen.
    @ingroup	gui
    @param	scr		Screen
    @param	text		Editbox start text
    @param	font		Font id
    @param	x		X position on screen
    @param	y		Y position on screen (0 = bottom)
    @param	width		width of the editbox (0 = text size)
    @param	maxlen		Max lenght of text (0 = text size)
    @param	userDataOnFocus	Parameter to the Focus (and lost) callback
    @param	onFocus		Focus callback function
    @param	onFocusLost	Focus Lost callback function
    @return	Editbox Id

-1 Error
 */
int
GfuiEditboxCreate(void *scr, const char *text, int font, int x, int y, int width, int maxlen,
		  void *userDataOnFocus, tfuiCallback onFocus, tfuiCallback onFocusLost)
{
	tGfuiEditbox *editbox;
	tGfuiLabel *label;
	tGfuiObject *object;
	tGfuiScreen *screen = (tGfuiScreen*)scr;

	object = (tGfuiObject*)calloc(1, sizeof(tGfuiObject));
	object->widget = GFUI_EDITBOX;
	object->focusMode = GFUI_FOCUS_MOUSE_CLICK;
	object->id = screen->curId++;
	object->visible = 1;

	editbox = &(object->u.editbox);
	editbox->state = GFUI_BTN_RELEASED;
	editbox->userDataOnFocus = userDataOnFocus;
	editbox->onFocus = onFocus;
	editbox->onFocusLost = onFocusLost;

	editbox->bgColor[0] = &(GfuiColor[GFUI_BGBTNDISABLED][0]);
	editbox->bgColor[1] = &(GfuiColor[GFUI_BGBTNENABLED][0]);
	editbox->bgColor[2] = &(GfuiColor[GFUI_BGBTNCLICK][0]);
	editbox->bgFocusColor[0] = &(GfuiColor[GFUI_BGBTNDISABLED][0]);
	editbox->bgFocusColor[1] = &(GfuiColor[GFUI_BGBTNFOCUS][0]);
	editbox->bgFocusColor[2] = &(GfuiColor[GFUI_BGBTNCLICK][0]);
	editbox->fgColor[0] = &(GfuiColor[GFUI_BTNDISABLED][0]);
	editbox->fgColor[1] = &(GfuiColor[GFUI_BTNENABLED][0]);
	editbox->fgColor[2] = &(GfuiColor[GFUI_BTNCLICK][0]);
	editbox->fgFocusColor[0] = &(GfuiColor[GFUI_BTNDISABLED][0]);
	editbox->fgFocusColor[1] = &(GfuiColor[GFUI_BTNFOCUS][0]);
	editbox->fgFocusColor[2] = &(GfuiColor[GFUI_BTNCLICK][0]);
	editbox->cursorColor[0] = &(GfuiColor[GFUI_EDITCURSORCLR][0]);
	editbox->cursorColor[1] = &(GfuiColor[GFUI_EDITCURSORCLR][1]);
	editbox->cursorColor[2] = &(GfuiColor[GFUI_EDITCURSORCLR][2]);

	label = &(editbox->label);
	if (maxlen == 0) maxlen = strlen(text);
	label->text = (char*)calloc(1, maxlen+1);
	strncpy(label->text, text, maxlen+1);
	label->font = gfuiFont[font];
	label->maxlen = maxlen;

	if (width == 0) {
		char *buf;
		int  i;
		buf = (char*)malloc(maxlen+1);
		if (buf == NULL) return -1;
		for (i = 0; i < maxlen; i++) buf[i] = 'W';
		buf[i] = '\0';
		width = gfuiFont[font]->getWidth((const char *)buf);
		free(buf);
	}

	label->align = GFUI_ALIGN_HL_VC;
	label->x = object->xmin = x;
	label->y = y - 2 * gfuiFont[font]->getDescender();
	object->ymin = y;
	object->xmax = x + width;
	object->ymax = y + gfuiFont[font]->getHeight() - gfuiFont[font]->getDescender();
	editbox->cursory1 = object->ymin + 2;
	editbox->cursory2 = object->ymax - 2;
	editbox->cursorx = label->x;

#define HORIZ_MARGIN 10
	object->xmin -= HORIZ_MARGIN;
	object->xmax += HORIZ_MARGIN;

	gfuiAddObject(screen, object);
	return object->id;
}

/** Get the Id of the editbox focused in the current screen.
    @ingroup	gui
    @return	Editbox Id

-1 if no editbox or no screen or the focus is not on a editbox
 */
int
GfuiEditboxGetFocused(void)
{
    tGfuiObject *curObject;

    if (GfuiScreen != NULL) {
	curObject = GfuiScreen->objects;
	if (curObject != NULL) {
	    do {
		curObject = curObject->next;
		if (curObject->focus) {
		    if (curObject->widget == GFUI_EDITBOX) {
			return curObject->id;
		    }
		    return -1;
		}
	    } while (curObject != GfuiScreen->objects);
	}
    }
    return -1;
}

void
gfuiDrawEditbox(tGfuiObject *obj)
{
    tGfuiLabel		*label;
    tGfuiEditbox	*editbox;
    float		*fgColor;
    float		*bgColor;

    editbox = &(obj->u.editbox);
    if (obj->state == GFUI_DISABLE) {
	editbox->state = GFUI_BTN_DISABLE;
    } else {
	editbox->state = GFUI_BTN_RELEASED;
    }
    if (obj->focus) {
	fgColor = editbox->fgFocusColor[editbox->state];
	bgColor = editbox->bgFocusColor[editbox->state];
    } else {
	fgColor = editbox->fgColor[editbox->state];
	bgColor = editbox->bgColor[editbox->state];
    }

    glColor4fv(bgColor);
    glBegin(GL_QUADS);
    glVertex2i(obj->xmin, obj->ymin);
    glVertex2i(obj->xmin, obj->ymax);
    glVertex2i(obj->xmax, obj->ymax);
    glVertex2i(obj->xmax, obj->ymin);
    glEnd();

    glColor4fv(fgColor);
    glBegin(GL_LINE_STRIP);
    glVertex2i(obj->xmin, obj->ymin);
    glVertex2i(obj->xmin, obj->ymax);
    glVertex2i(obj->xmax, obj->ymax);
    glVertex2i(obj->xmax, obj->ymin);
    glVertex2i(obj->xmin, obj->ymin);
    glEnd();

    label = &(editbox->label);
    glColor4fv(fgColor);
    gfuiPrintString(label->x, label->y, label->font, label->text);

    if ((obj->state != GFUI_DISABLE) && (obj->focus)) {
	/* draw cursor */
	glColor3fv(editbox->cursorColor[editbox->state]);
	glBegin(GL_LINES);
	glVertex2i(editbox->cursorx, editbox->cursory1);
	glVertex2i(editbox->cursorx, editbox->cursory2);
	glEnd();
    }
}

void
gfuiEditboxAction(int mouse)
{
    tGfuiObject		*object;
    tGfuiLabel		*label;
    tGfuiEditbox	*editbox;
    int			relX;
    char		buf[256];
    uint		i;

    object = GfuiScreen->hasFocus;
    if (object->state == GFUI_DISABLE) {
	return;
    }

    if (mouse == 2) { /* enter key */
	gfuiSelectNext(GfuiScreen);
    } else if (mouse == 0) { /* mouse down */
	editbox = &(object->u.editbox);
	label = &(editbox->label);
	/* Set the cursor position */
	relX = GfuiMouse.X - label->x;
	for (i = 0; i < strlen(label->text); i++){
	    buf[i] = label->text[i];
	    buf[i+1] = '\0';
	    if (relX font->getWidth((const char *)buf)) {
		break;
	    }
	}
	editbox->cursorIdx = i;
	if (i == 0) {
	    editbox->cursorx = label->x;
	} else {
	    buf[i] = '\0';
	    editbox->cursorx = label->x + label->font->getWidth((const char *)buf);
	}
    }
}

/* recalc cursorx with cursorIdx */
static void
gfuiEditboxRecalcCursor(tGfuiObject *obj)
{
    char		buf[256];
    tGfuiEditbox	*editbox;
    tGfuiLabel		*label;

    editbox = &(obj->u.editbox);
    label = &(editbox->label);
    strncpy(buf, label->text, editbox->cursorIdx);
    buf[editbox->cursorIdx] = '\0';
    editbox->cursorx = label->x + label->font->getWidth((const char *)buf);
}

void
gfuiEditboxKey(tGfuiObject *obj, int key, int modifier)
{
    tGfuiEditbox	*editbox;
    tGfuiLabel		*label;
    char		*p1, *p2;
    int			i1, i2;

    if (obj->state == GFUI_DISABLE) {
	return;
    }

    editbox = &(obj->u.editbox);
    label = &(editbox->label);

    switch (modifier) {
    case 0:
    case GLUT_ACTIVE_SHIFT:
	switch (key) {
	case 256 + GLUT_KEY_RIGHT:
	    editbox->cursorIdx++;
	    if (editbox->cursorIdx > (int)strlen(label->text)) {
		editbox->cursorIdx--;
	    }
	    break;
	case 256 + GLUT_KEY_LEFT:
	    editbox->cursorIdx--;
	    if (editbox->cursorIdx < 0) {
		editbox->cursorIdx = 0;
	    }
	    break;
	case 256 + GLUT_KEY_HOME:
	    editbox->cursorIdx = 0;
	    break;
	case 256 + GLUT_KEY_END:
	    editbox->cursorIdx = (int)strlen(label->text);
	    break;
	case 0x7F : /* DEL */
	    if (editbox->cursorIdx < (int)strlen(label->text)) {
		p1 = &(label->text[editbox->cursorIdx]);
		p2 = &(label->text[editbox->cursorIdx+1]);
		while ( *p1 != '\0' ) {
		    *p1++ = *p2++;
		}
	    }
	    break;
	case '\b' : /* Backspace */
	    if (editbox->cursorIdx > 0) {
		p1 = &(label->text[editbox->cursorIdx-1]);
		p2 = &(label->text[editbox->cursorIdx]);
		while ( *p1 != '\0' ) {
		    *p1++ = *p2++;
		}
		editbox->cursorIdx--;
	    }
	    break;
	}
	if (key >= ' ' && key < 127) {
	    if ((int)strlen(label->text) maxlen) {
		i2 = (int)strlen(label->text) + 1;
		i1 = i2 - 1;
		while (i2 > editbox->cursorIdx) {
		    label->text[i2] = label->text[i1];
		    i1--;
		    i2--;
		}
		label->text[editbox->cursorIdx] = key;
		editbox->cursorIdx++;
	    }
	}
	break;

    case GLUT_ACTIVE_CTRL:
	break;

    case GLUT_ACTIVE_ALT:
	break;
    }

    gfuiEditboxRecalcCursor(obj);
}

/** Get the string
    @ingroup	gui
     @param	scr		Screen
    @param	id		Edit box Id
    @return	Corresponding string.
 */
char *
GfuiEditboxGetString(void *scr, int id)
{
    tGfuiObject		*curObject;
    tGfuiEditbox	*editbox;
    tGfuiLabel		*label;

    curObject = gfuiGetObject(scr, id);

    if ((curObject == NULL) || (curObject->widget != GFUI_EDITBOX)) {
	return (char*)NULL;
    }

    editbox = &(curObject->u.editbox);
    label = &(editbox->label);

    return label->text;
}

/** Set a new string.
    @ingroup	gui
    @param	scr		Screen
    @param	id		Edit box Id
    @param	text		text to set
    @return	none
 */
void GfuiEditboxSetString(void *scr, int id, const char *text)
{
	tGfuiObject *curObject;
	tGfuiEditbox *editbox;
	tGfuiLabel *label;

	curObject = gfuiGetObject(scr, id);

	if ((curObject == NULL) || (curObject->widget != GFUI_EDITBOX)) {
		return;
	}

	editbox = &(curObject->u.editbox);
	label = &(editbox->label);

	strncpy(label->text, text, label->maxlen);
}

void
gfuiReleaseEditbox(tGfuiObject *curObject)
{
    tGfuiEditbox	*editbox;
    tGfuiLabel		*label;

    editbox = &(curObject->u.editbox);
    label = &(editbox->label);
    free(label->text);
    free(curObject);
}


text:
package com.gemstone.gemfire.internal.cache.persistence.soplog;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Provides default behavior for range scans.
 *
 * @author bakera
 */
public abstract class AbstractSortedReader implements SortedReader<ByteBuffer> {
  @Override
  public final SortedIterator<ByteBuffer> scan() throws IOException {
    return scan(null, true, null, true);
  }

  @Override
  public final SortedIterator<ByteBuffer> head(byte[] to, boolean inclusive)  throws IOException{
    return scan(null, true, to, inclusive);
  }

  @Override
  public final SortedIterator<ByteBuffer> tail(byte[] from, boolean inclusive)  throws IOException{
    return scan(from, inclusive, null, true);
  }

  @Override
  public final SortedIterator<ByteBuffer> scan(byte[] from, byte[] to)  throws IOException{
    return scan(from, true, to, false);
  }

  @Override
  public final SortedIterator<ByteBuffer> scan(byte[] equalTo)  throws IOException{
    return scan(equalTo, true, equalTo, true);
  }

  @Override
  public SortedIterator<ByteBuffer> scan(byte[] from, boolean fromInclusive, byte[] to,
      boolean toInclusive)  throws IOException{
    return scan(from, fromInclusive, to, toInclusive, true, null);
  }

  @Override
  public final SortedReader<ByteBuffer> withAscending(boolean ascending) {
    if (this instanceof DelegateSortedReader) {
      DelegateSortedReader tmp = (DelegateSortedReader) this;
      return new DelegateSortedReader(tmp.delegate, ascending, tmp.filter);
    }
    return new DelegateSortedReader(this, ascending, null);
  }

  @Override
  public final SortedReader<ByteBuffer> withFilter(MetadataFilter filter) {
    if (this instanceof DelegateSortedReader) {
      DelegateSortedReader tmp = (DelegateSortedReader) this;
      return new DelegateSortedReader(tmp.delegate, tmp.ascending, filter);
    }
    return new DelegateSortedReader(this, true, filter);
  }

  protected class DelegateSortedReader extends AbstractSortedReader {
    /** the embedded reader */
    private final AbstractSortedReader delegate;

    /** true if ascending */
    private final boolean ascending;

    /** the filter */
    private final MetadataFilter filter;

    public DelegateSortedReader(AbstractSortedReader reader, boolean ascending, MetadataFilter filter) {
      this.delegate = reader;
      this.ascending = ascending;
      this.filter = filter;
    }

    @Override
    public boolean mightContain(byte[] key) throws IOException {
      return delegate.mightContain(key);
    }

    @Override
    public ByteBuffer read(byte[] key) throws IOException {
      return delegate.read(key);
    }

    @Override
    public SerializedComparator getComparator() {
      return delegate.getComparator();
    }

    @Override
    public SortedStatistics getStatistics() throws IOException {
      return delegate.getStatistics();
    }

    @Override
    public void close() throws IOException {
      delegate.close();
    }

    @Override
    public SortedIterator<ByteBuffer> scan(
        byte[] from, boolean fromInclusive,
        byte[] to, boolean toInclusive) throws IOException {
      return scan(from, fromInclusive, to, toInclusive, ascending, filter);
    }

    @Override
    public SortedIterator<ByteBuffer> scan(
        byte[] from, boolean fromInclusive,
        byte[] to, boolean toInclusive,
        boolean ascending,
        MetadataFilter filter) throws IOException {
      return delegate.scan(from, fromInclusive, to, toInclusive, ascending, filter);
    }
  }
}


text:
<?php
/*
 * This work is hereby released into the Public Domain.
 * To view a copy of the public domain dedication,
 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
 *
 */

require_once dirname(__FILE__)."/../Driver.class.php";

/**
 * Draw your objects
 *
 * @package Artichow
 */
class awMingDriver extends awDriver {

	/**
	 * The Flash movie
	 *
	 * @var $movie
	 */
	public $movie;

	public function __construct() {

		parent::__construct();

		$this->driverString = 'ming';

		// Nice defaults
		ming_setScale(20.0);
		ming_useswfversion(6);

	}

	/**
	 * Initialize the driver for a particular awImage object
	 *
	 * @param awImage $image
	 */
	public function init(awImage $image) {

		if ($this->movie === NULL) {
			$this->setImageSize($image->width, $image->height);

			// Create movie
			$this->movie = new SWFMovie();
			if (!$this->movie) {
				awImage::drawError("Class Image: Unable to create a graph.");
			}

			$this->movie->setDimension($image->width, $image->height);

			$this->setAntiAliasing($image->getAntiAliasing());

			// Original color
			$this->filledRectangle(
				new awWhite,
				new awLine(
					new awPoint(0, 0),
					new awPoint($this->imageWidth, $this->imageHeight)
				)
			);

			$shadow = $image->shadow;
			if ($shadow !== NULL) {
				$shadow = $shadow->getSpace();
				$p1 = new awPoint($shadow->left, $shadow->top);
				$p2 = new awPoint($this->imageWidth - $shadow->right - 1, $this->imageHeight - $shadow->bottom - 1);

				// Draw image background
				$this->filledRectangle($image->getBackground(), new awLine($p1, $p2));

				// Draw image border
				$image->border->rectangle($this, $p1, $p2);
			}
		}
	}

	/**
	 * Initialize the Driver for a particular FileImage object
	 *
	 * @param awFileImage $fileImage The FileImage object to work on
	 * @param string $file Image filename
	 */
	public function initFromFile(awFileImage $fileImage, $file) {

	}

	/**
	 * Change the image size
	 *
	 * @param int $width Image width
	 * @param int $height Image height
	 */
	public function setImageSize($width, $height) {
		$this->imageWidth = $width;
		$this->imageHeight = $height;
	}

	/**
	 * Inform the driver of the position of your image
	 *
	 * @param float $x Position on X axis of the center of the component
	 * @param float $y Position on Y axis of the center of the component
	 */
	public function setPosition($x, $y) {
		// Calculate absolute position
		$this->x = round($x * $this->imageWidth - $this->w / 2);
		$this->y = round($y * $this->imageHeight - $this->h / 2);
	}

	/**
	 * Inform the driver of the position of your image
	 * This method need absolutes values
	 *
	 * @param int $x Left-top corner X position
	 * @param int $y Left-top corner Y position
	 */
	public function setAbsPosition($x, $y) {
		$this->x = $x;
		$this->y = $y;
	}

	/**
	 * Move the position of the image
	 *
	 * @param int $x Add this value to X axis
	 * @param int $y Add this value to Y axis
	 */
	public function movePosition($x, $y) {
		$this->x += (int)$x;
		$this->y += (int)$y;
	}

	/**
	 * Inform the driver of the size of your image
	 * Height and width must be between 0 and 1.
	 *
	 * @param int $w Image width
	 * @param int $h Image height
	 * @return array Absolute width and height of the image
	 */
	public function setSize($w, $h) {

		// Calcul absolute size
		$this->w = round($w * $this->imageWidth);
		$this->h = round($h * $this->imageHeight);

		return $this->getSize();

	}

	/**
	 * Inform the driver of the size of your image
	 * You can set absolute size with this method.
	 *
	 * @param int $w Image width
	 * @param int $h Image height
	 */
	public function setAbsSize($w, $h) {
		$this->w = $w;
		$this->h = $h;

		return $this->getSize();
	}

	/**
	 * Get the size of the component handled by the driver
	 *
	 * @return array Absolute width and height of the component
	 */
	public function getSize() {
		return array($this->w, $this->h);
	}

	/**
	 * Turn antialiasing on or off
	 *
	 * @var bool $bool
	 */
	public function setAntiAliasing($bool) {
		if ($this->movie !== NULL) {

			$actionscript = '
			_quality = "%s";
			';

			if ((bool)$bool) {
				$actionscript = sprintf($actionscript, 'high');
			} else {
				$actionscript = sprintf($actionscript, 'low');
			}

			$this->movie->add(new SWFAction(str_replace("\r", "", $actionscript)));
		}
	}

	/**
	 * When passed a Color object, returns the corresponding
	 * color identifier (driver dependant).
	 *
	 * @param awColor $color A Color object
	 * @return array $rgba A color identifier representing the color composed of the given RGB components
	 */
	public function getColor(awColor $color) {

		// Ming simply works with R, G, B and Alpha values.
		list($red, $green, $blue, $alpha) = $color->rgba();

		// However, the Ming alpha channel ranges from 255 (opaque) to 0 (transparent),
		// while the awColor alpha channel ranges from 0 (opaque) to 100 (transparent).
		// First, we convert from 0-100 to 0-255.
		$alpha = (int)($alpha * 255 / 100);

		// Then from 0-255 to 255-0.
		$alpha = abs($alpha - 255);

		return array($red, $green, $blue, $alpha);
	}

	/**
	 * Draw an image here
	 *
	 * @param awImage $image Image
	 * @param int $p1 Image top-left point
	 * @param int $p2 Image bottom-right point
	 */
	public function copyImage(awImage $image, awPoint $p1, awPoint $p2) {

	}

	/**
	 * Draw an image here
	 *
	 * @param awImage $image Image
	 * @param int $d1 Destination top-left position
	 * @param int $d2 Destination bottom-right position
	 * @param int $s1 Source top-left position
	 * @param int $s2 Source bottom-right position
	 * @param bool $resample Resample image ? (default to TRUE)
	 */
	public function copyResizeImage(awImage $image, awPoint $d1, awPoint $d2, awPoint $s1, awPoint $s2, $resample = TRUE) {

	}

	/**
	 * Draw a string
	 *
	 * @var awText $text Text to print
	 * @param awPoint $point Draw the text at this point
	 * @param int $width Text max width
	 */
	public function string(awText $text, awPoint $point, $width = NULL) {
		$font = $text->getFont();

		// Can we deal with that font?
		if ($this->isCompatibleWithFont($font) === FALSE) {
			awImage::drawError('Class MingDriver: Incompatible font type (\''.get_class($font).'\')');
		}

		// Ming can only work with awFileFont objects for now
		// (i.e. awFDBFont, or awTuffy et al.)
		$fontDriver = $this->fileFontDriver;

		if ($text->getBackground() !== NULL or $text->border->visible()) {

			list($left, $right, $top, $bottom) = $text->getPadding();

			$textWidth = $fontDriver->getTextWidth($text, $this);
			$textHeight = $fontDriver->getTextHeight($text, $this);

			$x1 = floor($point->x - $left);
			$y1 = floor($point->y - $top);
			$x2 = $x1 + $textWidth + $left + $right;
			$y2 = $y1 + $textHeight + $top + $bottom;

			$this->filledRectangle(
				$text->getBackground(),
				awLine::build($x1, $y1, $x2, $y2)
			);

			$text->border->rectangle(
				$this,
				new awPoint($x1 - 1, $y1 - 1),
				new awPoint($x2 + 1, $y2 + 1)
			);

		}

		$fontDriver->string($this, $text, $point, $width);
	}

	/**
	 * Draw a pixel
	 *
	 * @param awColor $color Pixel color
	 * @param awPoint $p
	 */
	public function point(awColor $color, awPoint $p) {
		if ($p->isHidden() === FALSE) {
			list($red, $green, $blue, $alpha) = $this->getColor($color);

			$point = new SWFShape();
			$point->setLine(1, $red, $green, $blue, $alpha);
			$point->movePenTo($this->x + round($p->x), $this->y + round($p->y));
			$point->drawLine(0.5, 0.5);
			$point->movePen(-0.5, 0);
			$point->drawLine(0.5, -0.5);

			$this->movie->add($point);
		}
	}

	/**
	 * Draw a colored line
	 *
	 * @param awColor $color Line color
	 * @param awLine $line
	 * @param int $thickness Line tickness
	 */
	public function line(awColor $color, awLine $line) {
		if ($line->getThickness() > 0 and $line->isHidden() === FALSE) {

			list($red, $green, $blue, $alpha) = $this->getColor($color);

			$mingLine = new SWFShape();
			$mingLine->setLine($line->getThickness(), $red, $green, $blue, $alpha);

			list($p1, $p2) = $line->getLocation();

			$mingLine->movePenTo($this->x + round($p1->x), $this->y + round($p1->y));

			switch($line->getStyle()) {

				case awLine::SOLID :
					$mingLine->drawLineTo($this->x + round($p2->x), $this->y + round($p2->y));
					$this->movie->add($mingLine);
					break;

				case awLine::DOTTED :
					$size = sqrt(pow($p2->y - $p1->y, 2) + pow($p2->x - $p1->x, 2));
					$cos = ($p2->x - $p1->x) / $size;
					$sin = ($p2->y - $p1->y) / $size;

					for ($i = 0; $i <= $size; $i += 2) {
						$p = new awPoint(
							round($i * $cos + $p1->x),
							round($i * $sin + $p1->y)
						);
						$this->point($color, $p);
					}

					break;

				case awLine::DASHED :
					$width = $p2->x - $p1->x;
					$height = $p2->y - $p1->y;
					$size = sqrt(pow($height, 2) + pow($width, 2));

					if ($size == 0) {
						return;
					}

					$cos = $width / $size;
					$sin = $height / $size;

					$functionX = ($width  > 0) ? 'min' : 'max';
					$functionY = ($height > 0) ? 'min' : 'max';

					for ($i = 0; $i <= $size; $i += 6) {

						$t1 = new awPoint(
							round($i * $cos + $p1->x),
							round($i * $sin + $p1->y)
						);

						$t2 = new awPoint(
							round($functionX(($i + 3) * $cos, $width) + $p1->x),
							round($functionY(($i + 3) * $sin, $height) + $p1->y)
						);

						$this->line($color, new awLine($t1, $t2));

					}

					break;

			}

		}

	}

	/**
	 * Draw a color arc

	 * @param awColor $color Arc color
	 * @param awPoint $center Point center
	 * @param int $width Ellipse width
	 * @param int $height Ellipse height
	 * @param int $from Start angle
	 * @param int $to End angle
	 */
	public function arc(awColor $color, awPoint $center, $width, $height, $from, $to) {

	}

	/**
	 * Draw an arc with a background color
	 *
	 * @param awColor $color Arc background color
	 * @param awPoint $center Point center
	 * @param int $width Ellipse width
	 * @param int $height Ellipse height
	 * @param int $from Start angle
	 * @param int $to End angle
	 */
	public function filledArc(awColor $color, awPoint $center, $width, $height, $from, $to) {

	}

	/**
	 * Draw a colored ellipse
	 *
	 * @param awColor $color Ellipse color
	 * @param awPoint $center Ellipse center
	 * @param int $width Ellipse width
	 * @param int $height Ellipse height
	 */
	public function ellipse(awColor $color, awPoint $center, $width, $height) {

	}

	/**
	 * Draw an ellipse with a background
	 *
	 * @param mixed $background Background (can be a color or a gradient)
	 * @param awPoint $center Ellipse center
	 * @param int $width Ellipse width
	 * @param int $height Ellipse height
	 */
	public function filledEllipse($background, awPoint $center, $width, $height) {

	}

	/**
	 * Draw a colored rectangle
	 *
	 * @param awColor $color Rectangle color
	 * @param awLine $line Rectangle diagonale
	 * @param awPoint $p2
	 */
	public function rectangle(awColor $color, awLine $line) {
		list($p1, $p2) = $line->getLocation();

		// Get Red, Green, Blue and Alpha values for the line
		list($r, $g, $b, $a) = $this->getColor($color);

		// Calculate the coordinates of the two other points of the rectangle
		$p3 = new Point($p1->x, $p2->y);
		$p4 = new Point($p2->x, $p1->y);

		$side = clone $line;

		// Draw the four sides of the rectangle, clockwise
		if (
			($p1->x <= $p2->x and $p1->y <= $p2->y)
			or
			($p1->x >= $p2->x and $p1->y >= $p2->y)
		) {
			$side->setLocation($p1, $p4);
			$this->line($color, $side);

			$side->setLocation($p4, $p2);
			$this->line($color, $side);

			$side->setLocation($p2, $p3);
			$this->line($color, $side);

			$side->setLocation($p3, $p1);
			$this->line($color, $side);
		} else {
			$side->setLocation($p1, $p3);
			$this->line($color, $side);

			$side->setLocation($p3, $p2);
			$this->line($color, $side);

			$side->setLocation($p2, $p4);
			$this->line($color, $side);

			$side->setLocation($p4, $p1);
			$this->line($color, $side);
		}
	}

	/**
	 * Draw a rectangle with a background
	 *
	 * @param mixed $background Background (can be a color or a gradient)
	 * @param awLine $line Rectangle diagonale
	 */
	public function filledRectangle($background, awLine $line) {
		list($p1, $p2) = $line->getLocation();

		// Common shape settings
		$shape = new SWFShape();
		$shape->setLine(0);

		if ($background instanceof awColor) {

			// Get the Red, Green, Blue and Alpha values
			list($r, $g, $b, $a) = $this->getColor($background);
			$shape->setRightFill($r, $g, $b, $a);

		} elseif ($background instanceof awGradient) {

			// Get the Gradient object as an SWFGradient one
			list($flashGradient, $style) = $this->getGradient($background);

			$fill = $shape->addFill($flashGradient, $style);

			// Angles between Artichow and Ming don't match.
			// Don't use abs() or vertical gradients get inverted.
			$angle = $background->angle - 90;
			$fill->rotateTo($angle);

			// Move the gradient based on the position of the rectangle we're drawing
			$centerX = min($p1->x, $p2->y) + abs($p1->x - $p2->x) / 2;
			$centerY = min($p1->y, $p2->y) + abs($p1->y - $p2->y) / 2;
			$fill->moveTo($centerX, $centerY);

			// Ming draws its gradients on a 1600x1600 image,
			// so we have to resize it.
			if ($angle === -90) {
				$ratio = abs($p1->y - $p2->y) / 1600;
			} else {
				$ratio = abs($p1->x - $p2->x) / 1600;
			}
			$fill->scaleTo($ratio);

			$shape->setRightFill($fill);

		}

		// Set starting position
		$shape->movePenTo($this->x + round($p1->x), $this->y + round($p1->y));

		// Depending on the points' relative positions,
		// we have two drawing possibilities
		if (
			($p1->x <= $p2->x and $p1->y <= $p2->y)
			or
			($p1->x >= $p2->x and $p1->y >= $p2->y)
		) {
			$shape->drawLineTo($this->x + round($p2->x), $this->y + round($p1->y));
			$shape->drawLineTo($this->x + round($p2->x), $this->y + round($p2->y));
			$shape->drawLineTo($this->x + round($p1->x), $this->y + round($p2->y));
			$shape->drawLineTo($this->x + round($p1->x), $this->y + round($p1->y));
		} else {
			$shape->drawLineTo($this->x + round($p1->x), $this->y + round($p2->y));
			$shape->drawLineTo($this->x + round($p2->x), $this->y + round($p2->y));
			$shape->drawLineTo($this->x + round($p2->x), $this->y + round($p1->y));
			$shape->drawLineTo($this->x + round($p1->x), $this->y + round($p1->y));
		}

		$this->movie->add($shape);
	}

	/**
	 * Draw a polygon
	 *
	 * @param awColor $color Polygon color
	 * @param Polygon A polygon
	 */
	public function polygon(awColor $color, awPolygon $polygon) {
		$points = $polygon->all();
		$count = count($points);

		if ($count > 1) {

			$side = new awLine;
			$side->setStyle($polygon->getStyle());
			$side->setThickness($polygon->getThickness());

			$prev = $points[0];

			for ($i = 1; $i < $count; $i++) {
				$current = $points[$i];
				$side->setLocation($prev, $current);
				$this->line($color, $side);
				$prev = $current;
			}

			// Close the polygon
			$side->setLocation($prev, $points[0]);
			$this->line($color, $side);
		}
	}

	/**
	 * Draw a polygon with a background
	 *
	 * @param mixed $background Background (can be a color or a gradient)
	 * @param Polygon A polygon
	 */
	public function filledPolygon($background, awPolygon $polygon) {
		$shape = new SWFShape();

		if ($background instanceof awColor) {
			list($red, $green, $blue, $alpha) = $this->getColor($background);

			$shape->setRightFill($red, $green, $blue, $alpha);
		} elseif ($background instanceof awGradient) {
			list($flashGradient, $style) = $this->getGradient($background);

			$fill = $shape->addFill($flashGradient, $style);

			list($xMin, $xMax) = $polygon->getBoxXRange();
			list($yMin, $yMax) = $polygon->getBoxYRange();

			if ($background->angle === 0) {
				$fill->scaleTo(($yMax - $yMin) / 1600);
			} else {
				$fill->scaleTo(($xMax - $xMin) / 1600);
			}
			$fill->moveTo($xMin + ($xMax - $xMin) / 2, $yMin + ($yMax - $yMin) / 2);

			$shape->setRightFill($fill);
		}

		$points = $polygon->all();
		$count = count($points);

		if ($count > 1) {

			$prev = $points[0];

			$shape->movePenTo($prev->x, $prev->y);

			for ($i = 1; $i < $count; $i++) {
				$current = $points[$i];
				$shape->drawLineTo($current->x, $current->y);
			}

			// Close the polygon
			$shape->drawLineTo($prev->x, $prev->y);

			$this->movie->add($shape);

		}
	}

	/**
	 * Sends the image, as well as the correct HTTP headers, to the browser
	 *
	 * @param awImage $image The Image object to send
	 */
	public function send(awImage $image) {
		$this->drawImage($image);
	}

	/**
	 * Get the image as binary data
	 *
	 * @param awImage $image
	 */
	public function get(awImage $image) {
		return $this->drawImage($image, TRUE, FALSE);
	}

	public function getTextWidth(awText $text) {
		$font = $text->getFont();
		if ($this->isCompatibleWithFont($font) === FALSE) {
			awImage::drawError('Class MingDriver: Incompatible font type (\''.get_class($font).'\')');
		}

		// Ming only supports FileFont
		$fontDriver = $this->fileFontDriver;

		return $fontDriver->getTextWidth($text, $this);
	}

	public function getTextHeight(awText $text) {
		$font = $text->getFont();
		if ($this->isCompatibleWithFont($font) === FALSE) {
			awImage::drawError('Class MingDriver: Incompatible font type (\''.get_class($font).'\')');
		}

		// Ming only supports FileFont
		$fontDriver = $this->fileFontDriver;

		return $fontDriver->getTextHeight($text, $this);
	}

	protected function isCompatibleWithFont(awFont $font) {
		if ($font instanceof awTTFFont or $font instanceof awPHPFont) {
			return FALSE;
		} else {
			return TRUE;
		}
	}

	private function drawImage(awImage $image, $return = FALSE, $header = TRUE) {

		// Send headers to the browser
		if ($header === TRUE) {
			$image->sendHeaders();
		}

		if ($return) {
			ob_start();
		}

		$this->movie->output();

		if ($return) {
			return ob_get_clean();
		}
	}

	/**
	 * Convert an awGradient object to an SWFGradient one.
	 * Returns an object as well as the style of the Flash gradient.
	 *
	 * @param awGradient $gradient The awGradient object to convert
	 * @return array
	 */
	private function getGradient(awGradient $gradient) {
		$flashGradient = new SWFGradient();

		// Get RGBA values for the gradient boundaries
		list($r1, $g1, $b1, $a1) = $this->getColor($gradient->from);
		list($r2, $g2, $b2, $a2) = $this->getColor($gradient->to);

		$flashGradient->addEntry(0, $r1, $g1, $b1, $a1);

		if ($gradient instanceof awBilinearGradient) {

			$flashGradient->addEntry($gradient->center, $r2, $g2, $b2, $a2);
			$flashGradient->addEntry(1, $r1, $g1, $b1, $a1);

			return array($flashGradient, SWFFILL_LINEAR_GRADIENT);
		} else {

			$flashGradient->addEntry(1, $r2, $g2, $b2, $a2);

			if ($gradient instanceof awLinearGradient) {
				return array($flashGradient, SWFFILL_LINEAR_GRADIENT);
			} else {
				return array($flashGradient, SWFFILL_RADIAL_GRADIENT);
			}
		}
	}
//	abstract private function getPolygonPoints(awPolygon $polygon);

}

registerClass('MingDriver');

/*
 * Check for ming presence
 */
if (function_exists('ming_useswfversion') === FALSE) {
	awImage::drawErrorFile('missing-ming');
}


text:
<?php
Namespace ADR\RESTBundle\Services\Hasher\Storage;

class LookupInterface
{

}


text:
layout: default
title: Table of Contents jQuery Plugin — jquery.toc
---

Table of Contents jQuery Plugin

        A minimal, tiny jQuery plugin that will generate a table of contents, using
        semantic, nested lists with hash-link anchors to headings.

Download

        Version 0.4.0 ·
        GitHub Project

Live Example

Table of contents, auto-generated from the content on this page:

Usage

        You can download the latest release, or install with
        Twitter's Bower:
        bower install jquery.toc.

        Include jQuery (>= 1.6) and jquery.toc.js/jquery.toc.min.js on your page. The plugin can
        then be used either via HTML5 data attributes, or via the programmatic API. See below for
        the available options.

Via data attributes

Minimal example:

<ul data-toc></ul>

With options:

<ol data-toc="div.container" data-toc-headings="h2,h3,h4"></ol>

Via the JavaScript programmatic API

Minimal example:

<ul id="toc"></ul>
...
<script type="text/javascript">
    $("#toc").toc();
</script>

With options:

<ul id="toc"></ul>
...
<script type="text/javascript">
    $("#toc").toc({content: "div.container", headings: "h2,h3,h4"});
</script>

Options

<ul data-toc="content" data-toc-headings="headings"></ul>

$(...).toc({content: "body", headings: "h1,h2,h3"});

The plugin has two options:

            content is a selector where the plugin will look for headings to build up
            the TOC. The default value is "body".

            headings is a string with a comma-separated list of selectors to be used as
            headings, in the order which defines their relative hierarchy level. The default value
            of "h1,h2,h3" will select all h1, h2, and
            h3 elements to build the TOC, with h1 being a level 1,
            h2 a level 2, and so on. You can use any valid list of jQuery selectors;
            for example, if you just want h1 tags with a specific class, and no
            h3 tags, you could use "h1.title,h2" for this parameter.

        In addition, the plugin will create nested lists of the same type (ul or
        ol) as the element that it is called on.

Automatic ID generation

        The plugin generates hash-links to the headings on the page, to allow users to jump to the
        heading by clicking in the generated table of contents. This feature requires that the
        headings have IDs assigned; if they do not, the plugin will generate and assign IDs
        automatically.

The generated IDs are based on the text inside the headings, and uses two simple rules:

            Space characters are converted to underscores. Multiple spaces are replaced with a
            single underscore.

If the ID already exists, a suffix like "_1", "_2", etc. is tried till we get a unique
            ID.

        For example, a heading like <h2>Heading 2.1</h2> will get the ID
        Heading_2.1.

Alternatives

        If you're looking for a jQuery plugin that does more than just generate a minimal table of
        contents, the project wiki lists
        some more plugins.

License

        Licensed under the Apache License,
        version 2.0.

Credits

Created by Nikhil Dabas.


text:
<?php

namespace AppBundle\Controller\Tests;

use AppBundle\Tests\Controller\LoginWebTestCase;

class DefaultControllerTest extends LoginWebTestCase
{
    public function testIndex()
    {
        $this->logIn();

        $crawler = $this->client->request('GET', '/');

        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
    }
}


text:
import unittest

from mock import patch, MagicMock

from cloudify.exceptions import NonRecoverableError

from .. import health_check
from ...tests import TestGCP

@patch('cloudify_gcp.utils.assure_resource_id_correct', return_value=True)
@patch('cloudify_gcp.gcp.ServiceAccountCredentials.from_json_keyfile_dict')
@patch('cloudify_gcp.utils.get_gcp_resource_name', return_value='valid_name')
@patch('cloudify_gcp.gcp.build')
class TestHealthCheck(TestGCP):

    def test_create_http(self, mock_build, *args):
        health_check.create(
                'name',
                'http',
                {},
                )

        mock_build.assert_called_once()
        mock_build().httpHealthChecks().insert.assert_called_with(
                body={
                    'description': 'Cloudify generated httpHealthCheck',
                    'name': 'name'},
                project='not really a project'
                )

    def test_create_https(self, mock_build, *args):
        health_check.create(
                'name',
                'https',
                {},
                )

        mock_build.assert_called_once()
        mock_build().httpsHealthChecks().insert.assert_called_with(
                body={
                    'description': 'Cloudify generated httpsHealthCheck',
                    'name': 'name'},
                project='not really a project'
                )

    @patch('cloudify_gcp.utils.response_to_operation')
    def test_delete(self, mock_response, mock_build, *args):
        self.ctxmock.instance.runtime_properties.update({
            'name': 'delete_name',
            'kind': 'compute#httpHealthCheck',
            })

        operation = MagicMock()
        operation.has_finished.return_value = True
        mock_response.return_value = operation

        health_check.delete()

        mock_build.assert_called_once()
        mock_build().httpHealthChecks().delete.assert_called_with(
                httpHealthCheck='delete_name',
                project='not really a project',
                )

class TestHealthCheckHelpers(unittest.TestCase):

    def test_health_check_of_type_raises(self):
        with self.assertRaises(NonRecoverableError) as e:
            health_check.health_check_of_type('carrots')

        self.assertIn('Unexpected type', e.exception.message)


text:
<?php

use Jose\Factory\JWEFactory;

/**
 * Class JWETest.
 *
 * @group JWE
 * @group Unit
 */
class JWETest extends \Jose\Test\BaseTestCase
{
    public function testJWE()
    {
        $claims = [
            'nbf' => time(),
            'iat' => time(),
            'exp' => time() + 3600,
            'iss' => 'Me',
            'aud' => 'You',
            'sub' => 'My friend',
        ];
        $jwe = JWEFactory::createJWE($claims);

        self::assertEquals(0, $jwe->countRecipients());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The recipient does not exist.
     */
    public function testToCompactJSONFailed()
    {
        $jwe = JWEFactory::createJWE([
            'nbf' => time(),
            'iat' => time(),
            'exp' => time() + 3600,
            'iss' => 'Me',
            'aud' => 'You',
            'sub' => 'My friend',
        ]);

        $jwe->toCompactJSON(0);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The shared protected header "plic" does not exist.
     */
    public function testAddAndGetSharedProtectedHeader()
    {
        $jwe = JWEFactory::createJWE([]);
        $jwe = $jwe->withSharedProtectedHeader('foo', 'bar');

        self::assertEquals(['foo' => 'bar'], $jwe->getSharedProtectedHeaders());
        self::assertEquals('bar', $jwe->getSharedProtectedHeader('foo'));
        self::assertEquals('bar', $jwe->getSharedProtectedHeader('plic'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The shared header "plic" does not exist.
     */
    public function testAddSharedProtectedHeader()
    {
        $jwe = JWEFactory::createJWE([]);
        $jwe = $jwe->withSharedHeader('foo', 'bar');

        self::assertEquals(['foo' => 'bar'], $jwe->getSharedHeaders());
        self::assertEquals('bar', $jwe->getSharedHeader('foo'));
        self::assertEquals('bar', $jwe->getSharedHeader('plic'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage This JWE has AAD and cannot be converted into Compact JSON.
     */
    public function testCannotGetCompactJSONBecauseAADIsSet()
    {
        $jwe = JWEFactory::createJWE([], [], [], 'foo');
        $jwe = $jwe->addRecipientWithEncryptedKey(null, []);

        $jwe->toCompactJSON(0);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage This JWE does not have shared protected headers and cannot be converted into Compact JSON.
     */
    public function testCannotGetCompactJSONBecauseSharedProtectedHeadersAreNotSet()
    {
        $jwe = JWEFactory::createJWE([], [], ['foo' => 'bar']);
        $jwe = $jwe->addRecipientWithEncryptedKey(null, []);

        $jwe->toCompactJSON(0);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage This JWE has shared headers or recipient headers and cannot be converted into Compact JSON.
     */
    public function testCannotGetCompactJSONBecauseSharedHeadersAreSet()
    {
        $jwe = JWEFactory::createJWE([], ['plic' => 'ploc'], ['foo' => 'bar']);
        $jwe = $jwe->addRecipientWithEncryptedKey(null, []);

        $jwe->toCompactJSON(0);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage This JWE has shared headers or recipient headers and cannot be converted into Compact JSON.
     */
    public function testCannotGetCompactJSONBecauseRecipientHeadersAreSet()
    {
        $jwe = JWEFactory::createJWE([], ['plic' => 'ploc']);
        $jwe = $jwe->addRecipientWithEncryptedKey(null, ['foo' => 'bar']);

        $jwe->toCompactJSON(0);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The header "var" does not exist.
     */
    public function testRecipient()
    {
        $jwe = JWEFactory::createJWE([]);
        $jwe = $jwe->addRecipientWithEncryptedKey(null, [
            'foo' => 'bar',
            'plic' => 'ploc',
        ]);

        self::assertEquals(1, $jwe->countRecipients());
        self::assertEquals('bar', $jwe->getRecipient(0)->getHeader('foo'));
        self::assertEquals('ploc', $jwe->getRecipient(0)->getHeader('plic'));
        $jwe->getRecipient(0)->getHeader('var');
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<View android:background="?android:colorSecondary" android:layout_width="fill_parent" android:layout_height="8.0dip"
  xmlns:android="http://schemas.android.com/apk/res/android" />


text:
<?php

// # Update Webhook Sample
//
// This sample code demonstrate how to use this call to update a webhook; supports the replace operation only, as documented here at:
// https://developer.paypal.com/webapps/developer/docs/api/#update-a-webhook
// API used: PATCH v1/notifications/webhooks/<Webhook-Id>

// ## Get Webhook ID.
// In samples we are using CreateWebhook.php sample to get the created instance of webhook.
// However, in real case scenario, we could use just the ID from database or use an already existing webhook.
/** @var \PayPal\Api\Webhook $webhook */
$webhook = require 'CreateWebhook.php';
// Updating the webhook as per given request
//
//      [
//         {
//             "op":"replace",
//            "path":"/url",
//            "value":"https://requestb.in/10ujt3c1"
//         },
//         {
//             "op":"replace",
//            "path":"/event_types",
//            "value":[
//               {
//                   "name":"PAYMENT.SALE.REFUNDED"
//               }
//            ]
//         }
//      ]
$patch = new \PayPal\Api\Patch();
$patch->setOp("replace")
    ->setPath("/url")
    ->setValue("https://requestb.in/10ujt3c1?uniqid=". uniqid());

$patch2 = new \PayPal\Api\Patch();
$patch2->setOp("replace")
    ->setPath("/event_types")
    ->setValue(json_decode('[{"name":"PAYMENT.SALE.REFUNDED"}]'));

$patchRequest = new \PayPal\Api\PatchRequest();
$patchRequest->addPatch($patch)->addPatch($patch2);

// ### Get Webhook
try {
    $output = $webhook->update($patchRequest, $apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
 	ResultPrinter::printError("Updated a Webhook", "Webhook", null, $patchRequest, $ex);
    exit(1);
}

// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
 ResultPrinter::printResult("Updated a Webhook", "Webhook", $output->getId(), $patchRequest, $output);

return $output;


text:
package net.jp2p.jxse.core.id;

import java.net.URI;

import net.jp2p.chaupal.id.IJp2pID;
import net.jxta.id.ID;

public class Jp2pID<I extends ID> implements IJp2pID {
	private static final long serialVersionUID = 5433521342152257221L;

	private I id;

	public Jp2pID( I id ) {
		this.id =id;
	}

	public I getID() {
		return id;
	}

	@Override
	public String getIDFormat() {
		return id.getIDFormat();
	}

	@Override
	public Object getUniqueValue() {
		return id.getUniqueValue();
	}

	@Override
	public URI toURI() {
		return id.toURI();
	}
}


text:
module JamfRubyExtensions

  module Array

    module Predicates

      # A case-insensitive version of #include? for Arrays of Strings.
      #
      # @param somestring [String] the String to search for
      #
      # @return [Boolean] Does the Array contain the String, ignoring case?
      #
      def j_ci_include_string?(somestring)
        any? { |s| s.to_s.casecmp? somestring }
      end

    end # module

  end # module

end # module


text:
namespace net {
class CanonicalCookie;
enum class CookieAccessSemantics;
}  // namespace net

namespace content {

namespace proto {

class CookieChangeSubscriptionProto;

}  // namespace proto

// Represents a single subscription to the list of cookies sent to a URL.
//
// The included linked list node and service worker registration ID are used by
// CookieStoreManager. They are ignored when comparing instances.
class CookieChangeSubscription
    : public base::LinkNode<CookieChangeSubscription> {
 public:
  // Used to read a service worker's subscriptions from the persistent store.
  //
  // Returns an empty vector if deserialization failed.
  static std::vector<std::unique_ptr<CookieChangeSubscription>>
  DeserializeVector(const std::string& proto_string,
                    int64_t service_worker_registration_id);

  // Used to write a service worker's subscriptions to the service worker store.
  //
  // The subscriptions vector should not be empty. If a registration does not
  // have subscriptions, it should not be serialized.
  //
  // Returns the empty string in case of a serialization error.
  static std::string SerializeVector(
      const std::vector<std::unique_ptr<CookieChangeSubscription>>&
          subscriptions);

  // Converts a service worker's subscriptions to a Mojo API call result.
  static std::vector<blink::mojom::CookieChangeSubscriptionPtr> ToMojoVector(
      const std::vector<std::unique_ptr<CookieChangeSubscription>>&
          subscription);

  // Public for testing.
  //
  // Production code should use the vector-based factory methods above.
  //
  // Returns null in case of deserialization error.
  static std::unique_ptr<CookieChangeSubscription> Create(
      proto::CookieChangeSubscriptionProto proto,
      int64_t service_worker_registration_id);

  // Converts a subscription from a Mojo API call.
  CookieChangeSubscription(
      blink::mojom::CookieChangeSubscriptionPtr mojo_subscription,
      int64_t service_worker_registration_id);

  // Public for testing.
  //
  // Production code should use the vector-based factory methods above.
  CookieChangeSubscription(GURL url,
                           std::string name,
                           ::network::mojom::CookieMatchType match_type,
                           int64_t service_worker_registration_id);

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

  ~CookieChangeSubscription();

  // The URL whose cookie list is watched for changes.
  const GURL& url() const { return url_; }

  // Operator for name-based matching.
  //
  // This is used to implement both equality and prefix-based name matching.
  // Supporting the latter helps avoid wasting battery by waking up service
  // workers unnecessarily.
  ::network::mojom::CookieMatchType match_type() const { return match_type_; }

  // Operand for the name-based matching operator above.
  //
  // For EQUAL matching, the cookie name must precisely match name(). For
  // STARTS_WITH matching, the cookie name must be prefixed by name().
  const std::string& name() const { return name_; }

  // The service worker registration that this subscription belongs to.
  int64_t service_worker_registration_id() const {
    return service_worker_registration_id_;
  }

  // Writes the subscription to the given protobuf.
  void Serialize(proto::CookieChangeSubscriptionProto* proto) const;
  // Writes the subscription to the given Mojo object.
  void Serialize(
      blink::mojom::CookieChangeSubscription* mojo_subscription) const;

  // True if the subscription covers a change to the given cookie.
  bool ShouldObserveChangeTo(const net::CanonicalCookie& cookie,
                             net::CookieAccessSemantics access_semantics) const;

 private:
  const GURL url_;
  const std::string name_;
  const ::network::mojom::CookieMatchType match_type_;
  const int64_t service_worker_registration_id_;
};

// Used to deduplicate equivalent subscriptons.
//
// Ignores the service worker registration ID and the linked list node.
bool operator==(const CookieChangeSubscription& lhs,
                const CookieChangeSubscription& rhs);

}  // namespace content

#endif  // CONTENT_BROWSER_COOKIE_STORE_COOKIE_CHANGE_SUBSCRIPTION_H_


text:
{{'If you are a person (not a computer), select the' | translate}}
                {{puiExpectedItemName}}:


text:
from ray_release.config import Test
from ray_release.logger import logger
from ray_release.reporter.reporter import Reporter
from ray_release.result import Result
from ray_release.util import format_link

class LogReporter(Reporter):
    def report_result(self, test: Test, result: Result):
        logger.info(
            f"Test {test['name']} finished after "
            f"{result.runtime:.2f} seconds. Last logs:\n\n"
            f"{result.last_logs}\n"
        )

        logger.info(
            f"Got the following metadata: \n"
            f"  name:    {test['name']}\n"
            f"  status:  {result.status}\n"
            f"  runtime: {result.runtime:.2f}\n"
            f"  stable:  {result.stable}\n"
            f"\n"
            f"  buildkite_url: {format_link(result.buildkite_url)}\n"
            f"  wheels_url:    {format_link(result.wheels_url)}\n"
            f"  cluster_url:   {format_link(result.cluster_url)}\n"
        )

        results = result.results
        if results:
            msg = "Observed the following results:\n\n"

            for key, val in results.items():
                msg += f"  {key} = {val}\n"
        else:
            msg = "Did not find any results."
        logger.info(msg)


text:
package org.docksidestage.dbflute.bsentity.dbmeta;

import java.util.List;
import java.util.Map;

import org.dbflute.Entity;
import org.dbflute.optional.OptionalEntity;
import org.dbflute.dbmeta.AbstractDBMeta;
import org.dbflute.dbmeta.info.*;
import org.dbflute.dbmeta.name.*;
import org.dbflute.dbmeta.property.PropertyGateway;
import org.dbflute.dbway.DBDef;
import org.docksidestage.dbflute.allcommon.*;
import org.docksidestage.dbflute.exentity.*;

/**
 * The DB meta of member_withdrawal. (Singleton)
 * @author DBFlute(AutoGenerator)
 */
public class MemberWithdrawalDbm extends AbstractDBMeta {

    // ===================================================================================
    //                                                                           Singleton
    //                                                                           =========
    private static final MemberWithdrawalDbm _instance = new MemberWithdrawalDbm();
    private MemberWithdrawalDbm() {}
    public static MemberWithdrawalDbm getInstance() { return _instance; }

    // ===================================================================================
    //                                                                       Current DBDef
    //                                                                       =============
    public String getProjectName() { return DBCurrent.getInstance().projectName(); }
    public String getProjectPrefix() { return DBCurrent.getInstance().projectPrefix(); }
    public String getGenerationGapBasePrefix() { return DBCurrent.getInstance().generationGapBasePrefix(); }
    public DBDef getCurrentDBDef() { return DBCurrent.getInstance().currentDBDef(); }

    // ===================================================================================
    //                                                                    Property Gateway
    //                                                                    ================
    // -----------------------------------------------------
    //                                       Column Property
    //                                       ---------------
    protected final Map<String, PropertyGateway> _epgMap = newHashMap();
    { xsetupEpg(); }
    protected void xsetupEpg() {
        setupEpg(_epgMap, et -> ((MemberWithdrawal)et).getMemberId(), (et, vl) -> ((MemberWithdrawal)et).setMemberId(cti(vl)), "memberId");
        setupEpg(_epgMap, et -> ((MemberWithdrawal)et).getWithdrawalReasonCode(), (et, vl) -> {
            CDef.WithdrawalReason cls = (CDef.WithdrawalReason)gcls(et, columnWithdrawalReasonCode(), vl);
            if (cls != null) {
                ((MemberWithdrawal)et).setWithdrawalReasonCodeAsWithdrawalReason(cls);
            } else {
                ((MemberWithdrawal)et).mynativeMappingWithdrawalReasonCode((String)vl);
            }
        }, "withdrawalReasonCode");
        setupEpg(_epgMap, et -> ((MemberWithdrawal)et).getWithdrawalReasonInputText(), (et, vl) -> ((MemberWithdrawal)et).setWithdrawalReasonInputText((String)vl), "withdrawalReasonInputText");
        setupEpg(_epgMap, et -> ((MemberWithdrawal)et).getWithdrawalDatetime(), (et, vl) -> ((MemberWithdrawal)et).setWithdrawalDatetime(ctldt(vl)), "withdrawalDatetime");
        setupEpg(_epgMap, et -> ((MemberWithdrawal)et).getRegisterDatetime(), (et, vl) -> ((MemberWithdrawal)et).setRegisterDatetime(ctldt(vl)), "registerDatetime");
        setupEpg(_epgMap, et -> ((MemberWithdrawal)et).getRegisterUser(), (et, vl) -> ((MemberWithdrawal)et).setRegisterUser((String)vl), "registerUser");
        setupEpg(_epgMap, et -> ((MemberWithdrawal)et).getUpdateDatetime(), (et, vl) -> ((MemberWithdrawal)et).setUpdateDatetime(ctldt(vl)), "updateDatetime");
        setupEpg(_epgMap, et -> ((MemberWithdrawal)et).getUpdateUser(), (et, vl) -> ((MemberWithdrawal)et).setUpdateUser((String)vl), "updateUser");
    }
    public PropertyGateway findPropertyGateway(String prop)
    { return doFindEpg(_epgMap, prop); }

    // -----------------------------------------------------
    //                                      Foreign Property
    //                                      ----------------
    protected final Map<String, PropertyGateway> _efpgMap = newHashMap();
    { xsetupEfpg(); }
    @SuppressWarnings("unchecked")
    protected void xsetupEfpg() {
        setupEfpg(_efpgMap, et -> ((MemberWithdrawal)et).getMember(), (et, vl) -> ((MemberWithdrawal)et).setMember((OptionalEntity<Member>)vl), "member");
        setupEfpg(_efpgMap, et -> ((MemberWithdrawal)et).getWithdrawalReason(), (et, vl) -> ((MemberWithdrawal)et).setWithdrawalReason((OptionalEntity<WithdrawalReason>)vl), "withdrawalReason");
    }
    public PropertyGateway findForeignPropertyGateway(String prop)
    { return doFindEfpg(_efpgMap, prop); }

    // ===================================================================================
    //                                                                          Table Info
    //                                                                          ==========
    protected final String _tableDbName = "member_withdrawal";
    protected final String _tableDispName = "MEMBER_WITHDRAWAL";
    protected final String _tablePropertyName = "memberWithdrawal";
    protected final TableSqlName _tableSqlName = new TableSqlName("MEMBER_WITHDRAWAL", _tableDbName);
    { _tableSqlName.xacceptFilter(DBFluteConfig.getInstance().getTableSqlNameFilter()); }
    public String getTableDbName() { return _tableDbName; }
    public String getTableDispName() { return _tableDispName; }
    public String getTablePropertyName() { return _tablePropertyName; }
    public TableSqlName getTableSqlName() { return _tableSqlName; }
    protected final String _tableAlias = "会員退会情報";
    public String getTableAlias() { return _tableAlias; }

    // ===================================================================================
    //                                                                         Column Info
    //                                                                         ===========
    protected final ColumnInfo _columnMemberId = cci("MEMBER_ID", "MEMBER_ID", null, "会員ID", Integer.class, "memberId", null, true, false, true, "INT", 10, 0, null, false, null, null, "member", null, null, false);
    protected final ColumnInfo _columnWithdrawalReasonCode = cci("WITHDRAWAL_REASON_CODE", "WITHDRAWAL_REASON_CODE", null, "退会理由コード", String.class, "withdrawalReasonCode", null, false, false, false, "CHAR", 3, 0, null, false, null, null, "withdrawalReason", null, CDef.DefMeta.WithdrawalReason, false);
    protected final ColumnInfo _columnWithdrawalReasonInputText = cci("WITHDRAWAL_REASON_INPUT_TEXT", "WITHDRAWAL_REASON_INPUT_TEXT", null, "退会理由入力テキスト", String.class, "withdrawalReasonInputText", null, false, false, false, "TEXT", 65535, 0, null, false, null, null, null, null, null, false);
    protected final ColumnInfo _columnWithdrawalDatetime = cci("WITHDRAWAL_DATETIME", "WITHDRAWAL_DATETIME", null, "退会日時", java.time.LocalDateTime.class, "withdrawalDatetime", null, false, false, true, "DATETIME", 19, 0, null, false, null, null, null, null, null, false);
    protected final ColumnInfo _columnRegisterDatetime = cci("REGISTER_DATETIME", "REGISTER_DATETIME", null, "登録日時", java.time.LocalDateTime.class, "registerDatetime", null, false, false, true, "DATETIME", 19, 0, null, true, null, null, null, null, null, false);
    protected final ColumnInfo _columnRegisterUser = cci("REGISTER_USER", "REGISTER_USER", null, "登録ユーザー", String.class, "registerUser", null, false, false, true, "VARCHAR", 200, 0, null, true, null, null, null, null, null, false);
    protected final ColumnInfo _columnUpdateDatetime = cci("UPDATE_DATETIME", "UPDATE_DATETIME", null, "更新日時", java.time.LocalDateTime.class, "updateDatetime", null, false, false, true, "DATETIME", 19, 0, null, true, null, null, null, null, null, false);
    protected final ColumnInfo _columnUpdateUser = cci("UPDATE_USER", "UPDATE_USER", null, "更新ユーザー", String.class, "updateUser", null, false, false, true, "VARCHAR", 200, 0, null, true, null, null, null, null, null, false);

    /**
     * (会員ID)MEMBER_ID: {PK, NotNull, INT(10), FK to member}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnMemberId() { return _columnMemberId; }
    /**
     * (退会理由コード)WITHDRAWAL_REASON_CODE: {IX, CHAR(3), FK to withdrawal_reason, classification=WithdrawalReason}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnWithdrawalReasonCode() { return _columnWithdrawalReasonCode; }
    /**
     * (退会理由入力テキスト)WITHDRAWAL_REASON_INPUT_TEXT: {TEXT(65535)}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnWithdrawalReasonInputText() { return _columnWithdrawalReasonInputText; }
    /**
     * (退会日時)WITHDRAWAL_DATETIME: {NotNull, DATETIME(19)}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnWithdrawalDatetime() { return _columnWithdrawalDatetime; }
    /**
     * (登録日時)REGISTER_DATETIME: {NotNull, DATETIME(19)}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnRegisterDatetime() { return _columnRegisterDatetime; }
    /**
     * (登録ユーザー)REGISTER_USER: {NotNull, VARCHAR(200)}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnRegisterUser() { return _columnRegisterUser; }
    /**
     * (更新日時)UPDATE_DATETIME: {NotNull, DATETIME(19)}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnUpdateDatetime() { return _columnUpdateDatetime; }
    /**
     * (更新ユーザー)UPDATE_USER: {NotNull, VARCHAR(200)}
     * @return The information object of specified column. (NotNull)
     */
    public ColumnInfo columnUpdateUser() { return _columnUpdateUser; }

    protected List<ColumnInfo> ccil() {
        List<ColumnInfo> ls = newArrayList();
        ls.add(columnMemberId());
        ls.add(columnWithdrawalReasonCode());
        ls.add(columnWithdrawalReasonInputText());
        ls.add(columnWithdrawalDatetime());
        ls.add(columnRegisterDatetime());
        ls.add(columnRegisterUser());
        ls.add(columnUpdateDatetime());
        ls.add(columnUpdateUser());
        return ls;
    }

    { initializeInformationResource(); }

    // ===================================================================================
    //                                                                         Unique Info
    //                                                                         ===========
    // -----------------------------------------------------
    //                                       Primary Element
    //                                       ---------------
    protected UniqueInfo cpui() { return hpcpui(columnMemberId()); }
    public boolean hasPrimaryKey() { return true; }
    public boolean hasCompoundPrimaryKey() { return false; }

    // ===================================================================================
    //                                                                       Relation Info
    //                                                                       =============
    // cannot cache because it uses related DB meta instance while booting
    // (instead, cached by super's collection)
    // -----------------------------------------------------
    //                                      Foreign Property
    //                                      ----------------
    /**
     * (会員)MEMBER by my MEMBER_ID, named 'member'.
     * @return The information object of foreign property. (NotNull)
     */
    public ForeignInfo foreignMember() {
        Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnMemberId(), MemberDbm.getInstance().columnMemberId());
        return cfi("FK_MEMBER_WITHDRAWAL_MEMBER", "member", this, MemberDbm.getInstance(), mp, 0, org.dbflute.optional.OptionalEntity.class, true, false, false, false, null, null, false, "memberWithdrawalAsOne", false);
    }
    /**
     * (退会理由)WITHDRAWAL_REASON by my WITHDRAWAL_REASON_CODE, named 'withdrawalReason'.
     * @return The information object of foreign property. (NotNull)
     */
    public ForeignInfo foreignWithdrawalReason() {
        Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnWithdrawalReasonCode(), WithdrawalReasonDbm.getInstance().columnWithdrawalReasonCode());
        return cfi("FK_MEMBER_WITHDRAWAL_WITHDRAWAL_REASON", "withdrawalReason", this, WithdrawalReasonDbm.getInstance(), mp, 1, org.dbflute.optional.OptionalEntity.class, false, false, false, false, null, null, false, "memberWithdrawalList", false);
    }

    // -----------------------------------------------------
    //                                     Referrer Property
    //                                     -----------------

    // ===================================================================================
    //                                                                        Various Info
    //                                                                        ============
    public boolean hasCommonColumn() { return true; }
    public List<ColumnInfo> getCommonColumnInfoList()
    { return newArrayList(columnRegisterDatetime(), columnRegisterUser(), columnUpdateDatetime(), columnUpdateUser()); }
    public List<ColumnInfo> getCommonColumnInfoBeforeInsertList()
    { return newArrayList(columnRegisterDatetime(), columnRegisterUser(), columnUpdateDatetime(), columnUpdateUser()); }
    public List<ColumnInfo> getCommonColumnInfoBeforeUpdateList()
    { return newArrayList(columnUpdateDatetime(), columnUpdateUser()); }

    // ===================================================================================
    //                                                                           Type Name
    //                                                                           =========
    public String getEntityTypeName() { return "org.docksidestage.dbflute.exentity.MemberWithdrawal"; }
    public String getConditionBeanTypeName() { return "org.docksidestage.dbflute.cbean.MemberWithdrawalCB"; }
    public String getBehaviorTypeName() { return "org.docksidestage.dbflute.exbhv.MemberWithdrawalBhv"; }

    // ===================================================================================
    //                                                                         Object Type
    //                                                                         ===========
    public Class<MemberWithdrawal> getEntityType() { return MemberWithdrawal.class; }

    // ===================================================================================
    //                                                                     Object Instance
    //                                                                     ===============
    public MemberWithdrawal newEntity() { return new MemberWithdrawal(); }

    // ===================================================================================
    //                                                                   Map Communication
    //                                                                   =================
    public void acceptPrimaryKeyMap(Entity et, Map<String, ? extends Object> mp)
    { doAcceptPrimaryKeyMap((MemberWithdrawal)et, mp); }
    public void acceptAllColumnMap(Entity et, Map<String, ? extends Object> mp)
    { doAcceptAllColumnMap((MemberWithdrawal)et, mp); }
    public Map<String, Object> extractPrimaryKeyMap(Entity et) { return doExtractPrimaryKeyMap(et); }
    public Map<String, Object> extractAllColumnMap(Entity et) { return doExtractAllColumnMap(et); }
}


text:
package cz.metacentrum.perun.core.impl;

import cz.metacentrum.perun.core.implApi.ConfigManagerImplApi;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;

/**
 *
 * @author David Flor <493294@mail.muni.cz>
 */
public class ConfigManagerImpl implements ConfigManagerImplApi {

	private PerunAppsConfigLoader perunAppsConfigLoader;

	@Override
	public void setPerunAppsConfigLoader(PerunAppsConfigLoader perunAppsConfigLoader) {
		this.perunAppsConfigLoader = perunAppsConfigLoader;
	}

	@Override
	public void reloadAppsConfig() {
		perunAppsConfigLoader.initialize();
	}
}


text:
[![NPM version](https://img.shields.io/npm/v/github-pagination.svg?style=flat)](https://www.npmjs.org/package/github-pagination)

A simple js lib for parse GitHub's pagination info from API's response.

------

## Installation

```bash
$ npm install github-pagination --save
```

or

```bash
$ bower install github-pagination --save
```

## Example
in node.js / io.js

```js
var octopage = require('./');

var test = '<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=15>; rel="next",  <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=34>; rel="last",  <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=1>; rel="first",  <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=13>; rel="prev"';

console.log(octopage.parser(test));
// { next: '15', last: '34', first: '1', prev: '13' }
```

in browser

link this script and then,

```html
<script src="octopage.js"></script>
<script>
  var test = '<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=15>; rel="next",  <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=34>; rel="last",  <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=1>; rel="first",  <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=13>; rel="prev"';

  console.log(octopage.parser(test));
  // { next: '15', last: '34', first: '1', prev: '13' }
</script>
```

## License

MIT © [Leigh Zhu](#)


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Utilisateur
 * Date: 22/10/13
 * Time: 07:41
 * To change this template use File | Settings | File Templates.
 */

namespace tuto\WelcomeBundle\Form\Handler;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

class ContactHandler {

    protected $form;
    protected $request;
    protected $mailer;

    /**
     * @param Form $form
     * @param Request $request
     * @param $mailer
     */
    public function __construct(Form $form, Request $request, $mailer){
        $this->form = $form;
        $this->request = $request;
        $this->mailer = $mailer;
    }

    /**
     * @return bool
     */
    public function process(){
        if($this->request->getMethod()=="POST"){
            $this->form->submit($this->request);
            $data=$this->form->getData();
            $this->onSuccess($data);
            return true;
        }
        return false;
    }

    protected function onSuccess($data){
        $message = \Swift_Message::newInstance()
            ->setContentType('text/html')
            ->setSubject($data['subject'])
            ->setFrom($data['email'])
            ->setTo('xxxxxx@gmail.com')
            ->setBody($data['content']);

        $this->mailer->send($message);
    }
}