text:
/** @file queryparser.h
 * @brief parsing a user query string to build a Xapian::Query object
 */
/* Copyright (C) 2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018 Olly Betts
 * Copyright (C) 2010 Adam Sjøgren
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
 * USA
 */

#ifndef XAPIAN_INCLUDED_QUERYPARSER_H
#define XAPIAN_INCLUDED_QUERYPARSER_H

#if !defined XAPIAN_IN_XAPIAN_H && !defined XAPIAN_LIB_BUILD
# error "Never use <xapian/queryparser.h> directly; include <xapian.h> instead."
#endif

#include "xapian/attributes.h"
#include "xapian/intrusive_ptr.h"
#include "xapian/query.h"
#include "xapian/termiterator.h"
#include "xapian/visibility.h"

#include <string>
#include <unordered_set>

namespace Xapian {

class Database;
class Stem;

/// Base class for stop-word decision functor.
class XAPIAN_VISIBILITY_DEFAULT Stopper
    : public Xapian::Internal::opt_intrusive_base {
    /// Don't allow assignment.
    void operator=(const Stopper &) = delete;

    /// Don't allow copying.
    Stopper(const Stopper &) = delete;

  public:
    /// Default constructor.
    Stopper() { }

    /** Is term a stop-word?
     *
     *  @param term	The term to test.
     */
    virtual bool operator()(const std::string & term) const = 0;

    /// Class has virtual methods, so provide a virtual destructor.
    virtual ~Stopper() { }

    /// Return a string describing this object.
    virtual std::string get_description() const;

    /** Start reference counting this object.
     *
     *  You can hand ownership of a dynamically allocated Stopper
     *  object to Xapian by calling release() and then passing the object to a
     *  Xapian method.  Xapian will arrange to delete the object once it is no
     *  longer required.
     */
    Stopper * release() {
	opt_intrusive_base::release();
	return this;
    }

    /** Start reference counting this object.
     *
     *  You can hand ownership of a dynamically allocated Stopper
     *  object to Xapian by calling release() and then passing the object to a
     *  Xapian method.  Xapian will arrange to delete the object once it is no
     *  longer required.
     */
    const Stopper * release() const {
	opt_intrusive_base::release();
	return this;
    }
};

/// Simple implementation of Stopper class - this will suit most users.
class XAPIAN_VISIBILITY_DEFAULT SimpleStopper : public Stopper {
    std::unordered_set<std::string> stop_words;

  public:
    /// Default constructor.
    SimpleStopper() { }

    /** Initialise from a pair of iterators.
     *
     * Xapian includes stop list files for many languages. You can initialise from a file like that:
     * @code
     * ifstream words("stopwords/english/stop.txt");
     * Xapian::SimplerStopper stopper(istream_iterator<string>(words), istream_iterator<string>());
     * @endcode
     *
     */
    template<class Iterator>
    SimpleStopper(Iterator begin, Iterator end) : stop_words(begin, end) { }

    /// Add a single stop word.
    void add(const std::string & word) { stop_words.insert(word); }

    virtual bool operator()(const std::string & term) const {
	return stop_words.find(term) != stop_words.end();
    }

    virtual std::string get_description() const;
};

enum {
    RP_SUFFIX = 1,
    RP_REPEATED = 2,
    RP_DATE_PREFER_MDY = 4
};

/// Base class for range processors.
class XAPIAN_VISIBILITY_DEFAULT RangeProcessor
    : public Xapian::Internal::opt_intrusive_base {
    /// Don't allow assignment.
    void operator=(const RangeProcessor &);

    /// Don't allow copying.
    RangeProcessor(const RangeProcessor &);

  protected:
    /** The value slot to process.
     *
     *  If this range processor isn't value-based, it can ignore this member.
     */
    Xapian::valueno slot;

    /** The prefix (or suffix with RP_SUFFIX) string to look for. */
    std::string str;

    /** Flags.
     *
     *  Bitwise-or (| in C++) of zero or more of the following:
     *  * Xapian::RP_SUFFIX - require @a str as a suffix
     *    instead of a prefix.
     *  * Xapian::RP_REPEATED - optionally allow @a str
     *    on both ends of the range - e.g. $1..$10 or
     *    5m..50m.  By default a prefix is only checked for on
     *    the start (e.g. date:1/1/1980..31/12/1989), and a
     *    suffix only on the end (e.g. 2..12kg).
     */
    unsigned flags;

  public:
    /** Default constructor. */
    RangeProcessor() : slot(Xapian::BAD_VALUENO), flags(0) { }

    /** Constructor.
     *
     *  @param slot_	Which value slot to generate ranges over.
     *  @param str_	A string to look for to recognise values as belonging
     *			to this range (as a prefix by default, or as a suffix
     *			if flags Xapian::RP_SUFFIX is specified).
     *  @param flags_	Zero or more of the following flags, combined with
     *			bitwise-or (| in C++):
     *			 * Xapian::RP_SUFFIX - require @a str_ as a suffix
     *			   instead of a prefix.
     *			 * Xapian::RP_REPEATED - optionally allow @a str_
     *			   on both ends of the range - e.g. $1..$10 or
     *			   5m..50m.  By default a prefix is only checked for on
     *			   the start (e.g. date:1/1/1980..31/12/1989), and a
     *			   suffix only on the end (e.g. 2..12kg).
     */
    explicit RangeProcessor(Xapian::valueno slot_,
			    const std::string& str_ = std::string(),
			    unsigned flags_ = 0)
	: slot(slot_), str(str_), flags(flags_) { }

    /// Destructor.
    virtual ~RangeProcessor();

    /** Check prefix/suffix on range.
     *
     *  If they match, remove the prefix/suffix and then call operator()()
     *  to try to handle the range.
     */
    Xapian::Query check_range(const std::string& b, const std::string& e);

    /** Check for a valid range of this type.
     *
     *  Override this method to implement your own range handling.
     *
     *  @param begin	The start of the range as specified in the query string
     *			by the user.
     *  @param end	The end of the range as specified in the query string
     *			by the user (empty string for no upper limit).
     *
     *  @return		An OP_VALUE_RANGE Query object (or if end.empty(), an
     *			OP_VALUE_GE Query object).  Or if the range isn't one
     *			which this object can handle then
     *			Xapian::Query(Xapian::Query::OP_INVALID) will be
     *			returned.
     */
    virtual Xapian::Query
	operator()(const std::string &begin, const std::string &end);

    /** Start reference counting this object.
     *
     *  You can hand ownership of a dynamically allocated RangeProcessor
     *  object to Xapian by calling release() and then passing the object to a
     *  Xapian method.  Xapian will arrange to delete the object once it is no
     *  longer required.
     */
    RangeProcessor * release() {
	opt_intrusive_base::release();
	return this;
    }

    /** Start reference counting this object.
     *
     *  You can hand ownership of a dynamically allocated RangeProcessor
     *  object to Xapian by calling release() and then passing the object to a
     *  Xapian method.  Xapian will arrange to delete the object once it is no
     *  longer required.
     */
    const RangeProcessor * release() const {
	opt_intrusive_base::release();
	return this;
    }
};

/** Handle a date range.
 *
 *  Begin and end must be dates in a recognised format.
 */
class XAPIAN_VISIBILITY_DEFAULT DateRangeProcessor : public RangeProcessor {
    int epoch_year;

  public:
    /** Constructor.
     *
     *  @param slot_	The value number to return from operator().
     *
     *  @param flags_	Zero or more of the following flags, combined with
     *			bitwise-or:
     *			 * Xapian::RP_DATE_PREFER_MDY - interpret ambiguous
     *			   dates as month/day/year rather than day/month/year.
     *
     *  @param epoch_year_  Year to use as the epoch for dates with 2 digit
     *			    years (default: 1970, so 1/1/69 is 2069 while
     *			    1/1/70 is 1970).
     */
    explicit DateRangeProcessor(Xapian::valueno slot_,
				unsigned flags_ = 0,
				int epoch_year_ = 1970)
	: RangeProcessor(slot_, std::string(), flags_),
	  epoch_year(epoch_year_) { }

    /** Constructor.
     *
     *  @param slot_	The value slot number to query.
     *
     *  @param str_	A string to look for to recognise values as belonging
     *			to this date range.
     *
     *  @param flags_	Zero or more of the following flags, combined with
     *			bitwise-or:
     *			 * Xapian::RP_SUFFIX - require @a str_ as a suffix
     *			   instead of a prefix.
     *			 * Xapian::RP_REPEATED - optionally allow @a str_
     *			   on both ends of the range - e.g. $1..$10 or
     *			   5m..50m.  By default a prefix is only checked for on
     *			   the start (e.g. date:1/1/1980..31/12/1989), and a
     *			   suffix only on the end (e.g. 2..12kg).
     *			 * Xapian::RP_DATE_PREFER_MDY - interpret ambiguous
     *			   dates as month/day/year rather than day/month/year.
     *
     *  @param epoch_year_  Year to use as the epoch for dates with 2 digit
     *			    years (default: 1970, so 1/1/69 is 2069 while
     *			    1/1/70 is 1970).
     *
     *  The string supplied in str_ is used by @a operator() to decide whether
     *  the pair of strings supplied to it constitute a valid range.  If
     *  prefix_ is true, the first value in a range must begin with str_ (and
     *  the second value may optionally begin with str_);
     *  if prefix_ is false, the second value in a range must end with str_
     *  (and the first value may optionally end with str_).
     *
     *  If str_ is empty, the Xapian::RP_SUFFIX and Xapian::RP_REPEATED are
     *  irrelevant, and no special strings are required at the start or end of
     *  the strings defining the range.
     *
     *  The remainder of both strings defining the endpoints must be valid
     *  dates.
     *
     *  For example, if str_ is "created:", Xapian::RP_SUFFIX is not specified,
     *  and the range processor has been added to the queryparser, the
     *  queryparser will accept "created:1/1/2000..31/12/2001".
     */
    DateRangeProcessor(Xapian::valueno slot_, const std::string &str_,
		       unsigned flags_ = 0, int epoch_year_ = 1970)
	: RangeProcessor(slot_, str_, flags_),
	  epoch_year(epoch_year_) { }

    /** Check for a valid date range.
     *
     *  If any specified prefix is present, and the range looks like a
     *  date range, the dates are converted to the format YYYYMMDD and
     *  combined into a value range query.
     *
     *  @param begin	The start of the range as specified in the query string
     *			by the user.
     *  @param end	The end of the range as specified in the query string
     *			by the user.
     */
    Xapian::Query operator()(const std::string& begin, const std::string& end);
};

/** Handle a number range.
 *
 *  This class must be used on values which have been encoded using
 *  Xapian::sortable_serialise() which turns numbers into strings which
 *  will sort in the same order as the numbers (the same values can be
 *  used to implement a numeric sort).
 */
class XAPIAN_VISIBILITY_DEFAULT NumberRangeProcessor : public RangeProcessor {
  public:
    /** Constructor.
     *
     *  @param slot_    The value slot number to query.
     *
     *  @param str_     A string to look for to recognise values as belonging
     *                  to this numeric range.
     *
     *  @param flags_	Zero or more of the following flags, combined with
     *			bitwise-or:
     *			 * Xapian::RP_SUFFIX - require @a str_ as a suffix
     *			   instead of a prefix.
     *			 * Xapian::RP_REPEATED - optionally allow @a str_
     *			   on both ends of the range - e.g. $1..$10 or
     *			   5m..50m.  By default a prefix is only checked for on
     *			   the start (e.g. date:1/1/1980..31/12/1989), and a
     *			   suffix only on the end (e.g. 2..12kg).
     *
     *  The string supplied in str_ is used by @a operator() to decide whether
     *  the pair of strings supplied to it constitute a valid range.  If
     *  prefix_ is true, the first value in a range must begin with str_ (and
     *  the second value may optionally begin with str_);
     *  if prefix_ is false, the second value in a range must end with str_
     *  (and the first value may optionally end with str_).
     *
     *  If str_ is empty, the setting of prefix_ is irrelevant, and no special
     *  strings are required at the start or end of the strings defining the
     *  range.
     *
     *  The remainder of both strings defining the endpoints must be valid
     *  floating point numbers. (FIXME: define format recognised).
     *
     *  For example, if str_ is "$" and prefix_ is true, and the range
     *  processor has been added to the queryparser, the queryparser will
     *  accept "$10..50" or "$10..$50", but not "10..50" or "10..$50" as valid
     *  ranges.  If str_ is "kg" and prefix_ is false, the queryparser will
     *  accept "10..50kg" or "10kg..50kg", but not "10..50" or "10kg..50" as
     *  valid ranges.
     */
    NumberRangeProcessor(Xapian::valueno slot_,
			 const std::string &str_ = std::string(),
			 unsigned flags_ = 0)
	: RangeProcessor(slot_, str_, flags_) { }

    /** Check for a valid numeric range.
     *
     *  If BEGIN..END is a valid numeric range with the specified prefix/suffix
     *  (if one was specified), the prefix/suffix is removed, the string
     *  converted to a number, and encoded with Xapian::sortable_serialise(),
     *  and a value range query is built.
     *
     *  @param begin	The start of the range as specified in the query string
     *			by the user.
     *  @param end	The end of the range as specified in the query string
     *			by the user.
     */
    Xapian::Query operator()(const std::string& begin, const std::string& end);
};

/** Handle a byte unit range.
 *
 *  This class must be used on values which have been encoded using
 *  Xapian::sortable_serialise() which turns numbers into strings which
 *  will sort in the same order as the numbers (the same values can be
 *  used to implement a numeric sort).
 */
class XAPIAN_VISIBILITY_DEFAULT UnitRangeProcessor : public RangeProcessor {
  public:
    /** Constructor.
     *
     *  @param slot_    The value slot number to query.
     *
     *  @param str_     A string to look for to recognise values as belonging
     *                  to this numeric range.
     *
     *  The string supplied in str_ is the prefix plus ":" that defines the field
     *  upon which the range query is performed.
     *
     *  For example, if str_ is "size:", and the range
     *  processor has been added to the queryparser, the queryparser will
     *  accept "size:3K..10K" as a valid range.
     */
    UnitRangeProcessor(Xapian::valueno slot_,
		       const std::string &str_ = std::string())
	: RangeProcessor(slot_, str_) { }

    /** Check for a valid byte value range.
     *
     *  If BEGIN..END is a valid numeric byte range with the specified prefix
     *  the prefix is removed, the string converted to a number, unit
     *  normalized and encoded with Xapian::sortable_serialise(),
     *  and a value range query is built.
     *
     *  @param begin	The start of the range as specified in the query string
     *			by the user.
     *  @param end	The end of the range as specified in the query string
     *			by the user.
     */
    Xapian::Query operator()(const std::string& begin, const std::string& end);
};

/** Base class for field processors.
 */
class XAPIAN_VISIBILITY_DEFAULT FieldProcessor
    : public Xapian::Internal::opt_intrusive_base {
    /// Don't allow assignment.
    void operator=(const FieldProcessor &);

    /// Don't allow copying.
    FieldProcessor(const FieldProcessor &);

  public:
    /// Default constructor.
    FieldProcessor() { }

    /// Destructor.
    virtual ~FieldProcessor();

    /** Convert a field-prefixed string to a Query object.
     *
     *  @param str	The string to convert.
     *
     *  @return	Query object corresponding to @a str.
     */
    virtual Xapian::Query operator()(const std::string &str) = 0;

    /** Start reference counting this object.
     *
     *  You can hand ownership of a dynamically allocated FieldProcessor
     *  object to Xapian by calling release() and then passing the object to a
     *  Xapian method.  Xapian will arrange to delete the object once it is no
     *  longer required.
     */
    FieldProcessor * release() {
	opt_intrusive_base::release();
	return this;
    }

    /** Start reference counting this object.
     *
     *  You can hand ownership of a dynamically allocated FieldProcessor
     *  object to Xapian by calling release() and then passing the object to a
     *  Xapian method.  Xapian will arrange to delete the object once it is no
     *  longer required.
     */
    const FieldProcessor * release() const {
	opt_intrusive_base::release();
	return this;
    }
};

/// Build a Xapian::Query object from a user query string.
class XAPIAN_VISIBILITY_DEFAULT QueryParser {
  public:
    /// Class representing the queryparser internals.
    class Internal;
    /// @private @internal Reference counted internals.
    Xapian::Internal::internal_intrusive_ptr<Internal, QueryParser> internal;

    /// Enum of feature flags.
    typedef enum {
	/// Support AND, OR, etc and bracketed subexpressions.
	FLAG_BOOLEAN = 1,
	/// Support quoted phrases.
	FLAG_PHRASE = 2,
	/// Support + and -.
	FLAG_LOVEHATE = 4,
	/// Support AND, OR, etc even if they aren't in ALLCAPS.
	FLAG_BOOLEAN_ANY_CASE = 8,
	/** Support wildcards.
	 *
	 *  This flag only enables support for right truncation (e.g. Xap*) -
	 *  see FLAG_WILDCARD_MULTI, FLAG_WILDCARD_SINGLE and FLAG_WILDCARD_GLOB
	 *  for extended wildcard support.
	 *
	 *  Currently you can't use wildcards with boolean filter prefixes,
	 *  or in a phrase (either an explicitly quoted one, or one implicitly
	 *  generated by hyphens or other punctuation).
	 *
	 *  In Xapian 1.2.x, you needed to tell the QueryParser object which
	 *  database to expand wildcards from by calling set_database().  In
	 *  Xapian 1.3.3, OP_WILDCARD was added and wildcards are now
	 *  expanded when Enquire::get_mset() is called, with the expansion
	 *  using the database being searched.
	 */
	FLAG_WILDCARD = 16,
	/** Allow queries such as 'NOT apples'.
	 *
	 *  These require the use of a list of all documents in the database
	 *  which is potentially expensive, so this feature isn't enabled by
	 *  default.
	 */
	FLAG_PURE_NOT = 32,
	/** Enable partial matching.
	 *
	 *  Partial matching causes the parser to treat the query as a
	 *  "partially entered" search.  This will automatically treat the
	 *  final word as a wildcarded match, unless it is followed by
	 *  whitespace, to produce more stable results from interactive
	 *  searches.
	 *
	 *  Currently FLAG_PARTIAL doesn't do anything if the final word
	 *  in the query has a boolean filter prefix, or if it is in a phrase
	 *  (either an explicitly quoted one, or one implicitly generated by
	 *  hyphens or other punctuation).  It also doesn't do anything if
	 *  if the final word is part of a value range.
	 *
	 *  In Xapian 1.2.x, you needed to tell the QueryParser object which
	 *  database to expand wildcards from by calling set_database().  In
	 *  Xapian 1.3.3, OP_WILDCARD was added and wildcards are now
	 *  expanded when Enquire::get_mset() is called, with the expansion
	 *  using the database being searched.
	 */
	FLAG_PARTIAL = 64,

	/** Enable spelling correction.
	 *
	 *  For each word in the query which doesn't exist as a term in the
	 *  database, Database::get_spelling_suggestion() will be called and if
	 *  a suggestion is returned, a corrected version of the query string
	 *  will be built up which can be read using
	 *  QueryParser::get_corrected_query_string().  The query returned is
	 *  based on the uncorrected query string however - if you want a
	 *  parsed query based on the corrected query string, you must call
	 *  QueryParser::parse_query() again.
	 *
	 *  NB: You must also call set_database() for this to work.
	 */
	FLAG_SPELLING_CORRECTION = 128,

	/** Enable synonym operator '~'.
	 *
	 *  NB: You must also call set_database() for this to work.
	 */
	FLAG_SYNONYM = 256,

	/** Enable automatic use of synonyms for single terms.
	 *
	 *  NB: You must also call set_database() for this to work.
	 */
	FLAG_AUTO_SYNONYMS = 512,

	/** Enable automatic use of synonyms for single terms and groups of
	 *  terms.
	 *
	 *  NB: You must also call set_database() for this to work.
	 */
	FLAG_AUTO_MULTIWORD_SYNONYMS = 1024,

	/** Enable generation of n-grams from CJK text.
	 *
	 *  With this enabled, spans of CJK characters are split into unigrams
	 *  and bigrams, with the unigrams carrying positional information.
	 *  Non-CJK characters are split into words as normal.
	 *
	 *  The corresponding option needs to have been used at index time.
	 *
	 *  Flag added in Xapian 1.3.4 and 1.2.22.  This mode can be
	 *  enabled in 1.2.8 and later by setting environment variable
	 *  XAPIAN_CJK_NGRAM to a non-empty value (but doing so was deprecated
	 *  in 1.4.11).
	 */
	FLAG_CJK_NGRAM = 2048,

	/** Enable generation of words from CJK text.
	 *
	 *  With this enabled, spans of CJK characters are split into CJK
	 *  words using text boundary heuristics. Non-CJK characters are
	 *  split into words as normal.
	 *
	 *  The corresponding option needs to have been used at index time.
	 */
	FLAG_CJK_WORDS = 4096,

	/** Support extended wildcard '*'.
	 *
	 *  This flag enables support for wildcard '*' matching zero
	 *  or more characters, which may be used anywhere in a word.
	 *
	 *  Such wildcards can be relatively expensive to expand and to match
	 *  so benchmark your system carefully if you have a lot of documents
	 *  and/or a high search load.
	 *
	 *  FLAG_WILDCARD is ignored if this flag is specified.
	 *
	 *  @since Added in Xapian 1.5.0.
	 */
	FLAG_WILDCARD_MULTI = 8192,

	/** Support extended wildcard '?'.
	 *
	 *  This flag enables support for wildcard '?' matching exactly one
	 *  character, which may be use anywhere in a word.
	 *
	 *  Such wildcards can be relatively expensive to expand and to match
	 *  so benchmark your system carefully if you have a lot of documents
	 *  and/or a high search load.
	 *
	 *  FLAG_WILDCARD is ignored if this flag is specified.
	 *
	 *  @since Added in Xapian 1.5.0.
	 */
	FLAG_WILDCARD_SINGLE = 16384,

	/** Enable glob-style wildcarding.
	 *
	 *  This enables all supported glob-style wildcard pattern flags
	 *  - currently that's FLAG_WILDCARD_MULTI and FLAG_WILDCARD_SINGLE.
	 *
	 *  FLAG_WILDCARD is ignored if this flag is specified.
	 *
	 *  @since Added in Xapian 1.5.0.
	 */
	FLAG_WILDCARD_GLOB = FLAG_WILDCARD_MULTI | FLAG_WILDCARD_SINGLE,

	/** Support fuzzy matching.
	 *
	 *  E.g. "unserten~3" would expand to "uncertain" (and likely other
	 *  terms).
	 *
	 *  foo~ uses edit distance of 2
	 *  since~0.2 uses edit distance of length("since") * 0.2 = 5 * 0.2 = 1
	 *
	 *  @since Added in Xapian 1.5.0.
	 */
	FLAG_FUZZY = 32768,

	/** The default flags.
	 *
	 *  Used if you don't explicitly pass any to @a parse_query().
	 *  The default flags are FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE.
	 *
	 *  Added in Xapian 1.0.11.
	 */
	FLAG_DEFAULT = FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE
    } feature_flag;

    /// Stemming strategies, for use with set_stemming_strategy().
    typedef enum {
	STEM_NONE, STEM_SOME, STEM_ALL, STEM_ALL_Z, STEM_SOME_FULL_POS
    } stem_strategy;

    /// Copy constructor.
    QueryParser(const QueryParser & o);

    /// Assignment.
    QueryParser & operator=(const QueryParser & o);

    /// Move constructor.
    QueryParser(QueryParser && o);

    /// Move assignment operator.
    QueryParser & operator=(QueryParser && o);

    /// Default constructor.
    QueryParser();

    /// Destructor.
    ~QueryParser();

    /** Set the stemmer.
     *
     *  This sets the stemming algorithm which will be used by the query
     *  parser.  The stemming algorithm will be used according to the stemming
     *  strategy set by set_stemming_strategy().  As of 1.3.1, this defaults
     *  to STEM_SOME, but in earlier versions the default was STEM_NONE.  If
     *  you want to work with older versions, you should explicitly set
     *  a stemming strategy as well as setting a stemmer, otherwise your
     *  stemmer won't actually be used.
     *
     *  @param stemmer	The Xapian::Stem object to set.
     */
    void set_stemmer(const Xapian::Stem & stemmer);

    /** Set the stemming strategy.
     *
     *  This controls how the query parser will apply the stemming algorithm.
     *  Note that the stemming algorithm is only applied to words in free-text
     *  fields - boolean filter terms are never stemmed.
     *
     *  @param strategy	The strategy to use - possible values are:
     *   - STEM_NONE:	Don't perform any stemming.  (default in Xapian <=
     *			1.3.0)
     *   - STEM_SOME:	Stem all terms except for those which start with a
     *			capital letter, or are followed by certain characters
     *			(currently: <code>(/\@<>=*[{"</code> ), or are used
     *			with operators which need positional information.
     *			Stemmed terms are prefixed with 'Z'.  (default in
     *			Xapian >= 1.3.1)
     *   - STEM_SOME_FULL_POS:
     *			Like STEM_SOME but also stems terms used with operators
     *			which need positional information.  Added in Xapian
     *			1.4.8.
     *   - STEM_ALL:	Stem all terms (note: no 'Z' prefix is added).
     *   - STEM_ALL_Z:	Stem all terms (note: 'Z' prefix is added).  (new in
     *			Xapian 1.2.11 and 1.3.1)
     */
    void set_stemming_strategy(stem_strategy strategy);

    /** Set the stopper.
     *
     *  @param stop	The Stopper object to set (default NULL, which means no
     *			stopwords).
     */
    void set_stopper(const Stopper *stop = NULL);

    /** Set the default operator.
     *
     *  @param default_op	The operator to use to combine non-filter
     *				query items when no explicit operator is used.
     *
     *				So for example, 'weather forecast' is parsed as
     *				if it were 'weather OR forecast' by default.
     *
     *				The most useful values for this are OP_OR (the
     *				default) and OP_AND.  OP_NEAR, OP_PHRASE,
     *				OP_ELITE_SET, OP_SYNONYM and OP_MAX are also
     *				permitted.  Passing other values will result in
     *				InvalidArgumentError being thrown.
     */
    void set_default_op(Query::op default_op);

    /** Get the current default operator. */
    Query::op get_default_op() const;

    /** Specify the database being searched.
     *
     *  @param db	The database to use for spelling correction
     *			(FLAG_SPELLING_CORRECTION), and synonyms (FLAG_SYNONYM,
     *			FLAG_AUTO_SYNONYMS, and FLAG_AUTO_MULTIWORD_SYNONYMS).
     */
    void set_database(const Database &db);

    /** Specify the maximum expansion of a wildcard and/or partial and/or
     *  fuzzy term.
     *
     *  Note: you must also set FLAG_WILDCARD and/or FLAG_PARTIAL and/or
     *  FLAG_FUZZY in the flags parameter to @a parse_query() for this setting
     *  to have anything to affect.
     *
     *  If you don't call this method, the default settings are no limit on
     *  wildcard and fuzzy expansion, and partial terms expanding to the most
     *  frequent 100 terms - i.e. as if you'd called:
     *
     *  set_max_expansion(0);
     *  set_max_expansion(100, Xapian::Query::WILDCARD_LIMIT_MOST_FREQUENT, Xapian::QueryParser::FLAG_PARTIAL);
     *
     *  @param max_expansion  The maximum number of terms each wildcard in the
     *			query can expand to, or 0 for no limit (which is the
     *			default).
     *	@param max_type	@a Xapian::Query::WILDCARD_LIMIT_ERROR,
     *			@a Xapian::Query::WILDCARD_LIMIT_FIRST or
     *			@a Xapian::Query::WILDCARD_LIMIT_MOST_FREQUENT
     *			(default: Xapian::Query::WILDCARD_LIMIT_ERROR).
     *  @param flags	What to set the limit for (default:
     *			FLAG_WILDCARD|FLAG_PARTIAL|FLAG_FUZZY, setting the
     *			limit for all types).
     *
     *  @since 1.3.3
     */
    void set_max_expansion(Xapian::termcount max_expansion,
			   int max_type = Xapian::Query::WILDCARD_LIMIT_ERROR,
			   unsigned flags = FLAG_WILDCARD |
					    FLAG_PARTIAL |
					    FLAG_FUZZY);

    /** Specify minimum length for fixed initial portion in wildcard patterns.
     *
     *  It can be desirable for performance reasons to restrict use of
     *  wildcards to patterns with a fixed initial portion, so this method
     *  provides a way to specify a minimum length.  A wildcard pattern
     *  with a shorter (or no) fixed initial portion will result in
     *  Xapian::QueryParser being thrown.  The default minimum length is 0.
     *
     *  It also provides a way to specify the minimum length of a word to
     *  expand for partial matching (see @a FLAG_PARTIAL).  In this case
     *  a shorter word at the end of the query simply result in no partial
     *  matching.  The default minimum length for this case is 2 (since
     *  1.5.0 - in earlier versions it was effectively 0).
     *
     *  @param min_prefix_len	Minimum length of fixed initial portion in
     *			        Unicode characters.
     *  @param flags		What to set the minimum length for
     *				(default: FLAG_WILDCARD|FLAG_PARTIAL, setting
     *				the limit for both wildcards and partial
     *				terms).
     *
     *  Added in Xapian 1.5.0.
     */
    void set_min_wildcard_prefix(unsigned min_prefix_len,
				 unsigned flags = FLAG_WILDCARD|FLAG_PARTIAL);

    /** Parse a query.
     *
     *  @param query_string  A free-text query as entered by a user
     *  @param flags         Zero or more QueryParser::feature_flag specifying
     *		what features the QueryParser should support.  Combine
     *		multiple values with bitwise-or (|) (default FLAG_DEFAULT).
     *	@param default_prefix  The default term prefix to use (default none).
     *		For example, you can pass "A" when parsing an "Author" field.
     *
     *  @exception If the query string can't be parsed, then
     *		   Xapian::QueryParserError is thrown.  You can get an English
     *		   error message to report to the user by catching it and
     *		   calling get_msg() on the caught exception.  The current
     *		   possible values (in case you want to translate them) are:
     *
     *		   @li Unknown range operation
     *		   @li parse error
     *		   @li Syntax: <expression> AND <expression>
     *		   @li Syntax: <expression> AND NOT <expression>
     *		   @li Syntax: <expression> NOT <expression>
     *		   @li Syntax: <expression> OR <expression>
     *		   @li Syntax: <expression> XOR <expression>
     */
    Query parse_query(const std::string &query_string,
		      unsigned flags = FLAG_DEFAULT,
		      const std::string &default_prefix = std::string());

    /** Add a free-text field term prefix.
     *
     *  For example:
     *
     *  @code
     *  qp.add_prefix("author", "A");
     *  @endcode
     *
     *  This allows the user to search for author:Orwell which will be
     *  converted to a search for the term "Aorwell".
     *
     *  Multiple fields can be mapped to the same prefix.  For example, you
     *  can make title: and subject: aliases for each other.
     *
     *  As of 1.0.4, you can call this method multiple times with the same
     *  value of field to allow a single field to be mapped to multiple
     *  prefixes.  Multiple terms being generated for such a field, and
     *  combined with @c Xapian::Query::OP_OR.
     *
     *  If any prefixes are specified for the empty field name (i.e. you
     *  call this method with an empty string as the first parameter)
     *  these prefixes will be used for terms without a field specifier.
     *  If you do this and also specify the @c default_prefix parameter to @c
     *  parse_query(), then the @c default_prefix parameter will override.
     *
     *  If the prefix parameter is empty, then "field:word" will produce the
     *  term "word" (and this can be one of several prefixes for a particular
     *  field, or for terms without a field specifier).
     *
     *  If you call @c add_prefix() and @c add_boolean_prefix() for the
     *  same value of @a field, a @c Xapian::InvalidOperationError exception
     *  will be thrown.
     *
     *  In 1.0.3 and earlier, subsequent calls to this method with the same
     *  value of @a field had no effect.
     *
     *  @param field   The user visible field name
     *  @param prefix  The term prefix to map this to
     */
    void add_prefix(const std::string& field, const std::string& prefix);

    /** Register a FieldProcessor.
     */
    void add_prefix(const std::string& field, Xapian::FieldProcessor * proc);

    /** Add a boolean term prefix allowing the user to restrict a
     *  search with a boolean filter specified in the free text query.
     *
     *  For example:
     *
     *  @code
     *  qp.add_boolean_prefix("site", "H");
     *  @endcode
     *
     *  This allows the user to restrict a search with site:xapian.org which
     *  will be converted to Hxapian.org combined with any weighted
     *  query with @c Xapian::Query::OP_FILTER.
     *
     *  If multiple boolean filters are specified in a query for the same
     *  prefix, they will be combined with the @c Xapian::Query::OP_OR
     *  operator.  Then, if there are boolean filters for different prefixes,
     *  they will be combined with the @c Xapian::Query::OP_AND operator.
     *
     *  Multiple fields can be mapped to the same prefix (so for example
     *  you can make site: and domain: aliases for each other).  Instances of
     *  fields with different aliases but the same prefix will still be
     *  combined with the OR operator.
     *
     *  For example, if "site" and "domain" map to "H", but author maps to "A",
     *  a search for "site:foo domain:bar author:Fred" will map to
     *  "(Hfoo OR Hbar) AND Afred".
     *
     *  As of 1.0.4, you can call this method multiple times with the same
     *  value of field to allow a single field to be mapped to multiple
     *  prefixes.  Multiple terms being generated for such a field, and
     *  combined with @c Xapian::Query::OP_OR.
     *
     *  Calling this method with an empty string for @a field will cause
     *  a @c Xapian::InvalidArgumentError.
     *
     *  If you call @c add_prefix() and @c add_boolean_prefix() for the
     *  same value of @a field, a @c Xapian::InvalidOperationError exception
     *  will be thrown.
     *
     *  In 1.0.3 and earlier, subsequent calls to this method with the same
     *  value of @a field had no effect.
     *
     *  @param field   The user visible field name
     *  @param prefix  The term prefix to map this to
     *  @param grouping	Controls how multiple filters are combined - filters
     *			with the same grouping value are combined with OP_OR,
     *			then the resulting queries are combined with OP_AND.
     *			If NULL, then @a field is used for grouping.  If an
     *			empty string, then a unique grouping is created for
     *			each filter (this is sometimes useful when each
     *			document can have multiple terms with this prefix).
     *			[default: NULL]
     */
    void add_boolean_prefix(const std::string &field, const std::string &prefix,
			    const std::string* grouping = NULL);

    /** Add a boolean term prefix allowing the user to restrict a
     *  search with a boolean filter specified in the free text query.
     *
     *  This is an older version of this method - use the version with
     *  the `grouping` parameter in preference to this one.
     *
     *  @param field   The user visible field name
     *  @param prefix  The term prefix to map this to
     *  @param exclusive Controls how multiple filters are combined.  If
     *			true then @a prefix is used as the `grouping` value,
     *			so terms with the same prefix are combined with OP_OR,
     *			then the resulting queries are combined with OP_AND.
     *			If false, then a unique grouping is created for
     *			each filter (this is sometimes useful when each
     *			document can have multiple terms with this prefix).
     */
    void add_boolean_prefix(const std::string &field, const std::string &prefix,
			    bool exclusive) {
	if (exclusive) {
	    add_boolean_prefix(field, prefix);
	} else {
	    std::string empty_grouping;
	    add_boolean_prefix(field, prefix, &empty_grouping);
	}
    }

    /** Register a FieldProcessor for a boolean prefix.
     */
    void add_boolean_prefix(const std::string &field, Xapian::FieldProcessor *proc,
			    const std::string* grouping = NULL);

    /** Register a FieldProcessor for a boolean prefix.
     *
     *  This is an older version of this method - use the version with
     *  the `grouping` parameter in preference to this one.
     */
    void add_boolean_prefix(const std::string &field, Xapian::FieldProcessor *proc,
			    bool exclusive) {
	if (exclusive) {
	    add_boolean_prefix(field, proc);
	} else {
	    std::string empty_grouping;
	    add_boolean_prefix(field, proc, &empty_grouping);
	}
    }

    /// Begin iterator over terms omitted from the query as stopwords.
    TermIterator stoplist_begin() const;

    /// End iterator over terms omitted from the query as stopwords.
    TermIterator XAPIAN_NOTHROW(stoplist_end() const) {
	return TermIterator();
    }

    /// Begin iterator over unstemmed forms of the given stemmed query term.
    TermIterator unstem_begin(const std::string &term) const;

    /// End iterator over unstemmed forms of the given stemmed query term.
    TermIterator XAPIAN_NOTHROW(unstem_end(const std::string &) const) {
	return TermIterator();
    }

    /// Register a RangeProcessor.
    void add_rangeprocessor(Xapian::RangeProcessor * range_proc,
			    const std::string* grouping = NULL);

    /** Get the spelling-corrected query string.
     *
     *  This will only be set if FLAG_SPELLING_CORRECTION is specified when
     *  QueryParser::parse_query() was last called.
     *
     *  If there were no corrections, an empty string is returned.
     */
    std::string get_corrected_query_string() const;

    /// Return a string describing this object.
    std::string get_description() const;
};

/// @private @internal Helper for sortable_serialise().
XAPIAN_VISIBILITY_DEFAULT
size_t XAPIAN_NOTHROW(sortable_serialise_(double value, char * buf));

/** Convert a floating point number to a string, preserving sort order.
 *
 *  This method converts a floating point number to a string, suitable for
 *  using as a value for numeric range restriction, or for use as a sort
 *  key.
 *
 *  The conversion is platform independent.
 *
 *  The conversion attempts to ensure that, for any pair of values supplied
 *  to the conversion algorithm, the result of comparing the original
 *  values (with a numeric comparison operator) will be the same as the
 *  result of comparing the resulting values (with a string comparison
 *  operator).  On platforms which represent doubles with the precisions
 *  specified by IEEE_754, this will be the case: if the representation of
 *  doubles is more precise, it is possible that two very close doubles
 *  will be mapped to the same string, so will compare equal.
 *
 *  Note also that both zero and -zero will be converted to the same
 *  representation: since these compare equal, this satisfies the
 *  comparison constraint, but it's worth knowing this if you wish to use
 *  the encoding in some situation where this distinction matters.
 *
 *  Handling of NaN isn't (currently) guaranteed to be sensible.
 *
 *  @param value	The number to serialise.
 */
inline std::string sortable_serialise(double value) {
    char buf[9];
    return std::string(buf, sortable_serialise_(value, buf));
}

/** Convert a string encoded using @a sortable_serialise back to a floating
 *  point number.
 *
 *  This expects the input to be a string produced by @a sortable_serialise().
 *  If the input is not such a string, the value returned is undefined (but
 *  no error will be thrown).
 *
 *  The result of the conversion will be exactly the value which was
 *  supplied to @a sortable_serialise() when making the string on platforms
 *  which represent doubles with the precisions specified by IEEE_754, but
 *  may be a different (nearby) value on other platforms.
 *
 *  @param serialised	The serialised string to decode.
 */
XAPIAN_VISIBILITY_DEFAULT
double XAPIAN_NOTHROW(sortable_unserialise(const std::string & serialised));

}

#endif // XAPIAN_INCLUDED_QUERYPARSER_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Engine.Classes.Quests
{
    public class RewardItem
    {
        public Item Details
        {
            get;
            set;
        }

        public RewardItem(Item details)
        {
            this.Details = details;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const assert = require('assert')
const fs = require('fs-extra')
const os = require('os')
const path = require('path')
const spawnSync = require('./spawn-sync')
const template = require('lodash.template')

const CONFIG = require('../config')

module.exports = function (packagedAppPath) {
  console.log(`Creating rpm package for "${packagedAppPath}"`)
  const atomExecutableName = CONFIG.channel === 'beta' ? 'atom-beta' : 'atom'
  const apmExecutableName = CONFIG.channel === 'beta' ? 'apm-beta' : 'apm'
  const appName = CONFIG.channel === 'beta' ? 'Atom Beta' : 'Atom'
  const appDescription = CONFIG.appMetadata.description
  // RPM versions can't have dashes or tildes in them.
  // (Ref.: https://twiki.cern.ch/twiki/bin/view/Main/RPMAndDebVersioning)
  const appVersion = CONFIG.appMetadata.version.replace(/-/g, '.')

  const rpmPackageDirPath = path.join(CONFIG.homeDirPath, 'rpmbuild')
  const rpmPackageBuildDirPath = path.join(rpmPackageDirPath, 'BUILD')
  const rpmPackageSourcesDirPath = path.join(rpmPackageDirPath, 'SOURCES')
  const rpmPackageSpecsDirPath = path.join(rpmPackageDirPath, 'SPECS')
  const rpmPackageRpmsDirPath = path.join(rpmPackageDirPath, 'RPMS')
  const rpmPackageApplicationDirPath = path.join(rpmPackageBuildDirPath, appName)
  const rpmPackageIconsDirPath = path.join(rpmPackageBuildDirPath, 'icons')

  if (fs.existsSync(rpmPackageDirPath)) {
    console.log(`Deleting existing rpm build directory at "${rpmPackageDirPath}"`)
    fs.removeSync(rpmPackageDirPath)
  }

  console.log(`Creating rpm package directory structure at "${rpmPackageDirPath}"`)
  fs.mkdirpSync(rpmPackageDirPath)
  fs.mkdirpSync(rpmPackageBuildDirPath)
  fs.mkdirpSync(rpmPackageSourcesDirPath)
  fs.mkdirpSync(rpmPackageSpecsDirPath)

  console.log(`Copying "${packagedAppPath}" to "${rpmPackageApplicationDirPath}"`)
  fs.copySync(packagedAppPath, rpmPackageApplicationDirPath)

  console.log(`Copying icons into "${rpmPackageIconsDirPath}"`)
  fs.copySync(
    path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'png'),
    rpmPackageIconsDirPath
  )

  console.log(`Writing rpm package spec file into "${rpmPackageSpecsDirPath}"`)
  const rpmPackageSpecFilePath = path.join(rpmPackageSpecsDirPath, 'atom.spec')
  const rpmPackageSpecsTemplate = fs.readFileSync(path.join(CONFIG.repositoryRootPath, 'resources', 'linux', 'redhat', 'atom.spec.in'))
  const rpmPackageSpecsContents = template(rpmPackageSpecsTemplate)({
    appName: appName, appFileName: atomExecutableName, apmFileName: apmExecutableName,
    description: appDescription, installDir: '/usr', version: appVersion
  })
  fs.writeFileSync(rpmPackageSpecFilePath, rpmPackageSpecsContents)

  console.log(`Writing desktop entry file into "${rpmPackageBuildDirPath}"`)
  const desktopEntryTemplate = fs.readFileSync(path.join(CONFIG.repositoryRootPath, 'resources', 'linux', 'atom.desktop.in'))
  const desktopEntryContents = template(desktopEntryTemplate)({
    appName: appName, appFileName: atomExecutableName, description: appDescription,
    installDir: '/usr', iconPath: atomExecutableName
  })
  fs.writeFileSync(path.join(rpmPackageBuildDirPath, `${atomExecutableName}.desktop`), desktopEntryContents)

  console.log(`Copying atom.sh into "${rpmPackageBuildDirPath}"`)
  fs.copySync(
    path.join(CONFIG.repositoryRootPath, 'atom.sh'),
    path.join(rpmPackageBuildDirPath, 'atom.sh')
  )

  console.log(`Generating .rpm package from "${rpmPackageDirPath}"`)
  spawnSync('rpmbuild', ['-ba', '--clean', rpmPackageSpecFilePath])
  for (let generatedArch of fs.readdirSync(rpmPackageRpmsDirPath)) {
    const generatedArchDirPath = path.join(rpmPackageRpmsDirPath, generatedArch)
    const generatedPackageFileNames = fs.readdirSync(generatedArchDirPath)
    assert(generatedPackageFileNames.length === 1, 'Generated more than one rpm package')
    const generatedPackageFilePath = path.join(generatedArchDirPath, generatedPackageFileNames[0])
    const outputRpmPackageFilePath = path.join(CONFIG.buildOutputPath, `atom.${generatedArch}.rpm`)
    console.log(`Copying "${generatedPackageFilePath}" into "${outputRpmPackageFilePath}"`)
    fs.copySync(generatedPackageFilePath, outputRpmPackageFilePath)
  }
}


text:
'use strict';

const gulp = require('gulp');
const cp   = require('child_process');
const fs   = require('./FS.js');

let node; // Запущенный нодный процесс сервера

gulp.task( 'server', [ 'lint-node' ], done => {
    if (node) node.kill();
    node = cp.spawn( 'node', ['server'], {
        env: Object.assign( { NODE_ENV: 'dev' }, process.env ),
        stdio: 'inherit'
    } );
    done();
} );

gulp.task( 'serve', [
    'markup', 'scripts', 'styles', 'static', 'server'
], () => {
    gulp.watch( fs.scriptsNode, [ 'server' ] );
    gulp.watch( fs.markup, [ 'markup' ] );
    gulp.watch( fs.scriptsBrowser, [ 'scripts' ] );
    gulp.watch( fs.styles, [ 'styles' ] );
    gulp.watch( fs.staticFiles, [ 'static' ] );
    // При появлении новых браузеных скриптов или таблиц стилей нодный сервер
    // не перезапускается автоматически. Поэтому новые файлы не будут
    // автоматически подключены к странице. Так сделано потому, что показалось,
    // что перезапуск нодного сервера — довольно дорогая операция.
} );


text:
<?php

namespace JAI\Bundle\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Role
 *
 * @ORM\Table(name="JAI_UserBundle_role")
 * @ORM\Entity(repositoryClass="JAI\Bundle\UserBundle\Repository\RoleRepository")
 */
class Role
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="role", type="string", length=255, unique=true)
     */
    private $role;

	/**
	 * @ORM\ManyToMany(targetEntity="JAI\Bundle\UserBundle\Entity\User",mappedBy="roles")
	 */
    private $users;

	public function __construct()
	{
	    $this->users = new ArrayCollection();
	}

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set role
     *
     * @param string $role
     *
     * @return Role
     */
    public function setRole($role)
    {
        $this->role = $role;

        return $this;
    }

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

    /**
     * Add user
     *
     * @param \JAI\Bundle\UserBundle\Entity\User $user
     *
     * @return Role
     */
    public function addUser(\JAI\Bundle\UserBundle\Entity\User $user)
    {
        $this->users[] = $user;

        return $this;
    }

    /**
     * Remove user
     *
     * @param \JAI\Bundle\UserBundle\Entity\User $user
     */
    public function removeUser(\JAI\Bundle\UserBundle\Entity\User $user)
    {
        $this->users->removeElement($user);
    }

    /**
     * Get users
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUsers()
    {
        return $this->users;
    }
}


text:
package org.olat.lms.commons.validation;

/**
 * Description:

 * TODO: patrickb Class Description for ValidationActionImpl
 *

 * Initial Date: 06.12.2006

 *
 * @author patrickb
 */
public abstract class ValidationActionImpl implements ValidationAction {
    protected Object userObj = null;

    public ValidationActionImpl(Object userObj) {
        this.userObj = userObj;
    }

    @Override
    public abstract Object execute();
}


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

    <title>${docType.simpleClassName} ($title)</title>
    <%
    int dotCount = docType.packageName.count('.')
    String pathPref = '../' * (dotCount + 1)
    %>
    <link rel="stylesheet" type="text/css" href="${pathPref}stylesheet.css" title="Style">

Overview

Package

Class

Index

Package: ${docType.packageName}

${docType.interface ? 'Interface' : 'Class'} ${docType.simpleClassName}

Methods Summary

Methods

                                        Return type
                                        Name and parameters

                                    <% docType.docMethods.eachWithIndex { docMethod, i -> %>

                                             ${docMethod.isStatic() ? 'static ' : ''}${docMethod.returnTypeDocUrl}

                                            ${docMethod.name}(${docMethod.parametersDocUrl})

                                            ${docMethod.shortComment}

                                    <% } %>

                        <% docType.inheritedMethods.each { inhDocType, inhDocMethods -> %>

Methods inherited from ${inhDocType.interface ? 'interface' : 'class'} ${inhDocType.packageName}.${docType.linkAnchor(inhDocType)}

                                    <%= inhDocMethods.findAll { !it.static }.collect { docMethod ->
                                        """${docMethod.name}"""
                                    }.join(", ") %>

                        <% } %>

Methods Detail

                            <% docType.docMethods.eachWithIndex { docMethod, i -> %>

public ${docMethod.isStatic() ? 'static ' : ''}${docMethod.returnTypeDocUrl} ${docMethod.name}(${docMethod.parametersDocUrl})

${docMethod.comment}

                                    <% if (docMethod.parametersSignature) { %>

Parameters:

                                        <% docMethod.parameterComments.each { name, comment -> %>

${name} - ${comment}

                                        <% } %>

                                    <%
                                    } %>

                                    <% if (docMethod.returnComment) { %>

Returns:

${docMethod.returnComment}

                                    <% } %>

                                    <%if (docMethod.sinceComment) { %>

Since:

${docMethod.sinceComment}

                                    <%}%>

                                    <% if (docMethod.seeComments) { %>

See Also:

                                        <% docMethod.seeComments.each { %>

${it}

                                        <% }%>

                                    <% } %>

                            <% } %>

Overview

Package

Class

Index


text:
import time

ID = "event"
permission = 3

def timer(self, channels):
    print "executing"
    if channels != False and len(channels) > 0:
        self.sendChatMessage(self.send, channels[0], "Time has passed.")

    #self.sendChatMessage(self.send, self.timerChannel, "Test: "+str(channels))

def execute(self, name, params, channel, userdata, rank):
    if len(params) == 1 and params[0] == "on":
        if not self.events["time"].doesExist("TestFunc"):
            self.sendChatMessage(self.send, channel, "Turning timerevent on.")
            self.timerChannel = channel
            self.events["time"].addEvent("TestFunc", 60, timer)
        else:
            self.sendChatMessage(self.send, channel, "Timerevent is already running.")
    if len(params) == 1 and params[0] == "off":
        if self.events["time"].doesExist("TestFunc"):
            self.sendChatMessage(self.send, channel, "Turning timerevent off.")
            self.events["time"].removeEvent("TestFunc")
        else:
            self.sendChatMessage(self.send, channel, "Timerevent isn't running!")

    if len(params) == 2 and params[0] == "add":
        channel = params[1]
        self.events["time"].addChannel("TestFunc", channel)

    if len(params) == 2 and params[0] == "rem":
        channel = params[1]
        self.events["time"].removeChannel("TestFunc", channel)


text:
//
// (C) 2005 Vojtech Janota
// (C) 2003 Xuan Thang Nguyen
//
// This library is free software, you can redistribute it
// and/or modify
// it under  the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation;
// either version 2 of the License, or any later version.
// The library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//

#ifndef __INET_LIBTABLE_H
#define __INET_LIBTABLE_H

#include <vector>
#include <string>

#include "inet/common/INETDefs.h"

#include "inet/networklayer/mpls/ConstType.h"
#include "inet/networklayer/contract/ipv4/IPv4Address.h"
#include "inet/networklayer/ipv4/IPv4Datagram.h"

namespace inet {

// label operations
#define PUSH_OPER    0
#define SWAP_OPER    1
#define POP_OPER     2

/**
 * TODO documentation
 */
struct LabelOp
{
    int label;
    int optcode;
};

typedef std::vector<LabelOp> LabelOpVector;

/**
 * TODO documentation
 */
class INET_API LIBTable : public cSimpleModule
{
  public:
    struct LIBEntry
    {
        int inLabel;
        std::string inInterface;

        LabelOpVector outLabel;
        std::string outInterface;

        // FIXME colors in nam, temporary solution
        int color;
    };

  protected:
    int maxLabel;
    std::vector<LIBEntry> lib;

  protected:
    virtual void initialize(int stage) override;
    virtual int numInitStages() const override { return NUM_INIT_STAGES; }
    virtual void handleMessage(cMessage *msg) override;

    // static configuration
    virtual void readTableFromXML(const cXMLElement *libtable);

  public:
    // label management
    virtual bool resolveLabel(std::string inInterface, int inLabel,
            LabelOpVector& outLabel, std::string& outInterface, int& color);

    virtual int installLibEntry(int inLabel, std::string inInterface, const LabelOpVector& outLabel,
            std::string outInterface, int color);

    virtual void removeLibEntry(int inLabel);

    // utility
    static LabelOpVector pushLabel(int label);
    static LabelOpVector swapLabel(int label);
    static LabelOpVector popLabel();
};

std::ostream& operator<<(std::ostream& os, const LIBTable::LIBEntry& lib);
std::ostream& operator<<(std::ostream& os, const LabelOpVector& label);

} // namespace inet

#endif // ifndef __INET_LIBTABLE_H


text:
package eu.execom.FabutPresentation.rest

import java.util._

import eu.execom.FabutPresentation.api._
import eu.execom.FabutPresentation.persistence._
import eu.execom.FabutPresentation.util._
import org.joda.time.DateTime
import org.json4s._
import org.scalatra._
import sun.misc.BASE64Encoder

abstract class AbstractSecuredServlet extends ScalatraServlet with Logging {

  val SECURITY_TOKEN = "X-FABUTPRESENTATION-AUTH"

  protected implicit val jsonFormats: Formats = DefaultFormats + new ArrayByteSerializer + DateTimeSerializer + new UUIDSerializer + new SortOrderSerializer + new InvitationStatusSerializer + new FriendRequestStatusSerializer

  error {
    case BadRequestException(code) =>
      logger.trace("BadRequest error occurred with code: " + code)
      halt(BadRequest(body = errorJson(code, "BadRequest error occurred with code")))
    case DataConstraintException(code) =>
      logger.trace("Data constraint error occurred with code: " + code)
      halt(BadRequest(body = errorJson(code, "Data constraint error occurred with code")))
    case UnauthorizedException(code) =>
      logger.trace("Unauthorized error occurred with code: " + code)
      halt(Unauthorized(body = errorJson(code, "Unauthorized error occurred with code")))
    case e:MappingException =>
      logger.warn(s"Bad data request, json object invalid format, ${e.msg}")
      halt(BadRequest(body = errorJson("JSON_MAPPING_EXCEPTION", s"Bad data request, json object invalid format, ${e.msg}")))
    case e =>
      logger.error("Unknown error occurred", e)
      halt(InternalServerError(reason = e.toString))
  }

  def errorJson(code:String, message: String) = {
    s"""{ "code": "$code", "message": "$message" }""".stripMargin
  }

  def securityToken: String = (cookies.get(SECURITY_TOKEN), request.header(SECURITY_TOKEN)) match {
    case (Some(authCode), _) =>
      logger.trace("Requested security token is found in cookie")
      authCode
    case (_, Some(authCode)) =>
      logger.trace("Requested security token is found in header cookie")
      authCode
    case _ =>
      logger.error("Security token doesn't exist")
      halt(Unauthorized(reason = "USER_CREDENTIALS_ARE_INVALID"))
  }

  def securityToken_=(token: String): Unit = cookies.set(SECURITY_TOKEN, token)

}

class ArrayByteSerializer extends Serializer[Array[Byte]] {
  private val MyClassClass = classOf[Array[Byte]]

  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Array[Byte]] = {
    case (TypeInfo(MyClassClass, _), json) => json match {
      case JString(content) =>
        new sun.misc.BASE64Decoder().decodeBuffer(content)
      case x => throw new MappingException("Can't convert " + x + " to Array[Byte]")
    }
  }

  def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
    case x: Array[Byte] => JString(new BASE64Encoder().encode(x))
  }
}

case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( {
  case JString(s) =>
    val milliseconds: Long = format.dateFormat.parse(s).map(_.getTime).getOrElse(throw new MappingException("Invalid date format " + s))
    new DateTime(milliseconds)
}, {
  case d: DateTime => JString(format.dateFormat.format(d.toDate))
}
  ))

class UUIDSerializer extends Serializer[UUID] {
  private val MyClassClass = classOf[UUID]

  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), UUID] = {
    case (TypeInfo(MyClassClass, _), json) => json match {
      case JString(content) => UUID.fromString(content)
      case x => throw new MappingException("Can't convert " + x + " to UUID")
    }
  }

  def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
    case x: UUID => JString(x.toString)
  }
}

class SortOrderSerializer extends Serializer[SortOrder] {
  private val MyClassClass = classOf[SortOrder]

  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), SortOrder] = {
    case (TypeInfo(MyClassClass, _), json) => json match {
      case JString(content) => SortOrder.withName(content)
      case x => throw new MappingException("Can't deserialize " + x + " to SortOrder")
    }
  }

  def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
    case x: SortOrder => JString(x.name)
  }
}

class InvitationStatusSerializer extends Serializer[InvitationStatus] {
  private val MyClassClass = classOf[InvitationStatus]

  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), InvitationStatus] = {
    case (TypeInfo(MyClassClass, _), json) => json match {
      case JString(content) => InvitationStatus.withName(content)
      case x => throw new MappingException("Can't deserialize " + x + " to InvitationStatus")
    }
  }

  def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
    case x: InvitationStatus => JString(x.name)
  }
}

class FriendRequestStatusSerializer extends Serializer[FriendRequestStatus] {
  private val MyClassClass = classOf[FriendRequestStatus]

  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), FriendRequestStatus] = {
    case (TypeInfo(MyClassClass, _), json) => json match {
      case JString(content) => FriendRequestStatus.withName(content)
      case x => throw new MappingException("Can't deserialize " + x + " to FriendRequestStatus")
    }
  }

  def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
    case x: FriendRequestStatus => JString(x.name)
  }
}


text:
'use strict'
const Backbone = require('backbone')
const Mustache = require('mustache')
const fs = require('fs')
const path = require('path')

module.exports = Backbone.View.extend({
  initialize: function () {
    this.template = fs.readFileSync(path.join(__dirname, 'sidebar.html'), {encoding: 'utf8'})
    this.render()
  },
  render: function () {
    this.$el.append(this.template)
  }
})


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentNHibernate.Mapping;
using SysAnalytics.Model.Entities;

namespace SysAnalytics.Data.Mappings
{
    public class AppliedDiscountMap : ClassMap<AppliedDiscount>
    {
        public AppliedDiscountMap()
        {
            Table("applied_discounts");
            Id(x => x.AppliedDiscountID).Column("id").GeneratedBy.Identity();
            References(o => o.Order).Column("order_id").Cascade.None().Not.LazyLoad();
            Map(x => x.Type);
            Map(x => x.Code);
            Map(x => x.Percent);
        }
    }
}


text:
package com.xqbase.bn.io;

import com.xqbase.bn.io.parsing.Parser;
import com.xqbase.bn.io.parsing.SkipParser;
import com.xqbase.bn.io.parsing.Symbol;

import java.io.IOException;

/**
 * Base class for parser based decoders.
 *
 * @author Tony He
 */
public abstract class ParsingDecoder implements Decoder,
                    Parser.ActionHandler, SkipParser.SkipHandler {

    protected final SkipParser skipParser;

    protected ParsingDecoder(Symbol root) throws IOException {
        this.skipParser = new SkipParser(root, this, this);
    }
}


text:
@extends('layouts.default')

@section('style')

@endsection

@section('content')

Buttons

        <button type="button" class="btn btn-xs btn-default" data-gist="45e83a87cf59155db51d">Show code sample</button>

        <button type="button" class="btn btn-lg btn-brand">Brand</button>
        <button type="button" class="btn btn-lg btn-default">Default</button>
        <button type="button" class="btn btn-lg btn-primary">Primary</button>
        <button type="button" class="btn btn-lg btn-success">Success</button>
        <button type="button" class="btn btn-lg btn-info">Info</button>
        <button type="button" class="btn btn-lg btn-warning">Warning</button>
        <button type="button" class="btn btn-lg btn-danger">Danger</button>
        <button type="button" class="btn btn-lg btn-link">Link</button>

        <button type="button" class="btn btn-brand">Brand</button>
        <button type="button" class="btn btn-default">Default</button>
        <button type="button" class="btn btn-primary">Primary</button>
        <button type="button" class="btn btn-success">Success</button>
        <button type="button" class="btn btn-info">Info</button>
        <button type="button" class="btn btn-warning">Warning</button>
        <button type="button" class="btn btn-danger">Danger</button>
        <button type="button" class="btn btn-link">Link</button>

        <button type="button" class="btn btn-sm btn-brand">Brand</button>
        <button type="button" class="btn btn-sm btn-default">Default</button>
        <button type="button" class="btn btn-sm btn-primary">Primary</button>
        <button type="button" class="btn btn-sm btn-success">Success</button>
        <button type="button" class="btn btn-sm btn-info">Info</button>
        <button type="button" class="btn btn-sm btn-warning">Warning</button>
        <button type="button" class="btn btn-sm btn-danger">Danger</button>
        <button type="button" class="btn btn-sm btn-link">Link</button>

        <button type="button" class="btn btn-xs btn-brand">Brand</button>
        <button type="button" class="btn btn-xs btn-default">Default</button>
        <button type="button" class="btn btn-xs btn-primary">Primary</button>
        <button type="button" class="btn btn-xs btn-success">Success</button>
        <button type="button" class="btn btn-xs btn-info">Info</button>
        <button type="button" class="btn btn-xs btn-warning">Warning</button>
        <button type="button" class="btn btn-xs btn-danger">Danger</button>
        <button type="button" class="btn btn-xs btn-link">Link</button>

Standard Form

    {!! Form::open(['nosubmit']) !!}

                        Input Example
                        <input class="form-control" name="inputExample" type="text" />

Input Example help text

                        Select Example
                        <select class="form-control" name="selectExample">
                            <option value="">Choose an option</option>
                            <option value="">Option One</option>
                            <option value="">Option Two</option>
                            <option value="">Option Three</option>
                            <option value="">Option Four</option>
                        </select>

                Textarea Example
                <textarea class="form-control" name="textareaExample" rows="8"></textarea>

Textarea Example help text

                Radio Example

                        <input name="radioExample" value="terrible" type="radio" /> Radio One

                        <input name="radioExample" value="watchable" type="radio" /> Radio Two

                        <input name="radioExample" value="best" type="radio" /> Radio Three

            <button type="submit" class="btn btn-default">Submit</button>

    {!! Form::close() !!}

Inline Form

    <form class="form-inline">

            Name
            <input class="form-control" name="inlineFormName" placeholder="Some Name" type="text" />

            Email
            <input class="form-control" name="inlineFormEmail" placeholder="some.email@example.com" type="email" />

        <button class="btn btn-default" type="submit">Submit</button>
    </form>

Horizontal Form

    <form class="form-horizontal" nosubmit>

            Email

                <input class="form-control" name="horizontalFormEmail" placeholder="Email" type="email" />

            Password

                <input class="form-control" name="horizontalFormPassword" placeholder="Password" type="password" />

                        <input type="checkbox" /> Remember me

                <button class="btn btn-default" type="submit">Sign in</button>

    </form>

Tables

                    #
                    First Name
                    Last Name
                    Username

                    1
                    Mark
                    Otto
                    @mdo

                    2
                    Jacob
                    Thornton
                    @fat

                    3
                    Larry
                    the Bird
                    @twitter

                    #
                    First Name
                    Last Name
                    Username

                    1
                    Mark
                    Otto
                    @mdo

                    2
                    Jacob
                    Thornton
                    @fat

                    3
                    Larry
                    the Bird
                    @twitter

                    #
                    First Name
                    Last Name
                    Username

                    1
                    Mark
                    Otto
                    @mdo

                    Mark
                    Otto
                    @TwBootstrap

                    2
                    Jacob
                    Thornton
                    @fat

                    3
                    Larry the Bird
                    @twitter

                    #
                    First Name
                    Last Name
                    Username

                    1
                    Mark
                    Otto
                    @mdo

                    2
                    Jacob
                    Thornton
                    @fat

                    3
                    Larry the Bird
                    @twitter

Labels

        Default
        Primary
        Success
        Info
        Warning
        Danger

        Default
        Primary
        Success
        Info
        Warning
        Danger

        Default
        Primary
        Success
        Info
        Warning
        Danger

        Default
        Primary
        Success
        Info
        Warning
        Danger

        Default
        Primary
        Success
        Info
        Warning
        Danger

        Default
        Primary
        Success
        Info
        Warning
        Danger

        Default
        Primary
        Success
        Info
        Warning
        Danger

Badges

        Inbox 42

Home 42

Profile

Messages 3

Dropdown menus

        <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
            Dropdown

        </button>

Action

Another action

Something else here

Separated link

        <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-expanded="true">
            Dropup

        </button>

Action

Another action

Something else here

Separated link

Navs

Home

Profile

Messages

Home

Profile

Messages

Navbars

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>
                Project name

Home

About

Contact

                        Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>
                Project name

Home

About

Contact

                        Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Alerts

        Well done! You successfully read this important alert message.

        Heads up! This alert needs your attention, but it's not super important.

        Warning! Best check yo self, you're not looking too good.

        Oh snap! Change a few things up and try submitting again.

Progress bars

60% Complete

40%40% Complete (success)

20% Complete

60% Complete (warning)

80% Complete (danger)

60% Complete

60% Complete

35% Complete (success)

20% Complete (warning)

10% Complete (danger)

List groups

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

                    Cras justo odio

                Dapibus ac facilisis in
                Morbi leo risus
                Porta ac consectetur ac
                Vestibulum at eros

List group item heading

Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.

List group item heading

Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.

List group item heading

Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.

Panels

Panel title

                    Panel content

Panel title

                    Panel content

Panel title

                    Panel content

Panel title

                    Panel content

Panel title

                    Panel content

Panel title

                    Panel content

Wells

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sed diam eget risus varius blandit sit amet non magna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Aenean lacinia bibendum nulla sed consectetur.

Thumbnails

Bootstrap Carousel

            Previous

            Next

Owl Carousel (Standard) http://owlgraphic.com/owlcarousel

        <button type="button" class="btn btn-xs btn-default" data-gist="ace83c433a546d8ad2a5">Show code sample</button>

Owl Carousel (Full-width) http://owlgraphic.com/owlcarousel

Twitter typeahead.js and Bloodhound http://twitter.github.io/typeahead.js/

        <input id="twtypeahead" class="form-control" type="text" placeholder="Countries">

Editables http://vitalets.github.io/x-editable

            Simple text field
            superuser

            Empty text field, required

            Select, local array, custom display

Tokenfield http://sliptree.github.io/bootstrap-tokenfield

    <input type="text" class="form-control" id="tokenfield-typeahead" value="red,green,blue" />

Bootstrap Notify http://bootstrap-growl.remabledesigns.com

        <button type="button" class="btn btn-xs btn-default" data-gist="450c0e7704e9edc1486b">Show code sample</button>

    <button class="btn btn-success" type="button" data-type="growl" data-style="success"
            data-title="Sample" data-message="An example of a growl-like notification.">Trigger Notification</button>
    <button class="btn btn-info" type="button" data-type="growl" data-style="info"
            data-title="Sample" data-message="An example of a growl-like notification.">Trigger Notification</button>
    <button class="btn btn-warning" type="button" data-type="growl" data-style="warning"
            data-title="Sample" data-message="An example of a growl-like notification.">Trigger Notification</button>
    <button class="btn btn-danger" type="button" data-type="growl" data-style="danger"
            data-title="Sample" data-message="An example of a growl-like notification.">Trigger Notification</button>

Bootstrap Tables http://bootstrap-table.wenzhixin.net.cn

        <button type="button" class="btn btn-xs btn-default" data-gist="756e70e4c64c504f3d9c">Show code sample</button>

            Name
            Employees
            State
            Description

SVG Icons

        <button type="button" class="btn btn-xs btn-default" data-gist="e027544494a59899fdbe">Show code sample</button>

This is just a small set of SVG icons. More can be added whenever

                    <svg class="svg-cart" title="svg-cart"><use xlink:href="#svg-cart"></use></svg>

                    <svg class="svg-envelop3"><use xlink:href="#svg-envelop3"></use></svg>

                    <svg class="svg-bell2"><use xlink:href="#svg-bell2"></use></svg>

                    <svg class="svg-bubbles2"><use xlink:href="#svg-bubbles2"></use></svg>

                    <svg class="svg-bubbles7"><use xlink:href="#svg-bubbles7"></use></svg>

                    <svg class="svg-bubbles10"><use xlink:href="#svg-bubbles10"></use></svg>

                    <svg class="svg-user"><use xlink:href="#svg-user"></use></svg>

                    <svg class="svg-users"><use xlink:href="#svg-users"></use></svg>

                    <svg class="svg-user-plus"><use xlink:href="#svg-user-plus"></use></svg>

                    <svg class="svg-user-minus"><use xlink:href="#svg-user-minus"></use></svg>

                    <svg class="svg-user-cancel"><use xlink:href="#svg-user-cancel"></use></svg>

                    <svg class="svg-user-block"><use xlink:href="#svg-user-block"></use></svg>

                    <svg class="svg-user-lock"><use xlink:href="#svg-user-lock"></use></svg>

                    <svg class="svg-user-check"><use xlink:href="#svg-user-check"></use></svg>

                    <svg class="svg-users2"><use xlink:href="#svg-users2"></use></svg>

                    <svg class="svg-stats-dots"><use xlink:href="#svg-stats-dots"></use></svg>

                    <svg class="svg-stats-bars2"><use xlink:href="#svg-stats-bars2"></use></svg>

                    <svg class="svg-meter"><use xlink:href="#svg-meter"></use></svg>

                    <svg class="svg-switch"><use xlink:href="#svg-switch"></use></svg>

                    <svg class="svg-warning"><use xlink:href="#svg-warning"></use></svg>

                    <svg class="svg-warning2"><use xlink:href="#svg-warning2"></use></svg>

                    <svg class="svg-notification"><use xlink:href="#svg-notification"></use></svg>

                    <svg class="svg-notification2"><use xlink:href="#svg-notification2"></use></svg>

                    <svg class="svg-question3"><use xlink:href="#svg-question3"></use></svg>

                    <svg class="svg-question4"><use xlink:href="#svg-question4"></use></svg>

                    <svg class="svg-plus-circle2"><use xlink:href="#svg-plus-circle2"></use></svg>

                    <svg class="svg-minus-circle2"><use xlink:href="#svg-minus-circle2"></use></svg>

                    <svg class="svg-info"><use xlink:href="#svg-info"></use></svg>

                    <svg class="svg-info2"><use xlink:href="#svg-info2"></use></svg>

                    <svg class="svg-cancel-circle"><use xlink:href="#svg-cancel-circle"></use></svg>

                    <svg class="svg-arrow-up"><use xlink:href="#svg-arrow-up"></use></svg>

                    <svg class="svg-arrow-up2"><use xlink:href="#svg-arrow-up2"></use></svg>

                    <svg class="svg-arrow-up3"><use xlink:href="#svg-arrow-up3"></use></svg>

                    <svg class="svg-arrow-up4"><use xlink:href="#svg-arrow-up4"></use></svg>

                    <svg class="svg-arrow-right"><use xlink:href="#svg-arrow-right"></use></svg>

                    <svg class="svg-arrow-right2"><use xlink:href="#svg-arrow-right2"></use></svg>

                    <svg class="svg-arrow-right3"><use xlink:href="#svg-arrow-right3"></use></svg>

                    <svg class="svg-arrow-right4"><use xlink:href="#svg-arrow-right4"></use></svg>

                    <svg class="svg-arrow-down"><use xlink:href="#svg-arrow-down"></use></svg>

                    <svg class="svg-arrow-down2"><use xlink:href="#svg-arrow-down2"></use></svg>

                    <svg class="svg-arrow-down3"><use xlink:href="#svg-arrow-down3"></use></svg>

                    <svg class="svg-arrow-down4"><use xlink:href="#svg-arrow-down4"></use></svg>

                    <svg class="svg-arrow-left"><use xlink:href="#svg-arrow-left"></use></svg>

                    <svg class="svg-arrow-left2"><use xlink:href="#svg-arrow-left2"></use></svg>

                    <svg class="svg-arrow-left3"><use xlink:href="#svg-arrow-left3"></use></svg>

                    <svg class="svg-arrow-left4"><use xlink:href="#svg-arrow-left4"></use></svg>

                    <svg class="svg-arrow-up5"><use xlink:href="#svg-arrow-up5"></use></svg>

                    <svg class="svg-arrow-right5"><use xlink:href="#svg-arrow-right5"></use></svg>

                    <svg class="svg-arrow-down5"><use xlink:href="#svg-arrow-down5"></use></svg>

                    <svg class="svg-arrow-left5"><use xlink:href="#svg-arrow-left5"></use></svg>

                    <svg class="svg-circle-right4"><use xlink:href="#svg-circle-right4"></use></svg>

                    <svg class="svg-circle-left4"><use xlink:href="#svg-circle-left4"></use></svg>

                    <svg class="svg-checkbox-checked"><use xlink:href="#svg-checkbox-checked"></use></svg>

                    <svg class="svg-checkbox-unchecked"><use xlink:href="#svg-checkbox-unchecked"></use></svg>

                    <svg class="svg-checkbox-partial"><use xlink:href="#svg-checkbox-partial"></use></svg>

                    <svg class="svg-radio-checked"><use xlink:href="#svg-radio-checked"></use></svg>

                    <svg class="svg-radio-checked2"><use xlink:href="#svg-radio-checked2"></use></svg>

                    <svg class="svg-radio-unchecked"><use xlink:href="#svg-radio-unchecked"></use></svg>

                    <svg class="svg-google-plus"><use xlink:href="#svg-google-plus"></use></svg>

                    <svg class="svg-google-plus2"><use xlink:href="#svg-google-plus2"></use></svg>

                    <svg class="svg-facebook"><use xlink:href="#svg-facebook"></use></svg>

                    <svg class="svg-facebook2"><use xlink:href="#svg-facebook2"></use></svg>

                    <svg class="svg-twitter"><use xlink:href="#svg-twitter"></use></svg>

                    <svg class="svg-twitter2"><use xlink:href="#svg-twitter2"></use></svg>

                    <svg class="svg-feed3"><use xlink:href="#svg-feed3"></use></svg>

                    <svg class="svg-youtube"><use xlink:href="#svg-youtube"></use></svg>

                    <svg class="svg-youtube2"><use xlink:href="#svg-youtube2"></use></svg>

                    <svg class="svg-vimeo"><use xlink:href="#svg-vimeo"></use></svg>

                    <svg class="svg-vimeo2"><use xlink:href="#svg-vimeo2"></use></svg>

                    <svg class="svg-linkedin"><use xlink:href="#svg-linkedin"></use></svg>

                    <svg class="svg-linkedin2"><use xlink:href="#svg-linkedin2"></use></svg>

                    <svg class="svg-html5"><use xlink:href="#svg-html5"></use></svg>

                    <svg class="svg-svg"><use xlink:href="#svg-svg"></use></svg>

                    <svg class="svg-chrome"><use xlink:href="#svg-chrome"></use></svg>

                    <svg class="svg-firefox"><use xlink:href="#svg-firefox"></use></svg>

                    <svg class="svg-IE"><use xlink:href="#svg-IE"></use></svg>

                    <svg class="svg-opera"><use xlink:href="#svg-opera"></use></svg>

                    <svg class="svg-safari"><use xlink:href="#svg-safari"></use></svg>

Glyphicons http://getbootstrap.com/components/#glyphicons

        <button type="button" class="btn btn-xs btn-default" data-gist="e6c5a43032ab99220721">Show code sample</button>

@endsection

@section('script')

@endsection


text:
package io.druid.discovery;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.druid.server.DruidNode;
import io.druid.server.coordination.ServerType;
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 */
public class DruidNodeDiscoveryProviderTest
{
  @Test
  public void testGetForService()
  {
    TestDruidNodeDiscoveryProvider provider = new TestDruidNodeDiscoveryProvider();

    DruidNodeDiscovery dataNodeDiscovery = provider.getForService(DataNodeService.DISCOVERY_SERVICE_KEY);
    Set<DiscoveryDruidNode> dataNodes = new HashSet<>();
    dataNodeDiscovery.registerListener(
        new DruidNodeDiscovery.Listener()
        {
          @Override
          public void nodesAdded(List<DiscoveryDruidNode> nodes)
          {
            dataNodes.addAll(nodes);
          }

          @Override
          public void nodesRemoved(List<DiscoveryDruidNode> nodes)
          {
            dataNodes.removeAll(nodes);
          }
        }
    );

    DruidNodeDiscovery lookupNodeDiscovery = provider.getForService(LookupNodeService.DISCOVERY_SERVICE_KEY);
    Set<DiscoveryDruidNode> lookupNodes = new HashSet<>();
    lookupNodeDiscovery.registerListener(
        new DruidNodeDiscovery.Listener()
        {
          @Override
          public void nodesAdded(List<DiscoveryDruidNode> nodes)
          {
            lookupNodes.addAll(nodes);
          }

          @Override
          public void nodesRemoved(List<DiscoveryDruidNode> nodes)
          {
            lookupNodes.removeAll(nodes);
          }
        }
    );

    Assert.assertTrue(dataNodes.isEmpty());
    Assert.assertTrue(dataNodes.isEmpty());
    Assert.assertTrue(dataNodeDiscovery.getAllNodes().isEmpty());
    Assert.assertTrue(lookupNodes.isEmpty());
    Assert.assertTrue(lookupNodeDiscovery.getAllNodes().isEmpty());

    DiscoveryDruidNode node1 = new DiscoveryDruidNode(
        new DruidNode("s1", "h1", 8080, null, true, false),
        DruidNodeDiscoveryProvider.NODE_TYPE_HISTORICAL,
        ImmutableMap.of(
            DataNodeService.DISCOVERY_SERVICE_KEY, new DataNodeService("tier", 1000, ServerType.HISTORICAL, 0),
            LookupNodeService.DISCOVERY_SERVICE_KEY, new LookupNodeService("tier"))
    );

    DiscoveryDruidNode node2 = new DiscoveryDruidNode(
        new DruidNode("s2", "h2", 8080, null, true, false),
        DruidNodeDiscoveryProvider.NODE_TYPE_HISTORICAL,
        ImmutableMap.of(
            DataNodeService.DISCOVERY_SERVICE_KEY, new DataNodeService("tier", 1000, ServerType.HISTORICAL, 0))
    );

    DiscoveryDruidNode node3 = new DiscoveryDruidNode(
        new DruidNode("s3", "h3", 8080, null, true, false),
        DruidNodeDiscoveryProvider.NODE_TYPE_HISTORICAL,
        ImmutableMap.of(
            LookupNodeService.DISCOVERY_SERVICE_KEY, new LookupNodeService("tier"))
    );

    DiscoveryDruidNode node4 = new DiscoveryDruidNode(
        new DruidNode("s4", "h4", 8080, null, true, false),
        DruidNodeDiscoveryProvider.NODE_TYPE_PEON,
        ImmutableMap.of(
            DataNodeService.DISCOVERY_SERVICE_KEY, new DataNodeService("tier", 1000, ServerType.HISTORICAL, 0),
            LookupNodeService.DISCOVERY_SERVICE_KEY, new LookupNodeService("tier"))
    );

    DiscoveryDruidNode node5 = new DiscoveryDruidNode(
        new DruidNode("s5", "h5", 8080, null, true, false),
        DruidNodeDiscoveryProvider.NODE_TYPE_PEON,
        ImmutableMap.of(
            DataNodeService.DISCOVERY_SERVICE_KEY, new DataNodeService("tier", 1000, ServerType.HISTORICAL, 0))
    );

    DiscoveryDruidNode node6 = new DiscoveryDruidNode(
        new DruidNode("s6", "h6", 8080, null, true, false),
        DruidNodeDiscoveryProvider.NODE_TYPE_PEON,
        ImmutableMap.of(
            LookupNodeService.DISCOVERY_SERVICE_KEY, new LookupNodeService("tier"))
    );

    DiscoveryDruidNode node7 = new DiscoveryDruidNode(
        new DruidNode("s7", "h7", 8080, null, true, false),
        DruidNodeDiscoveryProvider.NODE_TYPE_BROKER,
        ImmutableMap.of(
            LookupNodeService.DISCOVERY_SERVICE_KEY, new LookupNodeService("tier"))
    );

    DiscoveryDruidNode node7Clone = new DiscoveryDruidNode(
        new DruidNode("s7", "h7", 8080, null, true, false),
        DruidNodeDiscoveryProvider.NODE_TYPE_BROKER,
        ImmutableMap.of(
            LookupNodeService.DISCOVERY_SERVICE_KEY, new LookupNodeService("tier"))
    );

    DiscoveryDruidNode node8 = new DiscoveryDruidNode(
        new DruidNode("s8", "h8", 8080, null, true, false),
        DruidNodeDiscoveryProvider.NODE_TYPE_COORDINATOR,
        ImmutableMap.of()
    );

    provider.add(node1);
    provider.add(node2);
    provider.add(node3);
    provider.add(node4);
    provider.add(node5);
    provider.add(node6);
    provider.add(node7);
    provider.add(node7Clone);
    provider.add(node8);

    Assert.assertEquals(ImmutableSet.of(node1, node2, node4, node5), ImmutableSet.copyOf(dataNodeDiscovery.getAllNodes()));
    Assert.assertEquals(ImmutableSet.of(node1, node2, node4, node5), dataNodes);

    Assert.assertEquals(ImmutableSet.of(node1, node3, node4, node6, node7), ImmutableSet.copyOf(lookupNodeDiscovery.getAllNodes()));
    Assert.assertEquals(ImmutableSet.of(node1, node3, node4, node6, node7), lookupNodes);

    provider.remove(node8);
    provider.remove(node7Clone);
    provider.remove(node6);
    provider.remove(node5);
    provider.remove(node4);

    Assert.assertEquals(ImmutableSet.of(node1, node2), ImmutableSet.copyOf(dataNodeDiscovery.getAllNodes()));
    Assert.assertEquals(ImmutableSet.of(node1, node2), dataNodes);

    Assert.assertEquals(ImmutableSet.of(node1, node3), ImmutableSet.copyOf(lookupNodeDiscovery.getAllNodes()));
    Assert.assertEquals(ImmutableSet.of(node1, node3), lookupNodes);
  }

  private static class TestDruidNodeDiscoveryProvider extends DruidNodeDiscoveryProvider
  {
    private List<DruidNodeDiscovery.Listener> listeners = new ArrayList<>();

    @Override
    public DruidNodeDiscovery getForNodeType(String nodeType)
    {
      return new DruidNodeDiscovery()
      {
        @Override
        public Set<DiscoveryDruidNode> getAllNodes()
        {
          throw new UnsupportedOperationException();
        }

        @Override
        public void registerListener(Listener listener)
        {
          TestDruidNodeDiscoveryProvider.this.listeners.add(listener);
        }
      };
    }

    void add(DiscoveryDruidNode node)
    {
      for (DruidNodeDiscovery.Listener listener : listeners) {
        listener.nodesAdded(ImmutableList.of(node));
      }
    }

    void remove(DiscoveryDruidNode node)
    {
      for (DruidNodeDiscovery.Listener listener : listeners) {
        listener.nodesRemoved(ImmutableList.of(node));
      }
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace Examples
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            SolidEdgeFramework.Application application = null;
            SolidEdgeFramework.Documents documents = null;
            SolidEdgePart.PartDocument partDocument = null;
            SolidEdgePart.RefPlanes refPlanes = null;
            SolidEdgePart.ProfileSets profileSets = null;
            SolidEdgePart.ProfileSet profileSet = null;
            SolidEdgePart.Profiles profiles = null;
            SolidEdgePart.Profile profile = null;
            SolidEdgeFrameworkSupport.Relations2d relations2d = null;
            SolidEdgeFrameworkSupport.Relation2d relation2d = null;
            SolidEdgeFrameworkSupport.Lines2d lines2d = null;
            SolidEdgeFrameworkSupport.Line2d line2d = null;
            SolidEdgeFrameworkSupport.Circles2d circles2d = null;
            SolidEdgeFrameworkSupport.Circle2d circle2d = null;
            SolidEdgeFrameworkSupport.Arcs2d arcs2d = null;
            SolidEdgeFrameworkSupport.Arc2d arc2d = null;

            try
            {
                // See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
                OleMessageFilter.Register();

                // Attempt to connect to a running instance of Solid Edge.
                application = (SolidEdgeFramework.Application)Marshal.GetActiveObject("SolidEdge.Application");
                documents = application.Documents;
                partDocument = (SolidEdgePart.PartDocument)documents.Add("SolidEdge.PartDocument");
                refPlanes = partDocument.RefPlanes;
                profileSets = partDocument.ProfileSets;
                profileSet = profileSets.Add();
                profiles = profileSet.Profiles;
                profile = profiles.Add(refPlanes.Item(1));
                relations2d = (SolidEdgeFrameworkSupport.Relations2d)profile.Relations2d;
                lines2d = profile.Lines2d;
                circles2d = profile.Circles2d;
                arcs2d = profile.Arcs2d;

                line2d = lines2d.AddBy2Points(0.15, 0.15, 0.2, 0.2);
                circle2d = circles2d.AddByCenterRadius(0.15, 0.15, 0.05);
                arc2d = arcs2d.AddByStartAlongEnd(0.2, 0.2, 0.25, 0.2, 0.2, 0.25);

                var Elements = (System.Array)new object[] { line2d, circle2d, arc2d };
                relation2d = relations2d.AddSet(Elements.Length, ref Elements);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                OleMessageFilter.Unregister();
            }
        }
    }
}


text:
RocketChat.callbacks.add('afterSaveMessage', function(message, room) {
    // skips this callback if the message was edited
    if (message.editedAt) {
        return message;
    }

    // check if room is yet awaiting for response
    if (!(typeof room.t !== 'undefined' && room.t === 'l' && room.waitingResponse)) {
        return message;
    }

    // if the message has a token, it was sent by the visitor, so ignore it
    if (message.token) {
        return message;
    }

    Meteor.defer(() => {
        let now = new Date();
        var response = 0;
        if (message.t != 'livechat-close') {
            response = (now.getTime() - room.ts) / 1000;
        }
        RocketChat.models.Rooms.setResponseByRoomId(room._id, {
            user: {
                _id: message.u._id,
                username: message.u.username
            },
            responseDate: now,
            responseTime: response
        });
    });

    return message;
}, RocketChat.callbacks.priority.LOW, 'markRoomResponded');


text:
class CreateResultWeights < ActiveRecord::Migration
  def change
    create_table :result_weights do |t|
      t.integer :position, null: false
      t.float :weight, null: false

      t.timestamps null: false
    end
		add_index :result_weights, :position, unique: true
  end
end


text:
<?php
/**
 * Project: zf2-twb-bundle, File: TwbBundleFontAwesomeTest.php
 * @author Michael Schakulat <michael@fetchit.de>
 * @package zf2-twb-bundle
 */

namespace TwbBundleTest\View\Helper;

use TwbBundle\View\Helper\TwbBundleFontAwesome;
use TwbBundleTest\Bootstrap;
use Zend\View\Renderer\PhpRenderer;

class TwbBundleFontAwesomeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var TwbBundleFontAwesome
     */
    protected $fontAwesomeHelper;

    /**
     * @see \PHPUnit_Framework_TestCase::setUp()
     */
    public function setUp() {
        $oViewHelperPluginManager = Bootstrap::getServiceManager()
            ->get('ViewHelperManager');
        $oRenderer = new PhpRenderer();
        $this->fontAwesomeHelper = $oViewHelperPluginManager->get('fontAwesome')
            ->setView(
                $oRenderer->setHelperPluginManager($oViewHelperPluginManager)
            );
    }

    public function testInvoke() {
        $this->assertSame(
            $this->fontAwesomeHelper, $this->fontAwesomeHelper->__invoke()
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testRenderWithWrongTypeFontAwesome() {
        $this->fontAwesomeHelper->render(new \stdClass());
    }

    public function testRenderWithEmptyClassAttributes() {
        $this->assertEquals(
            '',
            $this->fontAwesomeHelper->render('test', array('class' => ''))
        );
    }

    public function testRenderWithDefinedClassAttributes() {
        $this->assertEquals(
            '',
            $this->fontAwesomeHelper->render('test', array('class' => 'test'))
        );
    }
}