text:
<?php namespace GoCardless\Pro\Models\Abstracts;

use GoCardless\Pro\Models\Traits\Factory;

abstract class BankAccount extends Entity
{
    use Factory;

    /** @var string */
    protected $account_number_ending;
    /** @var string */
    protected $bank_name;
    /** @var bool */
    protected $enabled;
    /** @var string */
    protected $account_holder_name;
    /** @var string */
    protected $account_number;
    /** @var string */
    protected $branch_code;
    /** @var string */
    protected $bank_code;
    /** @var string */
    protected $iban;
    /** @var string */
    protected $country_code;
    /** @var string */
    protected $currency;

    /**
     * @param $sort_code
     * @return $this
     */
    public function setSortCode($sort_code)
    {
        return $this->setBranchCode($sort_code);
    }

    /**
     * @return string
     */
    public function getAccountNumberEnding()
    {
        return $this->account_number_ending;
    }

    /**
     * @return string
     */
    public function getBankName()
    {
        return $this->bank_name;
    }

    /**
     * @return bool
     */
    public function isDisabled()
    {
        return !$this->isEnabled();
    }

    /**
     * @return bool
     */
    public function isEnabled()
    {
        return (bool)$this->enabled;
    }

    /**
     * @return string
     */
    public function getAccountHolderName()
    {
        return $this->account_holder_name;
    }

    /**
     * @param $account_holder_name
     * @return $this
     */
    public function setAccountHolderName($account_holder_name)
    {
        $this->account_holder_name = $account_holder_name;

        return $this;
    }

    /**
     * @return string
     */
    public function getAccountNumber()
    {
        return $this->account_number;
    }

    /**
     * @param $account_number
     * @return $this
     */
    public function setAccountNumber($account_number)
    {
        $this->account_number = $account_number;

        return $this;
    }

    /**
     * @return string
     */
    public function getSortCode()
    {
        return $this->getBranchCode();
    }

    /**
     * @return string
     */
    public function getBranchCode()
    {
        return $this->branch_code;
    }

    /**
     * @param $branch_code
     * @return $this
     */
    public function setBranchCode($branch_code)
    {
        $this->branch_code = $branch_code;

        return $this;
    }

    /**
     * @return string
     */
    public function getBankCode()
    {
        return $this->bank_code;
    }

    /**
     * @param $bank_code
     * @return $this
     */
    public function setBankCode($bank_code)
    {
        $this->bank_code = $bank_code;

        return $this;
    }

    /**
     * @return string
     */
    public function getIban()
    {
        return $this->iban;
    }

    /**
     * @param $iban
     * @return $this
     */
    public function setIban($iban)
    {
        $this->iban = $iban;

        return $this;
    }

    /**
     * @return boolean
     */
    public function hasIban()
    {
        return !!$this->iban;
    }

    /**
     * @return string
     */
    public function getCountryCode()
    {
        return $this->country_code;
    }

    /**
     * @param $country_code
     * @return $this
     */
    public function setCountryCode($country_code)
    {
        $this->country_code = $country_code;

        return $this;
    }

    /**
     * @return string
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * @param $currency
     * @return $this
     */
    public function setCurrency($currency)
    {
        $this->currency = $currency;

        return $this;
    }
}


text:
require 'sinatra/base'
require 'sinatra/param/version'
require 'date'
require 'time'

module Sinatra
  module Param
    Boolean = :boolean

    class InvalidParameterError < StandardError
      attr_accessor :param, :options
    end

    def param(name, type, options = {})
      name = name.to_s

      return unless params.member?(name) or options[:default] or options[:required]

      begin
        params[name] = coerce(params[name], type, options)
        params[name] = (options[:default].call if options[:default].respond_to?(:call)) || options[:default] if params[name].nil? and options[:default]
        params[name] = options[:transform].to_proc.call(params[name]) if params[name] and options[:transform]
        validate!(params[name], options)
      rescue InvalidParameterError => exception
        if options[:raise] or (settings.raise_sinatra_param_exceptions rescue false)
          exception.param, exception.options = name, options
          raise exception
        end

        error = exception.to_s

        if content_type and content_type.match(mime_type(:json))
          error = {message: error, errors: {name => exception.message}}.to_json
        end

        halt 400, error
      end
    end

    def one_of(*args)
      options = args.last.is_a?(Hash) ? args.pop : {}
      names = args.collect(&:to_s)

      return unless names.length >= 2

      begin
        validate_one_of!(params, names, options)
      rescue InvalidParameterError => exception
        if options[:raise] or (settings.raise_sinatra_param_exceptions rescue false)
          exception.param, exception.options = names, options
          raise exception
        end

        error = "Invalid parameters [#{names.join(', ')}]"
        if content_type and content_type.match(mime_type(:json))
          error = {message: error, errors: {names => exception.message}}.to_json
        end

        halt 400, error
      end
    end

    def any_of(*args)
      options = args.last.is_a?(Hash) ? args.pop : {}
      names = args.collect(&:to_s)

      return unless names.length >= 2

      begin
        validate_any_of!(params, names, options)
      rescue InvalidParameterError => exception
        if options[:raise] or (settings.raise_sinatra_param_exceptions rescue false)
          exception.param, exception.options = names, options
          raise exception
        end

        error = "Invalid parameters [#{names.join(', ')}]"
        if content_type and content_type.match(mime_type(:json))
          error = {message: error, errors: {names => exception.message}}.to_json
        end

        halt 400, error
      end
    end

    private

    def coerce(param, type, options = {})
      begin
        return nil if param.nil?
        return param if (param.is_a?(type) rescue false)
        return Integer(param) if type == Integer
        return Float(param) if type == Float
        return String(param) if type == String
        return Date.parse(param) if type == Date
        return Time.parse(param) if type == Time
        return DateTime.parse(param) if type == DateTime
        return Array(param.split(options[:delimiter] || ",")) if type == Array
        return Hash[param.split(options[:delimiter] || ",").map{|c| c.split(options[:separator] || ":")}] if type == Hash
        return (/(false|f|no|n|0)$/i === param.to_s ? false : (/(true|t|yes|y|1)$/i === param.to_s ? true : nil)) if type == TrueClass || type == FalseClass || type == Boolean
        return nil
      rescue ArgumentError
        raise InvalidParameterError, "'#{param}' is not a valid #{type}"
      end
    end

    def validate!(param, options)
      options.each do |key, value|
        case key
        when :required
          raise InvalidParameterError, "Parameter is required" if value && param.nil?
        when :blank
          raise InvalidParameterError, "Parameter cannot be blank" if !value && case param
          when String
            !(/\S/ === param)
          when Array, Hash
            param.empty?
          else
            param.nil?
          end
        when :format
          raise InvalidParameterError, "Parameter must be a string if using the format validation" unless param.kind_of?(String)
          raise InvalidParameterError, "Parameter must match format #{value}" unless param =~ value
        when :is
          raise InvalidParameterError, "Parameter must be #{value}" unless param === value
        when :in, :within, :range
          raise InvalidParameterError, "Parameter must be within #{value}" unless param.nil? || case value
          when Range
            value.include?(param)
          else
            Array(value).include?(param)
          end
        when :min
          raise InvalidParameterError, "Parameter cannot be less than #{value}" unless param.nil? || value <= param
        when :max
          raise InvalidParameterError, "Parameter cannot be greater than #{value}" unless param.nil? || value >= param
        when :min_length
          raise InvalidParameterError, "Parameter cannot have length less than #{value}" unless param.nil? || value <= param.length
        when :max_length
          raise InvalidParameterError, "Parameter cannot have length greater than #{value}" unless param.nil? || value >= param.length
        end
      end
    end

    def validate_one_of!(params, names, options)
      raise InvalidParameterError, "Only one of [#{names.join(', ')}] is allowed" if names.count{|name| present?(params[name])} > 1
    end

    def validate_any_of!(params, names, options)
      raise InvalidParameterError, "One of parameters [#{names.join(', ')}] is required" if names.count{|name| present?(params[name])} < 1
    end

    # ActiveSupport #present? and #blank? without patching Object
    def present?(object)
      !blank?(object)
    end

    def blank?(object)
      object.respond_to?(:empty?) ? object.empty? : !object
    end
  end

  helpers Param
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

    <title>get-identity-notification-attributes — AWS CLI 1.0.0 documentation</title>
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap.min.css" />

    <link rel="stylesheet" href="../../_static/guzzle.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="top" title="AWS CLI 1.0.0 documentation" href="../../index.html" />
    <link rel="up" title="ses" href="index.html" />
    <link rel="next" title="get-identity-verification-attributes" href="get-identity-verification-attributes.html" />
    <link rel="prev" title="get-identity-dkim-attributes" href="get-identity-dkim-attributes.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap-responsive.min.css" />

        AWS CLI

Home

Documentation

Forum

GitHub

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

ses »

          ← get-identity-dkim-attributes
          /

get-identity-verification-attributes →

Table Of Contents

get-identity-notification-attributes

Description

Synopsis

Options

Examples

Quick search

    <form class="form-search margin-top-1em" action="../../search.html" method="get">
        <input type="text" name="q" style="width: 105px" class="input-small search-query" />
        <button type="submit" class="btn btn-small">Search</button>
        <input type="hidden" name="check_keywords" value="yes" />
        <input type="hidden" name="area" value="default" />
    </form>

Feedback

Did you find this page useful? Do you have a suggestion? Give us feedback or
  send us a pull request on GitHub.

[ aws . ses ]

get-identity-notification-attributes¶

Description¶

Given a list of verified identities (email addresses and/or domains), returns a structure describing identity notification attributes.

This action is throttled at one request per second.

For more information about feedback notification, see the Amazon SES Developer Guide .

Synopsis¶

  get-identity-notification-attributes
--identities <value>

Options¶

<tt class="docutils literal">--identities</tt> (list)

A list of one or more identities.

Syntax:

"string" "string" ...

Examples¶

To get the Amazon SES notification attributes for a list of identities

The following example uses the <tt class="docutils literal">get-identity-notification-attributes</tt> command to retrieve the Amazon SES notification attributes for a list of identities:

aws ses get-identity-notification-attributes --identities "user1@example.com" "user2@example.com"

Output:

{
   "NotificationAttributes": {
       "user1@example.com": {
           "ForwardingEnabled": false,
           "ComplaintTopic": "arn:aws:sns:us-east-1:EXAMPLE65304:MyTopic",
           "BounceTopic": "arn:aws:sns:us-east-1:EXAMPLE65304:MyTopic"
       },
       "user2@example.com": {
           "ForwardingEnabled": true
       }
   },
   "ResponseMetadata": {
       "RequestId": "303335b1-d484-11e2-b9bf-5b6577ad6eb1"
   }
}

If email feedback forwarding is disabled, then this command returns the Amazon Resource Names (ARNs) of the SNS topics that bounce and complaint notifications are sent to.

If you call this command with an identity that you have never submitted for verification, that identity won't appear in the output.

For more information about bounce and complaint notifications, see Bounce and Complaint Notifications in Amazon SES in the Amazon Simple Email Service Developer Guide.

          ← get-identity-dkim-attributes
          /

get-identity-verification-attributes →

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

ses »

    © Copyright 2013, Amazon Web Services. Created using Sphinx.


text:
#ifndef _GETTEXT_PO_H
#define _GETTEXT_PO_H 1

#include <stdlib.h>

#ifdef __cplusplus
extern "C" {
#endif

/* =========================== Meta Information ============================ */

/* Version number: (major<<16) + (minor<<8) + subminor */
#define LIBGETTEXTPO_VERSION 0x001203
extern int libgettextpo_version;

/* ================================= Types ================================= */

/* A po_file_t represents the contents of a PO file.  */
typedef struct po_file *po_file_t;

/* A po_message_iterator_t represents an iterator through a domain of a
   PO file.  */
typedef struct po_message_iterator *po_message_iterator_t;

/* A po_message_t represents a message in a PO file.  */
typedef struct po_message *po_message_t;

/* A po_filepos_t represents a string's position within a source file.  */
typedef struct po_filepos *po_filepos_t;

/* A po_error_handler handles error situations.  */
struct po_error_handler
{
  /* Signal an error.  The error message is built from FORMAT and the following
     arguments.  ERRNUM, if nonzero, is an errno value.
     Must increment the error_message_count variable declared in error.h.
     Must not return if STATUS is nonzero.  */
  void (*error) (int status, int errnum,
                 const char *format, ...)
#if ((__GNUC__ == 3 && __GNUC_MINOR__ >= 1) || __GNUC__ > 3) && !__STRICT_ANSI__
  __attribute__ ((__format__ (__printf__, 3, 4)))
#endif
  ;

  /* Signal an error.  The error message is built from FORMAT and the following
     arguments.  The error location is at FILENAME line LINENO. ERRNUM, if
     nonzero, is an errno value.
     Must increment the error_message_count variable declared in error.h.
     Must not return if STATUS is nonzero.  */
  void (*error_at_line) (int status, int errnum,
                         const char *filename, unsigned int lineno,
                         const char *format, ...)
#if ((__GNUC__ == 3 && __GNUC_MINOR__ >= 1) || __GNUC__ > 3) && !__STRICT_ANSI__
  __attribute__ ((__format__ (__printf__, 5, 6)))
#endif
  ;

  /* Signal a multiline warning.  The PREFIX applies to all lines of the
     MESSAGE.  Free the PREFIX and MESSAGE when done.  */
  void (*multiline_warning) (char *prefix, char *message);

  /* Signal a multiline error.  The PREFIX applies to all lines of the
     MESSAGE.  Free the PREFIX and MESSAGE when done.
     Must increment the error_message_count variable declared in error.h if
     PREFIX is non-NULL.  */
  void (*multiline_error) (char *prefix, char *message);
};
typedef const struct po_error_handler *po_error_handler_t;

/* A po_xerror_handler handles warnings, error and fatal error situations.  */
#define PO_SEVERITY_WARNING     0 /* just a warning, tell the user */
#define PO_SEVERITY_ERROR       1 /* an error, the operation cannot complete */
#define PO_SEVERITY_FATAL_ERROR 2 /* an error, the operation must be aborted */
struct po_xerror_handler
{
  /* Signal a problem of the given severity.
     MESSAGE and/or FILENAME + LINENO indicate where the problem occurred.
     If FILENAME is NULL, FILENAME and LINENO and COLUMN should be ignored.
     If LINENO is (size_t)(-1), LINENO and COLUMN should be ignored.
     If COLUMN is (size_t)(-1), it should be ignored.
     MESSAGE_TEXT is the problem description (if MULTILINE_P is true,
     multiple lines of text, each terminated with a newline, otherwise
     usually a single line).
     Must not return if SEVERITY is PO_SEVERITY_FATAL_ERROR.  */
  void (*xerror) (int severity,
                  po_message_t message,
                  const char *filename, size_t lineno, size_t column,
                  int multiline_p, const char *message_text);
  /* Signal a problem that refers to two messages.
     Similar to two calls to xerror.
     If possible, a "..." can be appended to MESSAGE_TEXT1 and prepended to
     MESSAGE_TEXT2.  */
  void (*xerror2) (int severity,
                   po_message_t message1,
                   const char *filename1, size_t lineno1, size_t column1,
                   int multiline_p1, const char *message_text1,
                   po_message_t message2,
                   const char *filename2, size_t lineno2, size_t column2,
                   int multiline_p2, const char *message_text2);
};
typedef const struct po_xerror_handler *po_xerror_handler_t;

/* Memory allocation:
   The memory allocations performed by these functions use xmalloc(),
   therefore will cause a program exit if memory is exhausted.
   The memory allocated by po_file_read, and implicitly returned through
   the po_message_* functions, lasts until freed with po_file_free.  */

/* ============================= po_file_t API ============================= */

/* Create an empty PO file representation in memory.  */
extern po_file_t po_file_create (void);

/* Read a PO file into memory.
   Return its contents.  Upon failure, return NULL and set errno.  */
#define po_file_read po_file_read_v3
extern po_file_t po_file_read (const char *filename,
                               po_xerror_handler_t handler);

/* Write an in-memory PO file to a file.
   Upon failure, return NULL and set errno.  */
#define po_file_write po_file_write_v2
extern po_file_t po_file_write (po_file_t file, const char *filename,
                                po_xerror_handler_t handler);

/* Free a PO file from memory.  */
extern void po_file_free (po_file_t file);

/* Return the names of the domains covered by a PO file in memory.  */
extern const char * const * po_file_domains (po_file_t file);

/* =========================== Header entry API ============================ */

/* Return the header entry of a domain of a PO file in memory.
   The domain NULL denotes the default domain.
   Return NULL if there is no header entry.  */
extern const char * po_file_domain_header (po_file_t file, const char *domain);

/* Return the value of a field in a header entry.
   The return value is either a freshly allocated string, to be freed by the
   caller, or NULL.  */
extern char * po_header_field (const char *header, const char *field);

/* Return the header entry with a given field set to a given value.  The field
   is added if necessary.
   The return value is a freshly allocated string.  */
extern char * po_header_set_field (const char *header, const char *field, const char *value);

/* ======================= po_message_iterator_t API ======================= */

/* Create an iterator for traversing a domain of a PO file in memory.
   The domain NULL denotes the default domain.  */
extern po_message_iterator_t po_message_iterator (po_file_t file, const char *domain);

/* Free an iterator.  */
extern void po_message_iterator_free (po_message_iterator_t iterator);

/* Return the next message, and advance the iterator.
   Return NULL at the end of the message list.  */
extern po_message_t po_next_message (po_message_iterator_t iterator);

/* Insert a message in a PO file in memory, in the domain and at the position
   indicated by the iterator.  The iterator thereby advances past the freshly
   inserted message.  */
extern void po_message_insert (po_message_iterator_t iterator, po_message_t message);

/* =========================== po_message_t API ============================ */

/* Return a freshly constructed message.
   To finish initializing the message, you must set the msgid and msgstr.  */
extern po_message_t po_message_create (void);

/* Return the context of a message, or NULL for a message not restricted to a
   context.  */
extern const char * po_message_msgctxt (po_message_t message);

/* Change the context of a message. NULL means a message not restricted to a
   context.  */
extern void po_message_set_msgctxt (po_message_t message, const char *msgctxt);

/* Return the msgid (untranslated English string) of a message.  */
extern const char * po_message_msgid (po_message_t message);

/* Change the msgid (untranslated English string) of a message.  */
extern void po_message_set_msgid (po_message_t message, const char *msgid);

/* Return the msgid_plural (untranslated English plural string) of a message,
   or NULL for a message without plural.  */
extern const char * po_message_msgid_plural (po_message_t message);

/* Change the msgid_plural (untranslated English plural string) of a message.
   NULL means a message without plural.  */
extern void po_message_set_msgid_plural (po_message_t message, const char *msgid_plural);

/* Return the msgstr (translation) of a message.
   Return the empty string for an untranslated message.  */
extern const char * po_message_msgstr (po_message_t message);

/* Change the msgstr (translation) of a message.
   Use an empty string to denote an untranslated message.  */
extern void po_message_set_msgstr (po_message_t message, const char *msgstr);

/* Return the msgstr[index] for a message with plural handling, or
   NULL when the index is out of range or for a message without plural.  */
extern const char * po_message_msgstr_plural (po_message_t message, int index);

/* Change the msgstr[index] for a message with plural handling.
   Use a NULL value at the end to reduce the number of plural forms.  */
extern void po_message_set_msgstr_plural (po_message_t message, int index, const char *msgstr);

/* Return the comments for a message.  */
extern const char * po_message_comments (po_message_t message);

/* Change the comments for a message.
   comments should be a multiline string, ending in a newline, or empty.  */
extern void po_message_set_comments (po_message_t message, const char *comments);

/* Return the extracted comments for a message.  */
extern const char * po_message_extracted_comments (po_message_t message);

/* Change the extracted comments for a message.
   comments should be a multiline string, ending in a newline, or empty.  */
extern void po_message_set_extracted_comments (po_message_t message, const char *comments);

/* Return the i-th file position for a message, or NULL if i is out of
   range.  */
extern po_filepos_t po_message_filepos (po_message_t message, int i);

/* Remove the i-th file position from a message.
   The indices of all following file positions for the message are decremented
   by one.  */
extern void po_message_remove_filepos (po_message_t message, int i);

/* Add a file position to a message, if it is not already present for the
   message.
   file is the file name.
   start_line is the line number where the string starts, or (size_t)(-1) if no
   line number is available.  */
extern void po_message_add_filepos (po_message_t message, const char *file, size_t start_line);

/* Return the previous context of a message, or NULL for none.  */
extern const char * po_message_prev_msgctxt (po_message_t message);

/* Change the previous context of a message.  NULL is allowed.  */
extern void po_message_set_prev_msgctxt (po_message_t message, const char *prev_msgctxt);

/* Return the previous msgid (untranslated English string) of a message, or
   NULL for none.  */
extern const char * po_message_prev_msgid (po_message_t message);

/* Change the previous msgid (untranslated English string) of a message.
   NULL is allowed.  */
extern void po_message_set_prev_msgid (po_message_t message, const char *prev_msgid);

/* Return the previous msgid_plural (untranslated English plural string) of a
   message, or NULL for none.  */
extern const char * po_message_prev_msgid_plural (po_message_t message);

/* Change the previous msgid_plural (untranslated English plural string) of a
   message.  NULL is allowed.  */
extern void po_message_set_prev_msgid_plural (po_message_t message, const char *prev_msgid_plural);

/* Return true if the message is marked obsolete.  */
extern int po_message_is_obsolete (po_message_t message);

/* Change the obsolete mark of a message.  */
extern void po_message_set_obsolete (po_message_t message, int obsolete);

/* Return true if the message is marked fuzzy.  */
extern int po_message_is_fuzzy (po_message_t message);

/* Change the fuzzy mark of a message.  */
extern void po_message_set_fuzzy (po_message_t message, int fuzzy);

/* Return true if the message is marked as being a format string of the given
   type (e.g. "c-format").  */
extern int po_message_is_format (po_message_t message, const char *format_type);

/* Change the format string mark for a given type of a message.  */
extern void po_message_set_format (po_message_t message, const char *format_type, /*bool*/int value);

/* If a numeric range of a message is set, return true and store the minimum
   and maximum value in *MINP and *MAXP.  */
extern int po_message_is_range (po_message_t message, int *minp, int *maxp);

/* Change the numeric range of a message.  MIN and MAX must be non-negative,
   with MIN < MAX.  Use MIN = MAX = -1 to remove the numeric range of a
   message.  */
extern void po_message_set_range (po_message_t message, int min, int max);

/* =========================== po_filepos_t API ============================ */

/* Return the file name.  */
extern const char * po_filepos_file (po_filepos_t filepos);

/* Return the line number where the string starts, or (size_t)(-1) if no line
   number is available.  */
extern size_t po_filepos_start_line (po_filepos_t filepos);

/* ============================ Format type API ============================= */

/* Return a NULL terminated array of the supported format types.  */
extern const char * const * po_format_list (void);

/* Return the pretty name associated with a format type.
   For example, for "csharp-format", return "C#".
   Return NULL if the argument is not a supported format type.  */
extern const char * po_format_pretty_name (const char *format_type);

/* ============================= Checking API ============================== */

/* Test whether an entire file PO file is valid, like msgfmt does it.
   If it is invalid, pass the reasons to the handler.  */
extern void po_file_check_all (po_file_t file, po_xerror_handler_t handler);

/* Test a single message, to be inserted in a PO file in memory, like msgfmt
   does it.  If it is invalid, pass the reasons to the handler.  The iterator
   is not modified by this call; it only specifies the file and the domain.  */
extern void po_message_check_all (po_message_t message, po_message_iterator_t iterator, po_xerror_handler_t handler);

/* Test whether the message translation is a valid format string if the message
   is marked as being a format string.  If it is invalid, pass the reasons to
   the handler.  */
#define po_message_check_format po_message_check_format_v2
extern void po_message_check_format (po_message_t message, po_xerror_handler_t handler);

#ifdef __cplusplus
}
#endif

#endif /* _GETTEXT_PO_H */


text:
<?php

namespace Hshn\SerializerExtraBundle\Functional\Bundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * @author Shota Hoshino <lga0503@gmail.com>
 */
class HshnSerializerExtraTestBundle extends Bundle
{

}


text:
package org.jetbrains.plugins.scala.lang

import com.intellij.lang.ASTNode
import com.intellij.psi.tree.IElementType
import org.jetbrains.plugins.scala.extensions.PsiElementExt
import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes
import org.jetbrains.plugins.scala.lang.psi.api.expr.{ScArgumentExprList, ScBlockExpr}

package object formatting {

  private[formatting]
  implicit class ScArgumentExprListOps(private val args: ScArgumentExprList) extends AnyVal {

    /**
     * @example {{{
     * seq.map { p =>
     *   ...
     * }
     * }}}
     *
     */
    def isSingleInfixBlockExpression: Boolean =
      args match {
        case ScArgumentExprList(_: ScBlockExpr) =>
          // no need to also check for last child, cause parser will not capture it without opening parenthesis
          val firstChild = args.firstChild
          firstChild.forall(_.elementType != ScalaTokenTypes.tLPARENTHESIS)
        case _ =>
          false
      }
  }

  @inline
  private[formatting]
  def isYieldOrDo(node: ASTNode): Boolean =
    isYieldOrDo(node.getElementType)

  @inline
  private[formatting]
  def isYieldOrDo(elementType: IElementType): Boolean =
    ScalaTokenTypes.YIELD_OR_DO.contains(elementType)
}


text:
package com.tlkzzz.jeesite.modules.gen.dao;

import com.tlkzzz.jeesite.common.persistence.CrudDao;
import com.tlkzzz.jeesite.common.persistence.annotation.MyBatisDao;
import com.tlkzzz.jeesite.modules.gen.entity.GenTemplate;

/**
 * 代码模板DAO接口
 * @author tlkzzz
 * @version 2013-10-15
 */
@MyBatisDao
public interface GenTemplateDao extends CrudDao<GenTemplate> {

}


text:
Testing
=======

Testing is an important part of software development. Whether we are aware of it or not, we conduct testing continuously.
For example, when we write a class in PHP, we may debug it step by step or simply use `echo` or `die` statements to verify
the implementation works according to our initial plan. In the case of a web application, we're entering some test data
in forms to ensure the page interacts with us as expected.

The testing process could be automated so that each time when we need to verify something, we just need to call up
the code that does it for us. The code that verifies the result matches what we've planned is called *test* and
the process of its creation and further execution is known as *automated testing*, which is the main topic of these
testing chapters.

## Developing with tests

Test-Driven Development (TDD) and Behavior-Driven Development (BDD) are approaches of developing
software by describing behavior of a piece of code or the whole feature as a set of scenarios or tests before
writing actual code and only then creating the implementation that allows these tests to pass verifying that intended
behavior is achieved.

The process of developing a feature is the following:

- Create a new test that describes a feature to be implemented.
- Run the new test and make sure it fails. It is expected since there's no implementation yet.
- Write simple code to make the new test pass.
- Run all tests and make sure they all pass.
- Improve code and make sure tests are still OK.

After it's done the process is repeated again for another feature or improvement. If the existing feature is to be changed,
tests should be changed as well.

> Tip: If you feel that you are losing time doing a lot of small and simple iterations, try covering more by your
> test scenario so you do more before executing tests again. If you're debugging too much, try doing the opposite.

The reason to create tests before doing any implementation is that it allows us to focus on what we want to achieve
and fully dive into "how to do it" afterwards. Usually it leads to better abstractions and easier test maintenance when
it comes to feature adjustments or less coupled components.

So to sum up the advantages of such approach are the following:

- Keeps you focused on one thing at a time which results in improved planning and implementation.
- Results in test-covering more features in greater detail i.e. if tests are OK most likely nothing's broken.

In the long term it usually gives you a good time-saving effect.

## When and how to test

While the test first approach described above makes sense for long term and relatively complex projects it could be overkill
for simpler ones. There are some indicators of when it's appropriate:

- Project is already large and complex.
- Project requirements are starting to get complex. Project grows constantly.
- Project is meant to be long term.
- The cost of the failure is too high.

There's nothing wrong in creating tests covering behavior of existing implementation.

- Project is a legacy one to be gradually renewed.
- You've got a project to work on and it has no tests.

In some cases any form of automated testing could be overkill:

- Project is simple and isn't getting anymore complex.
- It's a one-time project that will no longer be worked on.

Still if you have time it's good to automate testing in these cases as well.

## Further reading

- Test Driven Development: By Example / Kent Beck. ISBN: 0321146530.


text:
import '../src'
import bufferEqual from 'buffer-equal'
import gulp from 'gulp'
import imageSize from 'image-size'
import timeout from 'timeout-then'
import rump from 'rump'
import {colors} from 'gulp-util'
import {exists, readFile, stat, writeFile} from 'mz/fs'
import {sep} from 'path'
import {spy} from 'sinon'

const {stripColor} = colors

describe('tasks', function() {
  this.timeout(0)

  afterEach(() => {
    rump.configure({
      paths: {
        source: {root: 'test/fixtures/src', images: ''},
        destination: {root: 'tmp', images: ''},
      },
      images: {retina: true},
    })
  })

  it('are added and defined', () => {
    const callback = spy()
    rump.on('gulp:main', callback)
    rump.on('gulp:images', callback)
    rump.addGulpTasks({prefix: 'spec'})
    callback.should.be.calledTwice()
    gulp.tasks['spec:info:images'].should.be.ok()
    gulp.tasks['spec:build:images'].should.be.ok()
    gulp.tasks['spec:watch:images'].should.be.ok()
  })

  it('display correct information in info task', () => {
    const logs = [],
          {log} = console
    console.log = newLog
    gulp.start('spec:info')
    console.log = log
    logs.slice(-7).should.eql([
      '',
      '--- Images v0.8.0',
      `Images from test${sep}fixtures${sep}src are copied to tmp`,
      'Affected files (* - non-retina copies also generated):',
      'image1.png',
      'image2@2x.jpg *',
      '',
    ])
    logs.length = 0
    console.log = newLog
    gulp.start('spec:info:prod')
    console.log = log
    logs.slice(-7).should.eql([
      '',
      '--- Images v0.8.0',
      `Images from test${sep}fixtures${sep}src are minified and copied to tmp`,
      'Affected files (* - non-retina copies also generated):',
      'image1.png',
      'image2@2x.jpg *',
      '',
    ])
    rump.reconfigure({images: {retina: false}})
    logs.length = 0
    console.log = newLog
    gulp.start('spec:info')
    console.log = log
    logs.slice(-7).should.eql([
      '',
      '--- Images v0.8.0',
      `Images from test${sep}fixtures${sep}src are minified and copied to tmp`,
      'Affected files:',
      'image1.png',
      'image2@2x.jpg',
      '',
    ])
    rump.reconfigure({paths: {source: {images: 'nonexistant'}}})
    logs.length = 0
    console.log = newLog
    gulp.start('spec:info')
    console.log = log
    logs.length.should.not.be.above(4)

    function newLog(...args) {
      logs.push(stripColor(args.join(' ')))
    }
  })

  it('for building', async() => {
    const originals = await Promise.all([
      readFile('test/fixtures/src/image1.png'),
      readFile('test/fixtures/src/image2@2x.jpg'),
    ])
    let contents, nonRetinaExists
    await new Promise(resolve => {
      gulp.task('postbuild', ['spec:build'], resolve)
      gulp.start('postbuild')
    })
    contents = await Promise.all([
      readFile('tmp/image1.png'),
      readFile('tmp/image2@2x.jpg'),
    ])
    contents.forEach((content, index) => {
      bufferEqual(originals[index], content).should.be.true()
    })
    nonRetinaExists = await exists('tmp/image2.jpg')
    nonRetinaExists.should.be.true()
  })

  describe('for watching', () => {
    let original

    before(async() => {
      original = await readFile('test/fixtures/src/image1.png')
      await new Promise(resolve => {
        gulp.task('postwatch', ['spec:watch'], resolve)
        gulp.start('postwatch')
      })
    })

    beforeEach(() => timeout(1000))

    afterEach(() => writeFile('test/fixtures/src/image1.png', original))

    it('handles updates', async() => {
      let content = await readFile('tmp/image1.png')
      bufferEqual(original, await readFile('tmp/image1.png')).should.be.true()
      content = await readFile('test/fixtures/new/image1.png')
      await timeout(1000)
      await writeFile('test/fixtures/src/image1.png', content)
      await timeout(1000)
      bufferEqual(original, await readFile('tmp/image1.png')).should.be.false()
    })

    it('handles retina images', () => {
      const {width, height} = imageSize('tmp/image2.jpg'),
            retinaSize = imageSize('tmp/image2@2x.jpg')
      retinaSize.width.should.equal(width * 2)
      retinaSize.height.should.equal(height * 2)
    })

    it('handles minification in production', async() => {
      let sourceStat = await stat('test/fixtures/src/image1.png'),
          destinationStat = await stat('tmp/image1.png')
      sourceStat.size.should.equal(destinationStat.size)
      rump.reconfigure({environment: 'production'})
      await timeout(1000)
      await writeFile('test/fixtures/src/image1.png', original)
      await timeout(1000);
      [sourceStat, destinationStat] = await Promise.all([
        stat('test/fixtures/src/image1.png'),
        stat('tmp/image1.png'),
      ])
      sourceStat.size.should.be.above(destinationStat.size)
    })
  })
})


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SchoolSystem.Fee_Management
{
    public partial class ConcessionReport : UserControl
    {
        public ConcessionReport()
        {
            InitializeComponent();
        }
    }
}


text:
<?php

namespace Ck\Evt\BackendBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CkEvtBackendBundle extends Bundle
{
}


text:
package net.sourceforge.marathon.util;

import java.awt.Desktop;
import java.net.URI;
import java.util.logging.Logger;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.html.HTMLAnchorElement;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.scene.web.WebView;

public class HyperlinkRedirectListener implements ChangeListener<State>, EventListener {
    private static final Logger LOGGER = Logger.getLogger(HyperlinkRedirectListener.class.getName());

    private static final String CLICK_EVENT = "click";
    private static final String ANCHOR_TAG = "a";

    private final WebView webView;

    public HyperlinkRedirectListener(WebView webView) {
        this.webView = webView;
    }

    @Override
    public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
        if (State.SUCCEEDED.equals(newValue)) {
            Document document = webView.getEngine().getDocument();
            NodeList anchors = document.getElementsByTagName(ANCHOR_TAG);
            for (int i = 0; i < anchors.getLength(); i++) {
                Node node = anchors.item(i);
                EventTarget eventTarget = (EventTarget) node;
                eventTarget.addEventListener(CLICK_EVENT, this, false);
            }
        }
    }

    @Override
    public void handleEvent(Event event) {
        HTMLAnchorElement anchorElement = (HTMLAnchorElement) event.getCurrentTarget();
        String href = anchorElement.getHref();

        if (Desktop.isDesktopSupported()) {
            openLinkInSystemBrowser(href);
        } else {
            LOGGER.warning("OS does not support desktop operations like browsing. Cannot open link '{" + href + "}'.");
        }

        event.preventDefault();
    }

    private void openLinkInSystemBrowser(String url) {
        LOGGER.info("Opening link '{" + url + "}' in default system browser.");

        try {
            URI uri = new URI(url);
            Desktop.getDesktop().browse(uri);
        } catch (Throwable e) {
            LOGGER.warning("Error on opening link '{" + url + "}' in system browser.");
        }
    }
}


text:
SELECT "contents".* FROM "contents" AS "contents" WHERE (("contents"."id" = 2));
SELECT "contents".* FROM "contents" AS "contents" WHERE "contents"."id" IN (1);
SELECT "contents".* FROM "contents" AS "contents" WHERE "contents"."thread_id" IN (1);
SELECT "contents".* FROM "contents" AS "contents" WHERE "contents"."id" IN (1);
START TRANSACTION;
DELETE FROM "contents" WHERE "id" = 2;
DELETE FROM "contents" WHERE "id" = 3;
DELETE FROM "contents" WHERE "id" = 1;
COMMIT;


text:
module SameSiteSecurity
  class Middleware
    def initialize(app)
      @app = app
    end

    def call(env)
      Rack::Request.new(env)
      status, headers, response = @app.call(env)
      if (cookies = headers["Set-Cookie"])
        cookies = cookies.split("\n") unless cookies.is_a?(Array)

        headers["Set-Cookie"] = cookies.map { |cookie|
          "#{cookie}; SameSite=Lax"
        }.join("\n")
      end
      [status, headers, response]
    end
  end
end


text:
'use strict';

var _utils = require('./utils');

var _validate = _interopRequireDefault(require('./validate'));

var _validateCLIOptions = _interopRequireDefault(
  require('./validateCLIOptions')
);

var _condition = require('./condition');

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {default: obj};
}

module.exports = {
  ValidationError: _utils.ValidationError,
  createDidYouMeanMessage: _utils.createDidYouMeanMessage,
  format: _utils.format,
  logValidationWarning: _utils.logValidationWarning,
  multipleValidOptions: _condition.multipleValidOptions,
  validate: _validate.default,
  validateCLIOptions: _validateCLIOptions.default
};


text:
package org.literacyapp.util;

import android.os.Environment;

import org.literacyapp.dao.Audio;
import org.literacyapp.dao.Image;
import org.literacyapp.dao.Video;

import java.io.File;

public class MultimediaHelper {

    public static File getMultimediaDirectory() {
        File multimediaDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "LiteracyApp" + File.separator + "multimedia");
        if (!multimediaDirectory.exists()) {
            multimediaDirectory.mkdirs();
        }
        return multimediaDirectory;
    }

    public static File getAudioDirectory() {
        File audioDirectory = new File(getMultimediaDirectory(), "audio");
        if (!audioDirectory.exists()) {
            audioDirectory.mkdir();
        }
        return audioDirectory;
    }

    public static File getImageDirectory() {
        File imageDirectory = new File(getMultimediaDirectory(), "image");
        if (!imageDirectory.exists()) {
            imageDirectory.mkdir();
        }
        return imageDirectory;
    }

    public static File getVideoDirectory() {
        File videoDirectory = new File(getMultimediaDirectory(), "video");
        if (!videoDirectory.exists()) {
            videoDirectory.mkdir();
        }
        return videoDirectory;
    }

    public static File getStudentImageDirectory() {
        File studentImageDirectory = new File(getMultimediaDirectory(), "studentImage");
        if (!studentImageDirectory.exists()) {
            studentImageDirectory.mkdir();
        }
        return studentImageDirectory;
    }

    public static File getFile(Audio audio) {
        File file = null;

        if (audio == null) {
            return null;
        }

        File audioDirectory = getAudioDirectory();
        file = new File(audioDirectory, audio.getId() + "_r" + audio.getRevisionNumber() + "." + audio.getAudioFormat().toString().toLowerCase());

        return file;
    }

    public static File getFile(Image image) {
        File file = null;

        if (image == null) {
            return null;
        }

        File imageDirectory = getImageDirectory();
        file = new File(imageDirectory, image.getId() + "_r" + image.getRevisionNumber() + "." + image.getImageFormat().toString().toLowerCase());

        return file;
    }

    public static File getFile(Video video) {
        File file = null;

        if (video == null) {
            return null;
        }

        File videoDirectory = getVideoDirectory();
        file = new File(videoDirectory, video.getId() + "_r" + video.getRevisionNumber() + "." + video.getVideoFormat().toString().toLowerCase());

        return file;
    }
}


text:
package e2e

import (
	"fmt"
	"time"

	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/kubernetes/pkg/api/v1"
	"k8s.io/kubernetes/pkg/controller/replication"
	"k8s.io/kubernetes/test/e2e/framework"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = framework.KubeDescribe("ReplicationController", func() {
	f := framework.NewDefaultFramework("replication-controller")

	It("should serve a basic image on each replica with a public image [Conformance]", func() {
		testReplicationControllerServeImageOrFail(f, "basic", framework.ServeHostnameImage)
	})

	It("should serve a basic image on each replica with a private image", func() {
		// requires private images
		framework.SkipUnlessProviderIs("gce", "gke")

		testReplicationControllerServeImageOrFail(f, "private", "gcr.io/k8s-authenticated-test/serve_hostname:v1.4")
	})

	It("should surface a failure condition on a common issue like exceeded quota", func() {
		testReplicationControllerConditionCheck(f)
	})

	It("should adopt matching pods on creation", func() {
		testRCAdoptMatchingOrphans(f)
	})

	It("should release no longer matching pods", func() {
		testRCReleaseControlledNotMatching(f)
	})
})

func newRC(rsName string, replicas int32, rcPodLabels map[string]string, imageName string, image string) *v1.ReplicationController {
	zero := int64(0)
	return &v1.ReplicationController{
		ObjectMeta: metav1.ObjectMeta{
			Name: rsName,
		},
		Spec: v1.ReplicationControllerSpec{
			Replicas: func(i int32) *int32 { return &i }(replicas),
			Template: &v1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: rcPodLabels,
				},
				Spec: v1.PodSpec{
					TerminationGracePeriodSeconds: &zero,
					Containers: []v1.Container{
						{
							Name:  imageName,
							Image: image,
						},
					},
				},
			},
		},
	}
}

// A basic test to check the deployment of an image using
// a replication controller. The image serves its hostname
// which is checked for each replica.
func testReplicationControllerServeImageOrFail(f *framework.Framework, test string, image string) {
	name := "my-hostname-" + test + "-" + string(uuid.NewUUID())
	replicas := int32(1)

	// Create a replication controller for a service
	// that serves its hostname.
	// The source for the Docker containter kubernetes/serve_hostname is
	// in contrib/for-demos/serve_hostname
	By(fmt.Sprintf("Creating replication controller %s", name))
	newRC := newRC(name, replicas, map[string]string{"name": name}, name, image)
	newRC.Spec.Template.Spec.Containers[0].Ports = []v1.ContainerPort{{ContainerPort: 9376}}
	_, err := f.ClientSet.Core().ReplicationControllers(f.Namespace.Name).Create(newRC)
	Expect(err).NotTo(HaveOccurred())

	// Check that pods for the new RC were created.
	// TODO: Maybe switch PodsCreated to just check owner references.
	pods, err := framework.PodsCreated(f.ClientSet, f.Namespace.Name, name, replicas)
	Expect(err).NotTo(HaveOccurred())

	// Wait for the pods to enter the running state. Waiting loops until the pods
	// are running so non-running pods cause a timeout for this test.
	framework.Logf("Ensuring all pods for ReplicationController %q are running", name)
	running := int32(0)
	for _, pod := range pods.Items {
		if pod.DeletionTimestamp != nil {
			continue
		}
		err = f.WaitForPodRunning(pod.Name)
		if err != nil {
			updatePod, getErr := f.ClientSet.Core().Pods(f.Namespace.Name).Get(pod.Name, metav1.GetOptions{})
			if getErr == nil {
				err = fmt.Errorf("Pod %q never run (phase: %s, conditions: %+v): %v", updatePod.Name, updatePod.Status.Phase, updatePod.Status.Conditions, err)
			} else {
				err = fmt.Errorf("Pod %q never run: %v", pod.Name, err)
			}
		}
		Expect(err).NotTo(HaveOccurred())
		framework.Logf("Pod %q is running (conditions: %+v)", pod.Name, pod.Status.Conditions)
		running++
	}

	// Sanity check
	if running != replicas {
		Expect(fmt.Errorf("unexpected number of running pods: %+v", pods.Items)).NotTo(HaveOccurred())
	}

	// Verify that something is listening.
	framework.Logf("Trying to dial the pod")
	retryTimeout := 2 * time.Minute
	retryInterval := 5 * time.Second
	label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name}))
	err = wait.Poll(retryInterval, retryTimeout, framework.PodProxyResponseChecker(f.ClientSet, f.Namespace.Name, label, name, true, pods).CheckAllResponses)
	if err != nil {
		framework.Failf("Did not get expected responses within the timeout period of %.2f seconds.", retryTimeout.Seconds())
	}
}

// 1. Create a quota restricting pods in the current namespace to 2.
// 2. Create a replication controller that wants to run 3 pods.
// 3. Check replication controller conditions for a ReplicaFailure condition.
// 4. Relax quota or scale down the controller and observe the condition is gone.
func testReplicationControllerConditionCheck(f *framework.Framework) {
	c := f.ClientSet
	namespace := f.Namespace.Name
	name := "condition-test"

	framework.Logf("Creating quota %q that allows only two pods to run in the current namespace", name)
	quota := newPodQuota(name, "2")
	_, err := c.Core().ResourceQuotas(namespace).Create(quota)
	Expect(err).NotTo(HaveOccurred())

	err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
		quota, err = c.Core().ResourceQuotas(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return false, err
		}
		podQuota := quota.Status.Hard[v1.ResourcePods]
		quantity := resource.MustParse("2")
		return (&podQuota).Cmp(quantity) == 0, nil
	})
	if err == wait.ErrWaitTimeout {
		err = fmt.Errorf("resource quota %q never synced", name)
	}
	Expect(err).NotTo(HaveOccurred())

	By(fmt.Sprintf("Creating rc %q that asks for more than the allowed pod quota", name))
	rc := newRC(name, 3, map[string]string{"name": name}, nginxImageName, nginxImage)
	rc, err = c.Core().ReplicationControllers(namespace).Create(rc)
	Expect(err).NotTo(HaveOccurred())

	By(fmt.Sprintf("Checking rc %q has the desired failure condition set", name))
	generation := rc.Generation
	conditions := rc.Status.Conditions
	err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
		rc, err = c.Core().ReplicationControllers(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return false, err
		}

		if generation > rc.Status.ObservedGeneration {
			return false, nil
		}
		conditions = rc.Status.Conditions

		cond := replication.GetCondition(rc.Status, v1.ReplicationControllerReplicaFailure)
		return cond != nil, nil
	})
	if err == wait.ErrWaitTimeout {
		err = fmt.Errorf("rc manager never added the failure condition for rc %q: %#v", name, conditions)
	}
	Expect(err).NotTo(HaveOccurred())

	By(fmt.Sprintf("Scaling down rc %q to satisfy pod quota", name))
	rc, err = framework.UpdateReplicationControllerWithRetries(c, namespace, name, func(update *v1.ReplicationController) {
		x := int32(2)
		update.Spec.Replicas = &x
	})
	Expect(err).NotTo(HaveOccurred())

	By(fmt.Sprintf("Checking rc %q has no failure condition set", name))
	generation = rc.Generation
	conditions = rc.Status.Conditions
	err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
		rc, err = c.Core().ReplicationControllers(namespace).Get(name, metav1.GetOptions{})
		if err != nil {
			return false, err
		}

		if generation > rc.Status.ObservedGeneration {
			return false, nil
		}
		conditions = rc.Status.Conditions

		cond := replication.GetCondition(rc.Status, v1.ReplicationControllerReplicaFailure)
		return cond == nil, nil
	})
	if err == wait.ErrWaitTimeout {
		err = fmt.Errorf("rc manager never removed the failure condition for rc %q: %#v", name, conditions)
	}
	Expect(err).NotTo(HaveOccurred())
}

func testRCAdoptMatchingOrphans(f *framework.Framework) {
	name := "pod-adoption"
	By(fmt.Sprintf("Given a Pod with a 'name' label %s is created", name))
	p := f.PodClient().CreateSync(&v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
			Labels: map[string]string{
				"name": name,
			},
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:  name,
					Image: nginxImageName,
				},
			},
		},
	})

	By("When a replication controller with a matching selector is created")
	replicas := int32(1)
	rcSt := newRC(name, replicas, map[string]string{"name": name}, name, nginxImageName)
	rcSt.Spec.Selector = map[string]string{"name": name}
	rc, err := f.ClientSet.Core().ReplicationControllers(f.Namespace.Name).Create(rcSt)
	Expect(err).NotTo(HaveOccurred())

	By("Then the orphan pod is adopted")
	err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
		p2, err := f.ClientSet.Core().Pods(f.Namespace.Name).Get(p.Name, metav1.GetOptions{})
		// The Pod p should either be adopted or deleted by the RC
		if errors.IsNotFound(err) {
			return true, nil
		}
		Expect(err).NotTo(HaveOccurred())
		for _, owner := range p2.OwnerReferences {
			if *owner.Controller && owner.UID == rc.UID {
				// pod adopted
				return true, nil
			}
		}
		// pod still not adopted
		return false, nil
	})
	Expect(err).NotTo(HaveOccurred())
}

func testRCReleaseControlledNotMatching(f *framework.Framework) {
	name := "pod-release"
	By("Given a ReplicationController is created")
	replicas := int32(1)
	rcSt := newRC(name, replicas, map[string]string{"name": name}, name, nginxImageName)
	rcSt.Spec.Selector = map[string]string{"name": name}
	rc, err := f.ClientSet.Core().ReplicationControllers(f.Namespace.Name).Create(rcSt)
	Expect(err).NotTo(HaveOccurred())

	By("When the matched label of one of its pods change")
	pods, err := framework.PodsCreated(f.ClientSet, f.Namespace.Name, rc.Name, replicas)
	Expect(err).NotTo(HaveOccurred())

	p := pods.Items[0]
	err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
		pod, err := f.ClientSet.Core().Pods(f.Namespace.Name).Get(p.Name, metav1.GetOptions{})
		Expect(err).NotTo(HaveOccurred())

		pod.Labels = map[string]string{"name": "not-matching-name"}
		_, err = f.ClientSet.Core().Pods(f.Namespace.Name).Update(pod)
		if err != nil && errors.IsConflict(err) {
			return false, nil
		}
		if err != nil {
			return false, err
		}
		return true, nil
	})
	Expect(err).NotTo(HaveOccurred())

	By("Then the pod is released")
	err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
		p2, err := f.ClientSet.Core().Pods(f.Namespace.Name).Get(p.Name, metav1.GetOptions{})
		Expect(err).NotTo(HaveOccurred())
		for _, owner := range p2.OwnerReferences {
			if *owner.Controller && owner.UID == rc.UID {
				// pod still belonging to the replication controller
				return false, nil
			}
		}
		// pod already released
		return true, nil
	})
	Expect(err).NotTo(HaveOccurred())
}


text:
package help.de.smartics.maven.plugin.jboss.modules;

import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;

/**
 * Builds test instances of {@link Artifact}.
 */
public final class ArtifactBuilder
{
  // ********************************* Fields *********************************

  // --- constants ------------------------------------------------------------

  /**
   * The default groupId found in instances of this builder.
   *

   * The value of this constant is {@value}.
   *

   */
  public static final String DEFAULT_GROUP_ID = "de.smartics.test";

  /**
   * The default artifactId found in instances of this builder.
   *

   * The value of this constant is {@value}.
   *

   */
  public static final String DEFAULT_ARTIFACT_ID = "testArtifact";

  /**
   * The default version found in instances of this builder.
   *

   * The value of this constant is {@value}.
   *

   */
  public static final String DEFAULT_VERSION = "1.0";

  /**
   * The default type found in instances of this builder.
   *

   * The value of this constant is {@value}.
   *

   */
  public static final String DEFAULT_TYPE = "jar";

  /**
   * The default classifier found in instances of this builder.
   *

   * The value of this constant is {@value}.
   *

   */
  public static final String DEFAULT_CLASSIFIER = "sources";

  // --- members --------------------------------------------------------------

  /**
   * The group identifier of the artifact.
   */
  private String groupId;

  /**
   * The identifier of the artifact.
   */
  private String artifactId;

  /**
   * The version of the artifact.
   */
  private String version;

  /**
   * The type of the artifact.
   */
  private String type;

  /**
   * The classifier of the artifact.
   */
  private String classifier;

  // ****************************** Initializer *******************************

  // ****************************** Constructors ******************************

  private ArtifactBuilder()
  {
  }

  private ArtifactBuilder(final ArtifactBuilder builder)
  {
    this.groupId = builder.groupId;
    this.artifactId = builder.artifactId;
    this.version = builder.version;
    this.type = builder.type;
    this.classifier = builder.classifier;
  }

  // ****************************** Inner Classes *****************************

  // ********************************* Methods ********************************

  // --- init -----------------------------------------------------------------

  // --- get&set --------------------------------------------------------------

  /**
   * Sets the group identifier of the artifact.
   *
   * @param groupId the group identifier of the artifact.
   * @return a reference to this builder.
   */
  public ArtifactBuilder withGroupId(final String groupId)
  {
    this.groupId = groupId;
    return this;
  }

  /**
   * Sets the identifier of the artifact.
   *
   * @param artifactId the identifier of the artifact.
   * @return a reference to this builder.
   */
  public ArtifactBuilder withArtifactId(final String artifactId)
  {
    this.artifactId = artifactId;
    return this;
  }

  /**
   * Sets the version of the artifact to the specified version.
   *
   * @param version the version of the artifact.
   * @return a reference to this builder.
   */
  public ArtifactBuilder withVersion(final String version)
  {
    this.version = version;
    return this;
  }

  /**
   * Sets the type of the artifact.
   *
   * @param type the type of the artifact.
   * @return a reference to this builder.
   */
  public ArtifactBuilder withType(final String type)
  {
    this.type = type;
    return this;
  }

  /**
   * Sets the classifier of the artifact.
   *
   * @param classifier the classifier of the artifact.
   * @return a reference to this builder.
   */
  public ArtifactBuilder withClassifier(final String classifier)
  {
    this.classifier = classifier;
    return this;
  }

  // --- business -------------------------------------------------------------

  /**
   * Builds an empty instance of {@link ArtifactBuilder}.
   *
   * @return the created instance.
   */
  public static ArtifactBuilder a()
  {
    final ArtifactBuilder builder = new ArtifactBuilder();
    builder.withType(DEFAULT_TYPE);
    return builder;
  }

  /**
   * Builds default instance of {@link ArtifactBuilder}.
   *
   * @return the created instance.
   */
  public static ArtifactBuilder aDefault()
  {
    final ArtifactBuilder builder = a();

    builder.withGroupId(DEFAULT_GROUP_ID);
    builder.withArtifactId(DEFAULT_ARTIFACT_ID);
    builder.withVersion(DEFAULT_VERSION);
    builder.withClassifier(DEFAULT_CLASSIFIER);

    return builder;
  }

  /**
   * Builds a copy of this instance.
   *
   * @return a copy of this instance.
   */
  public ArtifactBuilder but()
  {
    return new ArtifactBuilder(this);
  }

  /**
   * Builds an instance of {@link Artifact}.
   *
   * @return the created instance.
   */
  public Artifact build()
  {
    return new DefaultArtifact(groupId, artifactId, classifier, type, version);
  }

  // --- object basics --------------------------------------------------------

  @Override
  public String toString()
  {
    final StringBuilder buffer = new StringBuilder(64);
    buffer.append("groupId=").append(groupId);
    buffer.append(" / artifactId=").append(artifactId);
    buffer.append(" / version=").append(version);
    buffer.append(" / type=").append(type);
    buffer.append(" / classifier=").append(classifier);
    return buffer.toString();
  }

}


text:
/*global define:false */
/**
 * Copyright 2012-2017 Craig Campbell
 *
 * 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.
 *
 * Mousetrap is a simple keyboard shortcut library for Javascript with
 * no external dependencies
 *
 * @version 1.6.2
 * @url craig.is/killing/mice
 */
(function(window, document, undefined) {

    // Check if mousetrap is used inside browser, if not, return
    if (!window) {
        return;
    }

    /**
     * mapping of special keycodes to their corresponding keys
     *
     * everything in this dictionary cannot use keypress events
     * so it has to be here to map to the correct keycodes for
     * keyup/keydown events
     *
     * @type {Object}
     */
    var _MAP = {
        8: 'backspace',
        9: 'tab',
        13: 'enter',
        16: 'shift',
        17: 'ctrl',
        18: 'alt',
        20: 'capslock',
        27: 'esc',
        32: 'space',
        33: 'pageup',
        34: 'pagedown',
        35: 'end',
        36: 'home',
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down',
        45: 'ins',
        46: 'del',
        91: 'meta',
        93: 'meta',
        224: 'meta'
    };

    /**
     * mapping for special characters so they can support
     *
     * this dictionary is only used incase you want to bind a
     * keyup or keydown event to one of these keys
     *
     * @type {Object}
     */
    var _KEYCODE_MAP = {
        106: '*',
        107: '+',
        109: '-',
        110: '.',
        111 : '/',
        186: ';',
        187: '=',
        188: ',',
        189: '-',
        190: '.',
        191: '/',
        192: '`',
        219: '[',
        220: '\\',
        221: ']',
        222: '\''
    };

    /**
     * this is a mapping of keys that require shift on a US keypad
     * back to the non shift equivelents
     *
     * this is so you can use keyup events with these keys
     *
     * note that this will only work reliably on US keyboards
     *
     * @type {Object}
     */
    var _SHIFT_MAP = {
        '~': '`',
        '!': '1',
        '@': '2',
        '#': '3',
        '$': '4',
        '%': '5',
        '^': '6',
        '&': '7',
        '*': '8',
        '(': '9',
        ')': '0',
        '_': '-',
        '+': '=',
        ':': ';',
        '\"': '\'',
        '<': ',',
        '>': '.',
        '?': '/',
        '|': '\\'
    };

    /**
     * this is a list of special strings you can use to map
     * to modifier keys when you specify your keyboard shortcuts
     *
     * @type {Object}
     */
    var _SPECIAL_ALIASES = {
        'option': 'alt',
        'command': 'meta',
        'return': 'enter',
        'escape': 'esc',
        'plus': '+',
        'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
    };

    /**
     * variable to store the flipped version of _MAP from above
     * needed to check if we should use keypress or not when no action
     * is specified
     *
     * @type {Object|undefined}
     */
    var _REVERSE_MAP;

    /**
     * loop through the f keys, f1 to f19 and add them to the map
     * programatically
     */
    for (var i = 1; i < 20; ++i) {
        _MAP[111 + i] = 'f' + i;
    }

    /**
     * loop through to map numbers on the numeric keypad
     */
    for (i = 0; i <= 9; ++i) {

        // This needs to use a string cause otherwise since 0 is falsey
        // mousetrap will never fire for numpad 0 pressed as part of a keydown
        // event.
        //
        // @see https://github.com/ccampbell/mousetrap/pull/258
        _MAP[i + 96] = i.toString();
    }

    /**
     * cross browser add event method
     *
     * @param {Element|HTMLDocument} object
     * @param {string} type
     * @param {Function} callback
     * @returns void
     */
    function _addEvent(object, type, callback) {
        if (object.addEventListener) {
            object.addEventListener(type, callback, false);
            return;
        }

        object.attachEvent('on' + type, callback);
    }

    /**
     * takes the event and returns the key character
     *
     * @param {Event} e
     * @return {string}
     */
    function _characterFromEvent(e) {

        // for keypress events we should return the character as is
        if (e.type == 'keypress') {
            var character = String.fromCharCode(e.which);

            // if the shift key is not pressed then it is safe to assume
            // that we want the character to be lowercase.  this means if
            // you accidentally have caps lock on then your key bindings
            // will continue to work
            //
            // the only side effect that might not be desired is if you
            // bind something like 'A' cause you want to trigger an
            // event when capital A is pressed caps lock will no longer
            // trigger the event.  shift+a will though.
            if (!e.shiftKey) {
                character = character.toLowerCase();
            }

            return character;
        }

        // for non keypress events the special maps are needed
        if (_MAP[e.which]) {
            return _MAP[e.which];
        }

        if (_KEYCODE_MAP[e.which]) {
            return _KEYCODE_MAP[e.which];
        }

        // if it is not in the special map

        // with keydown and keyup events the character seems to always
        // come in as an uppercase character whether you are pressing shift
        // or not.  we should make sure it is always lowercase for comparisons
        return String.fromCharCode(e.which).toLowerCase();
    }

    /**
     * checks if two arrays are equal
     *
     * @param {Array} modifiers1
     * @param {Array} modifiers2
     * @returns {boolean}
     */
    function _modifiersMatch(modifiers1, modifiers2) {
        return modifiers1.sort().join(',') === modifiers2.sort().join(',');
    }

    /**
     * takes a key event and figures out what the modifiers are
     *
     * @param {Event} e
     * @returns {Array}
     */
    function _eventModifiers(e) {
        var modifiers = [];

        if (e.shiftKey) {
            modifiers.push('shift');
        }

        if (e.altKey) {
            modifiers.push('alt');
        }

        if (e.ctrlKey) {
            modifiers.push('ctrl');
        }

        if (e.metaKey) {
            modifiers.push('meta');
        }

        return modifiers;
    }

    /**
     * prevents default for this event
     *
     * @param {Event} e
     * @returns void
     */
    function _preventDefault(e) {
        if (e.preventDefault) {
            e.preventDefault();
            return;
        }

        e.returnValue = false;
    }

    /**
     * stops propogation for this event
     *
     * @param {Event} e
     * @returns void
     */
    function _stopPropagation(e) {
        if (e.stopPropagation) {
            e.stopPropagation();
            return;
        }

        e.cancelBubble = true;
    }

    /**
     * determines if the keycode specified is a modifier key or not
     *
     * @param {string} key
     * @returns {boolean}
     */
    function _isModifier(key) {
        return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
    }

    /**
     * reverses the map lookup so that we can look for specific keys
     * to see what can and can't use keypress
     *
     * @return {Object}
     */
    function _getReverseMap() {
        if (!_REVERSE_MAP) {
            _REVERSE_MAP = {};
            for (var key in _MAP) {

                // pull out the numeric keypad from here cause keypress should
                // be able to detect the keys from the character
                if (key > 95 && key < 112) {
                    continue;
                }

                if (_MAP.hasOwnProperty(key)) {
                    _REVERSE_MAP[_MAP[key]] = key;
                }
            }
        }
        return _REVERSE_MAP;
    }

    /**
     * picks the best action based on the key combination
     *
     * @param {string} key - character for key
     * @param {Array} modifiers
     * @param {string=} action passed in
     */
    function _pickBestAction(key, modifiers, action) {

        // if no action was picked in we should try to pick the one
        // that we think would work best for this key
        if (!action) {
            action = _getReverseMap()[key] ? 'keydown' : 'keypress';
        }

        // modifier keys don't work as expected with keypress,
        // switch to keydown
        if (action == 'keypress' && modifiers.length) {
            action = 'keydown';
        }

        return action;
    }

    /**
     * Converts from a string key combination to an array
     *
     * @param  {string} combination like "command+shift+l"
     * @return {Array}
     */
    function _keysFromString(combination) {
        if (combination === '+') {
            return ['+'];
        }

        combination = combination.replace(/\+{2}/g, '+plus');
        return combination.split('+');
    }

    /**
     * Gets info for a specific key combination
     *
     * @param  {string} combination key combination ("command+s" or "a" or "*")
     * @param  {string=} action
     * @returns {Object}
     */
    function _getKeyInfo(combination, action) {
        var keys;
        var key;
        var i;
        var modifiers = [];

        // take the keys from this pattern and figure out what the actual
        // pattern is all about
        keys = _keysFromString(combination);

        for (i = 0; i < keys.length; ++i) {
            key = keys[i];

            // normalize key names
            if (_SPECIAL_ALIASES[key]) {
                key = _SPECIAL_ALIASES[key];
            }

            // if this is not a keypress event then we should
            // be smart about using shift keys
            // this will only work for US keyboards however
            if (action && action != 'keypress' && _SHIFT_MAP[key]) {
                key = _SHIFT_MAP[key];
                modifiers.push('shift');
            }

            // if this key is a modifier then add it to the list of modifiers
            if (_isModifier(key)) {
                modifiers.push(key);
            }
        }

        // depending on what the key combination is
        // we will try to pick the best event for it
        action = _pickBestAction(key, modifiers, action);

        return {
            key: key,
            modifiers: modifiers,
            action: action
        };
    }

    function _belongsTo(element, ancestor) {
        if (element === null || element === document) {
            return false;
        }

        if (element === ancestor) {
            return true;
        }

        return _belongsTo(element.parentNode, ancestor);
    }

    function Mousetrap(targetElement) {
        var self = this;

        targetElement = targetElement || document;

        if (!(self instanceof Mousetrap)) {
            return new Mousetrap(targetElement);
        }

        /**
         * element to attach key events to
         *
         * @type {Element}
         */
        self.target = targetElement;

        /**
         * a list of all the callbacks setup via Mousetrap.bind()
         *
         * @type {Object}
         */
        self._callbacks = {};

        /**
         * direct map of string combinations to callbacks used for trigger()
         *
         * @type {Object}
         */
        self._directMap = {};

        /**
         * keeps track of what level each sequence is at since multiple
         * sequences can start out with the same sequence
         *
         * @type {Object}
         */
        var _sequenceLevels = {};

        /**
         * variable to store the setTimeout call
         *
         * @type {null|number}
         */
        var _resetTimer;

        /**
         * temporary state where we will ignore the next keyup
         *
         * @type {boolean|string}
         */
        var _ignoreNextKeyup = false;

        /**
         * temporary state where we will ignore the next keypress
         *
         * @type {boolean}
         */
        var _ignoreNextKeypress = false;

        /**
         * are we currently inside of a sequence?
         * type of action ("keyup" or "keydown" or "keypress") or false
         *
         * @type {boolean|string}
         */
        var _nextExpectedAction = false;

        /**
         * resets all sequence counters except for the ones passed in
         *
         * @param {Object} doNotReset
         * @returns void
         */
        function _resetSequences(doNotReset) {
            doNotReset = doNotReset || {};

            var activeSequences = false,
                key;

            for (key in _sequenceLevels) {
                if (doNotReset[key]) {
                    activeSequences = true;
                    continue;
                }
                _sequenceLevels[key] = 0;
            }

            if (!activeSequences) {
                _nextExpectedAction = false;
            }
        }

        /**
         * finds all callbacks that match based on the keycode, modifiers,
         * and action
         *
         * @param {string} character
         * @param {Array} modifiers
         * @param {Event|Object} e
         * @param {string=} sequenceName - name of the sequence we are looking for
         * @param {string=} combination
         * @param {number=} level
         * @returns {Array}
         */
        function _getMatches(character, modifiers, e, sequenceName, combination, level) {
            var i;
            var callback;
            var matches = [];
            var action = e.type;

            // if there are no events related to this keycode
            if (!self._callbacks[character]) {
                return [];
            }

            // if a modifier key is coming up on its own we should allow it
            if (action == 'keyup' && _isModifier(character)) {
                modifiers = [character];
            }

            // loop through all callbacks for the key that was pressed
            // and see if any of them match
            for (i = 0; i < self._callbacks[character].length; ++i) {
                callback = self._callbacks[character][i];

                // if a sequence name is not specified, but this is a sequence at
                // the wrong level then move onto the next match
                if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) {
                    continue;
                }

                // if the action we are looking for doesn't match the action we got
                // then we should keep going
                if (action != callback.action) {
                    continue;
                }

                // if this is a keypress event and the meta key and control key
                // are not pressed that means that we need to only look at the
                // character, otherwise check the modifiers as well
                //
                // chrome will not fire a keypress if meta or control is down
                // safari will fire a keypress if meta or meta+shift is down
                // firefox will fire a keypress if meta or control is down
                if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) {

                    // when you bind a combination or sequence a second time it
                    // should overwrite the first one.  if a sequenceName or
                    // combination is specified in this call it does just that
                    //
                    // @todo make deleting its own method?
                    var deleteCombo = !sequenceName && callback.combo == combination;
                    var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level;
                    if (deleteCombo || deleteSequence) {
                        self._callbacks[character].splice(i, 1);
                    }

                    matches.push(callback);
                }
            }

            return matches;
        }

        /**
         * actually calls the callback function
         *
         * if your callback function returns false this will use the jquery
         * convention - prevent default and stop propogation on the event
         *
         * @param {Function} callback
         * @param {Event} e
         * @returns void
         */
        function _fireCallback(callback, e, combo, sequence) {

            // if this event should not happen stop here
            if (self.stopCallback(e, e.target || e.srcElement, combo, sequence)) {
                return;
            }

            if (callback(e, combo) === false) {
                _preventDefault(e);
                _stopPropagation(e);
            }
        }

        /**
         * handles a character key event
         *
         * @param {string} character
         * @param {Array} modifiers
         * @param {Event} e
         * @returns void
         */
        self._handleKey = function(character, modifiers, e) {
            var callbacks = _getMatches(character, modifiers, e);
            var i;
            var doNotReset = {};
            var maxLevel = 0;
            var processedSequenceCallback = false;

            // Calculate the maxLevel for sequences so we can only execute the longest callback sequence
            for (i = 0; i < callbacks.length; ++i) {
                if (callbacks[i].seq) {
                    maxLevel = Math.max(maxLevel, callbacks[i].level);
                }
            }

            // loop through matching callbacks for this key event
            for (i = 0; i < callbacks.length; ++i) {

                // fire for all sequence callbacks
                // this is because if for example you have multiple sequences
                // bound such as "g i" and "g t" they both need to fire the
                // callback for matching g cause otherwise you can only ever
                // match the first one
                if (callbacks[i].seq) {

                    // only fire callbacks for the maxLevel to prevent
                    // subsequences from also firing
                    //
                    // for example 'a option b' should not cause 'option b' to fire
                    // even though 'option b' is part of the other sequence
                    //
                    // any sequences that do not match here will be discarded
                    // below by the _resetSequences call
                    if (callbacks[i].level != maxLevel) {
                        continue;
                    }

                    processedSequenceCallback = true;

                    // keep a list of which sequences were matches for later
                    doNotReset[callbacks[i].seq] = 1;
                    _fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq);
                    continue;
                }

                // if there were no sequence matches but we are still here
                // that means this is a regular match so we should fire that
                if (!processedSequenceCallback) {
                    _fireCallback(callbacks[i].callback, e, callbacks[i].combo);
                }
            }

            // if the key you pressed matches the type of sequence without
            // being a modifier (ie "keyup" or "keypress") then we should
            // reset all sequences that were not matched by this event
            //
            // this is so, for example, if you have the sequence "h a t" and you
            // type "h e a r t" it does not match.  in this case the "e" will
            // cause the sequence to reset
            //
            // modifier keys are ignored because you can have a sequence
            // that contains modifiers such as "enter ctrl+space" and in most
            // cases the modifier key will be pressed before the next key
            //
            // also if you have a sequence such as "ctrl+b a" then pressing the
            // "b" key will trigger a "keypress" and a "keydown"
            //
            // the "keydown" is expected when there is a modifier, but the
            // "keypress" ends up matching the _nextExpectedAction since it occurs
            // after and that causes the sequence to reset
            //
            // we ignore keypresses in a sequence that directly follow a keydown
            // for the same character
            var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress;
            if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) {
                _resetSequences(doNotReset);
            }

            _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown';
        };

        /**
         * handles a keydown event
         *
         * @param {Event} e
         * @returns void
         */
        function _handleKeyEvent(e) {

            // normalize e.which for key events
            // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
            if (typeof e.which !== 'number') {
                e.which = e.keyCode;
            }

            var character = _characterFromEvent(e);

            // no character found then stop
            if (!character) {
                return;
            }

            // need to use === for the character check because the character can be 0
            if (e.type == 'keyup' && _ignoreNextKeyup === character) {
                _ignoreNextKeyup = false;
                return;
            }

            self.handleKey(character, _eventModifiers(e), e);
        }

        /**
         * called to set a 1 second timeout on the specified sequence
         *
         * this is so after each key press in the sequence you have 1 second
         * to press the next key before you have to start over
         *
         * @returns void
         */
        function _resetSequenceTimer() {
            clearTimeout(_resetTimer);
            _resetTimer = setTimeout(_resetSequences, 1000);
        }

        /**
         * binds a key sequence to an event
         *
         * @param {string} combo - combo specified in bind call
         * @param {Array} keys
         * @param {Function} callback
         * @param {string=} action
         * @returns void
         */
        function _bindSequence(combo, keys, callback, action) {

            // start off by adding a sequence level record for this combination
            // and setting the level to 0
            _sequenceLevels[combo] = 0;

            /**
             * callback to increase the sequence level for this sequence and reset
             * all other sequences that were active
             *
             * @param {string} nextAction
             * @returns {Function}
             */
            function _increaseSequence(nextAction) {
                return function() {
                    _nextExpectedAction = nextAction;
                    ++_sequenceLevels[combo];
                    _resetSequenceTimer();
                };
            }

            /**
             * wraps the specified callback inside of another function in order
             * to reset all sequence counters as soon as this sequence is done
             *
             * @param {Event} e
             * @returns void
             */
            function _callbackAndReset(e) {
                _fireCallback(callback, e, combo);

                // we should ignore the next key up if the action is key down
                // or keypress.  this is so if you finish a sequence and
                // release the key the final key will not trigger a keyup
                if (action !== 'keyup') {
                    _ignoreNextKeyup = _characterFromEvent(e);
                }

                // weird race condition if a sequence ends with the key
                // another sequence begins with
                setTimeout(_resetSequences, 10);
            }

            // loop through keys one at a time and bind the appropriate callback
            // function.  for any key leading up to the final one it should
            // increase the sequence. after the final, it should reset all sequences
            //
            // if an action is specified in the original bind call then that will
            // be used throughout.  otherwise we will pass the action that the
            // next key in the sequence should match.  this allows a sequence
            // to mix and match keypress and keydown events depending on which
            // ones are better suited to the key provided
            for (var i = 0; i < keys.length; ++i) {
                var isFinal = i + 1 === keys.length;
                var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action);
                _bindSingle(keys[i], wrappedCallback, action, combo, i);
            }
        }

        /**
         * binds a single keyboard combination
         *
         * @param {string} combination
         * @param {Function} callback
         * @param {string=} action
         * @param {string=} sequenceName - name of sequence if part of sequence
         * @param {number=} level - what part of the sequence the command is
         * @returns void
         */
        function _bindSingle(combination, callback, action, sequenceName, level) {

            // store a direct mapped reference for use with Mousetrap.trigger
            self._directMap[combination + ':' + action] = callback;

            // make sure multiple spaces in a row become a single space
            combination = combination.replace(/\s+/g, ' ');

            var sequence = combination.split(' ');
            var info;

            // if this pattern is a sequence of keys then run through this method
            // to reprocess each pattern one key at a time
            if (sequence.length > 1) {
                _bindSequence(combination, sequence, callback, action);
                return;
            }

            info = _getKeyInfo(combination, action);

            // make sure to initialize array if this is the first time
            // a callback is added for this key
            self._callbacks[info.key] = self._callbacks[info.key] || [];

            // remove an existing match if there is one
            _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);

            // add this call back to the array
            // if it is a sequence put it at the beginning
            // if not put it at the end
            //
            // this is important because the way these are processed expects
            // the sequence ones to come first
            self._callbacks[info.key][sequenceName ? 'unshift' : 'push']({
                callback: callback,
                modifiers: info.modifiers,
                action: info.action,
                seq: sequenceName,
                level: level,
                combo: combination
            });
        }

        /**
         * binds multiple combinations to the same callback
         *
         * @param {Array} combinations
         * @param {Function} callback
         * @param {string|undefined} action
         * @returns void
         */
        self._bindMultiple = function(combinations, callback, action) {
            for (var i = 0; i < combinations.length; ++i) {
                _bindSingle(combinations[i], callback, action);
            }
        };

        // start!
        _addEvent(targetElement, 'keypress', _handleKeyEvent);
        _addEvent(targetElement, 'keydown', _handleKeyEvent);
        _addEvent(targetElement, 'keyup', _handleKeyEvent);
    }

    /**
     * binds an event to mousetrap
     *
     * can be a single key, a combination of keys separated with +,
     * an array of keys, or a sequence of keys separated by spaces
     *
     * be sure to list the modifier keys first to make sure that the
     * correct key ends up getting bound (the last key in the pattern)
     *
     * @param {string|Array} keys
     * @param {Function} callback
     * @param {string=} action - 'keypress', 'keydown', or 'keyup'
     * @returns void
     */
    Mousetrap.prototype.bind = function(keys, callback, action) {
        var self = this;
        keys = keys instanceof Array ? keys : [keys];
        self._bindMultiple.call(self, keys, callback, action);
        return self;
    };

    /**
     * unbinds an event to mousetrap
     *
     * the unbinding sets the callback function of the specified key combo
     * to an empty function and deletes the corresponding key in the
     * _directMap dict.
     *
     * TODO: actually remove this from the _callbacks dictionary instead
     * of binding an empty function
     *
     * the keycombo+action has to be exactly the same as
     * it was defined in the bind method
     *
     * @param {string|Array} keys
     * @param {string} action
     * @returns void
     */
    Mousetrap.prototype.unbind = function(keys, action) {
        var self = this;
        return self.bind.call(self, keys, function() {}, action);
    };

    /**
     * triggers an event that has already been bound
     *
     * @param {string} keys
     * @param {string=} action
     * @returns void
     */
    Mousetrap.prototype.trigger = function(keys, action) {
        var self = this;
        if (self._directMap[keys + ':' + action]) {
            self._directMap[keys + ':' + action]({}, keys);
        }
        return self;
    };

    /**
     * resets the library back to its initial state.  this is useful
     * if you want to clear out the current keyboard shortcuts and bind
     * new ones - for example if you switch to another page
     *
     * @returns void
     */
    Mousetrap.prototype.reset = function() {
        var self = this;
        self._callbacks = {};
        self._directMap = {};
        return self;
    };

    /**
     * should we stop this event before firing off callbacks
     *
     * @param {Event} e
     * @param {Element} element
     * @return {boolean}
     */
    Mousetrap.prototype.stopCallback = function(e, element) {
        var self = this;

        // if the element has the class "mousetrap" then no need to stop
        if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
            return false;
        }

        if (_belongsTo(element, self.target)) {
            return false;
        }

        // stop for input, select, and textarea
        return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable;
    };

    /**
     * exposes _handleKey publicly so it can be overwritten by extensions
     */
    Mousetrap.prototype.handleKey = function() {
        var self = this;
        return self._handleKey.apply(self, arguments);
    };

    /**
     * allow custom key mappings
     */
    Mousetrap.addKeycodes = function(object) {
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                _MAP[key] = object[key];
            }
        }
        _REVERSE_MAP = null;
    };

    /**
     * Init the global mousetrap functions
     *
     * This method is needed to allow the global mousetrap functions to work
     * now that mousetrap is a constructor function.
     */
    Mousetrap.init = function() {
        var documentMousetrap = Mousetrap(document);
        for (var method in documentMousetrap) {
            if (method.charAt(0) !== '_') {
                Mousetrap[method] = (function(method) {
                    return function() {
                        return documentMousetrap[method].apply(documentMousetrap, arguments);
                    };
                } (method));
            }
        }
    };

    Mousetrap.init();

    // expose mousetrap to the global object
    window.Mousetrap = Mousetrap;

    // expose as a common js module
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = Mousetrap;
    }

    // expose mousetrap as an AMD module
    if (typeof define === 'function' && define.amd) {
        define(function() {
            return Mousetrap;
        });
    }
}) (typeof window !== 'undefined' ? window : null, typeof  window !== 'undefined' ? document : null);