text:
"""Contains classes for the Tokenizer."""

from sparknlp.common import *
from sparknlp.common.annotator_type import AnnotatorType

class Tokenizer(AnnotatorApproach):
    """Tokenizes raw text in document type columns into TokenizedSentence .

    This class represents a non fitted tokenizer. Fitting it will cause the
    internal RuleFactory to construct the rules for tokenizing from the input
    configuration.

    Identifies tokens with tokenization open standards. A few rules will help
    customizing it if defaults do not fit user needs.

    For extended examples of usage see the `Spark NLP Workshop
    <https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Public/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb>`__.

    ====================== ======================
    Input Annotation types Output Annotation type
    ====================== ======================
    ``DOCUMENT``           ``TOKEN``
    ====================== ======================

    Parameters
    ----------
    targetPattern
        Pattern to grab from text as token candidates, by default ``\\S+``
    prefixPattern
        Regex with groups and begins with ``\\A`` to match target prefix, by
        default ``\\A([^\\s\\w\\$\\.]*)``
    suffixPattern
        Regex with groups and ends with ``\\z`` to match target suffix, by
        default ``([^\\s\\w]?)([^\\s\\w]*)\\z``
    infixPatterns
        Regex patterns that match tokens within a single target. groups identify
        different sub-tokens. multiple defaults
    exceptions
        Words that won't be affected by tokenization rules
    exceptionsPath
        Path to file containing list of exceptions
    caseSensitiveExceptions
        Whether to care for case sensitiveness in exceptions, by default True
    contextChars
        Character list used to separate from token boundaries, by default ['.',
        ',', ';', ':', '!', '?', '*', '-', '(', ')', '"', "'"]
    splitPattern
        Pattern to separate from the inside of tokens. Takes priority over
        splitChars.
    splitChars
        Character list used to separate from the inside of tokens
    minLength
        Set the minimum allowed length for each token, by default 0
    maxLength
        Set the maximum allowed length for each token, by default 99999

    Examples
    --------
    >>> import sparknlp
    >>> from sparknlp.base import *
    >>> from sparknlp.annotator import *
    >>> from pyspark.ml import Pipeline
    >>> data = spark.createDataFrame([["I'd like to say we didn't expect that. Jane's boyfriend."]]).toDF("text")
    >>> documentAssembler = DocumentAssembler().setInputCol("text").setOutputCol("document")
    >>> tokenizer = Tokenizer().setInputCols(["document"]).setOutputCol("token").fit(data)
    >>> pipeline = Pipeline().setStages([documentAssembler, tokenizer]).fit(data)
    >>> result = pipeline.transform(data)
    >>> result.selectExpr("token.result").show(truncate=False)
    +-----------------------------------------------------------------------+
    |output                                                                 |
    +-----------------------------------------------------------------------+
    |[I'd, like, to, say, we, didn't, expect, that, ., Jane's, boyfriend, .]|
    +-----------------------------------------------------------------------+
    """

    name = 'Tokenizer'

    inputAnnotatorTypes = [AnnotatorType.DOCUMENT]

    targetPattern = Param(Params._dummy(),
                          "targetPattern",
                          "pattern to grab from text as token candidates. Defaults \S+",
                          typeConverter=TypeConverters.toString)

    prefixPattern = Param(Params._dummy(),
                          "prefixPattern",
                          "regex with groups and begins with \A to match target prefix. Defaults to \A([^\s\w\$\.]*)",
                          typeConverter=TypeConverters.toString)

    suffixPattern = Param(Params._dummy(),
                          "suffixPattern",
                          "regex with groups and ends with \z to match target suffix. Defaults to ([^\s\w]?)([^\s\w]*)\z",
                          typeConverter=TypeConverters.toString)

    infixPatterns = Param(Params._dummy(),
                          "infixPatterns",
                          "regex patterns that match tokens within a single target. groups identify different sub-tokens. multiple defaults",
                          typeConverter=TypeConverters.toListString)

    exceptions = Param(Params._dummy(),
                       "exceptions",
                       "Words that won't be affected by tokenization rules",
                       typeConverter=TypeConverters.toListString)

    exceptionsPath = Param(Params._dummy(),
                           "exceptionsPath",
                           "path to file containing list of exceptions",
                           typeConverter=TypeConverters.identity)

    caseSensitiveExceptions = Param(Params._dummy(),
                                    "caseSensitiveExceptions",
                                    "Whether to care for case sensitiveness in exceptions",
                                    typeConverter=TypeConverters.toBoolean)

    contextChars = Param(Params._dummy(),
                         "contextChars",
                         "character list used to separate from token boundaries",
                         typeConverter=TypeConverters.toListString)

    splitPattern = Param(Params._dummy(),
                         "splitPattern",
                         "character list used to separate from the inside of tokens",
                         typeConverter=TypeConverters.toString)

    splitChars = Param(Params._dummy(),
                       "splitChars",
                       "character list used to separate from the inside of tokens",
                       typeConverter=TypeConverters.toListString)

    minLength = Param(Params._dummy(),
                      "minLength",
                      "Set the minimum allowed length for each token",
                      typeConverter=TypeConverters.toInt)

    maxLength = Param(Params._dummy(),
                      "maxLength",
                      "Set the maximum allowed length for each token",
                      typeConverter=TypeConverters.toInt)

    @keyword_only
    def __init__(self):
        super(Tokenizer, self).__init__(classname="com.johnsnowlabs.nlp.annotators.Tokenizer")
        self._setDefault(
            targetPattern="\\S+",
            contextChars=[".", ",", ";", ":", "!", "?", "*", "-", "(", ")", "\"", "'"],
            caseSensitiveExceptions=True,
            minLength=0,
            maxLength=99999
        )

    def getInfixPatterns(self):
        """Gets regex patterns that match tokens within a single target. Groups
        identify different sub-tokens.

        Returns
        -------
        List[str]
            The infix patterns
        """
        return self.getOrDefault("infixPatterns")

    def getSuffixPattern(self):
        """Gets regex with groups and ends with ``\\z`` to match target suffix.

        Returns
        -------
        str
            The suffix pattern
        """
        return self.getOrDefault("suffixPattern")

    def getPrefixPattern(self):
        """Gets regex with groups and begins with ``\\A`` to match target
        prefix.

        Returns
        -------
        str
            The prefix pattern
        """
        return self.getOrDefault("prefixPattern")

    def getContextChars(self):
        """Gets character list used to separate from token boundaries.

        Returns
        -------
        List[str]
            Character list used to separate from token boundaries
        """
        return self.getOrDefault("contextChars")

    def getSplitChars(self):
        """Gets character list used to separate from the inside of tokens.

        Returns
        -------
        List[str]
            Character list used to separate from the inside of tokens
        """
        return self.getOrDefault("splitChars")

    def setTargetPattern(self, value):
        """Sets pattern to grab from text as token candidates, by default
        ``\\S+``.

        Parameters
        ----------
        value : str
            Pattern to grab from text as token candidates
        """
        return self._set(targetPattern=value)

    def setPrefixPattern(self, value):
        """Sets regex with groups and begins with ``\\A`` to match target prefix, by
        default ``\\A([^\\s\\w\\$\\.]*)``.

        Parameters
        ----------
        value : str
            Regex with groups and begins with ``\\A`` to match target prefix
        """
        return self._set(prefixPattern=value)

    def setSuffixPattern(self, value):
        """Sets regex with groups and ends with ``\\z`` to match target suffix,
        by default ``([^\\s\\w]?)([^\\s\\w]*)\\z``.

        Parameters
        ----------
        value : str
            Regex with groups and ends with ``\\z`` to match target suffix
        """
        return self._set(suffixPattern=value)

    def setInfixPatterns(self, value):
        """Sets regex patterns that match tokens within a single target. Groups
        identify different sub-tokens.

        Parameters
        ----------
        value : List[str]
            Regex patterns that match tokens within a single target
        """
        return self._set(infixPatterns=value)

    def addInfixPattern(self, value):
        """Adds an additional regex pattern that match tokens within a single
        target. Groups identify different sub-tokens.

        Parameters
        ----------
        value : str
            Regex pattern that match tokens within a single target
        """
        try:
            infix_patterns = self.getInfixPatterns()
        except KeyError:
            infix_patterns = []
        infix_patterns.insert(0, value)
        return self._set(infixPatterns=infix_patterns)

    def setExceptions(self, value):
        """Sets words that won't be affected by tokenization rules.

        Parameters
        ----------
        value : List[str]
            Words that won't be affected by tokenization rules
        """
        return self._set(exceptions=value)

    def getExceptions(self):
        """Gets words that won't be affected by tokenization rules.

        Returns
        -------
        List[str]
            Words that won't be affected by tokenization rules
        """
        return self.getOrDefault("exceptions")

    def setExceptionsPath(self, path, read_as=ReadAs.TEXT, options={"format": "text"}):
        """Path to txt file with list of token exceptions

        Parameters
        ----------
        path : str
            Path to the source file
        read_as : str, optional
            How to read the file, by default ReadAs.TEXT
        options : dict, optional
            Options to read the resource, by default {"format": "text"}
        """
        opts = options.copy()
        return self._set(exceptionsPath=ExternalResource(path, read_as, opts))

    def addException(self, value):
        """Adds an additional word that won't be affected by tokenization rules.

        Parameters
        ----------
        value : str
            Additional word that won't be affected by tokenization rules
        """
        try:
            exception_tokens = self.getExceptions()
        except KeyError:
            exception_tokens = []
        exception_tokens.append(value)
        return self._set(exceptions=exception_tokens)

    def setCaseSensitiveExceptions(self, value):
        """Sets whether to care for case sensitiveness in exceptions, by default
        True.

        Parameters
        ----------
        value : bool
            Whether to care for case sensitiveness in exceptions
        """
        return self._set(caseSensitiveExceptions=value)

    def getCaseSensitiveExceptions(self):
        """Gets whether to care for case sensitiveness in exceptions.

        Returns
        -------
        bool
            Whether to care for case sensitiveness in exceptions
        """
        return self.getOrDefault("caseSensitiveExceptions")

    def setContextChars(self, value):
        """Sets character list used to separate from token boundaries, by
        default ['.', ',', ';', ':', '!', '?', '*', '-', '(', ')', '"', "'"].

        Parameters
        ----------
        value : List[str]
            Character list used to separate from token boundaries
        """
        return self._set(contextChars=value)

    def addContextChars(self, value):
        """Adds an additional character to the list used to separate from token
        boundaries.

        Parameters
        ----------
        value : str
            Additional context character
        """
        try:
            context_chars = self.getContextChars()
        except KeyError:
            context_chars = []
        context_chars.append(value)
        return self._set(contextChars=context_chars)

    def setSplitPattern(self, value):
        """Sets pattern to separate from the inside of tokens. Takes priority
        over splitChars.

        Parameters
        ----------
        value : str
            Pattern used to separate from the inside of tokens
        """
        return self._set(splitPattern=value)

    def setSplitChars(self, value):
        """Sets character list used to separate from the inside of tokens.

        Parameters
        ----------
        value : List[str]
            Character list used to separate from the inside of tokens
        """
        return self._set(splitChars=value)

    def addSplitChars(self, value):
        """Adds an additional character to separate from the inside of tokens.

        Parameters
        ----------
        value : str
            Additional character to separate from the inside of tokens
        """
        try:
            split_chars = self.getSplitChars()
        except KeyError:
            split_chars = []
        split_chars.append(value)
        return self._set(splitChars=split_chars)

    def setMinLength(self, value):
        """Sets the minimum allowed length for each token, by default 0.

        Parameters
        ----------
        value : int
            Minimum allowed length for each token
        """
        return self._set(minLength=value)

    def setMaxLength(self, value):
        """Sets the maximum allowed length for each token, by default 99999.

        Parameters
        ----------
        value : int
            Maximum allowed length for each token
        """
        return self._set(maxLength=value)

    def _create_model(self, java_model):
        return TokenizerModel(java_model=java_model)

class TokenizerModel(AnnotatorModel):
    """Tokenizes raw text into word pieces, tokens. Identifies tokens with
    tokenization open standards. A few rules will help customizing it if
    defaults do not fit user needs.

    This class represents an already fitted :class:`.Tokenizer`.

    See the main class Tokenizer for more examples of usage.

    ======================  ======================
    Input Annotation types  Output Annotation type
    ======================  ======================
    ``DOCUMENT``            ``TOKEN``
    ======================  ======================

    Parameters
    ----------
    splitPattern
        Character list used to separate from the inside of tokens
    splitChars
        Character list used to separate from the inside of tokens
    """
    name = "TokenizerModel"

    inputAnnotatorTypes = [AnnotatorType.DOCUMENT]

    exceptions = Param(Params._dummy(),
                       "exceptions",
                       "Words that won't be affected by tokenization rules",
                       typeConverter=TypeConverters.toListString)

    caseSensitiveExceptions = Param(Params._dummy(),
                                    "caseSensitiveExceptions",
                                    "Whether to care for case sensitiveness in exceptions",
                                    typeConverter=TypeConverters.toBoolean)

    targetPattern = Param(Params._dummy(),
                          "targetPattern",
                          "pattern to grab from text as token candidates. Defaults \S+",
                          typeConverter=TypeConverters.toString)

    rules = Param(Params._dummy(),
                  "rules",
                  "Rules structure factory containing pre processed regex rules",
                  typeConverter=TypeConverters.identity)

    splitPattern = Param(Params._dummy(),
                         "splitPattern",
                         "character list used to separate from the inside of tokens",
                         typeConverter=TypeConverters.toString)

    splitChars = Param(Params._dummy(),
                       "splitChars",
                       "character list used to separate from the inside of tokens",
                       typeConverter=TypeConverters.toListString)

    def __init__(self, classname="com.johnsnowlabs.nlp.annotators.TokenizerModel", java_model=None):
        super(TokenizerModel, self).__init__(
            classname=classname,
            java_model=java_model
        )
        self._setDefault(
            targetPattern="\\S+",
            caseSensitiveExceptions=True
        )

    def setSplitPattern(self, value):
        """Sets pattern to separate from the inside of tokens. Takes priority
        over splitChars.

        Parameters
        ----------
        value : str
            Pattern used to separate from the inside of tokens
        """
        return self._set(splitPattern=value)

    def setSplitChars(self, value):
        """Sets character list used to separate from the inside of tokens.

        Parameters
        ----------
        value : List[str]
            Character list used to separate from the inside of tokens
        """
        return self._set(splitChars=value)

    def addSplitChars(self, value):
        """Adds an additional character to separate from the inside of tokens.

        Parameters
        ----------
        value : str
            Additional character to separate from the inside of tokens
        """
        try:
            split_chars = self.getSplitChars()
        except KeyError:
            split_chars = []
        split_chars.append(value)
        return self._set(splitChars=split_chars)

    @staticmethod
    def pretrained(name="token_rules", lang="en", remote_loc=None):
        """Downloads and loads a pretrained model.

        Parameters
        ----------
        name : str, optional
            Name of the pretrained model, by default "token_rules"
        lang : str, optional
            Language of the pretrained model, by default "en"
        remote_loc : str, optional
            Optional remote address of the resource, by default None. Will use
            Spark NLPs repositories otherwise.

        Returns
        -------
        TokenizerModel
            The restored model
        """
        from sparknlp.pretrained import ResourceDownloader
        return ResourceDownloader.downloadModel(TokenizerModel, name, lang, remote_loc)


text:
Today we will be making some simple 8x8 bitmap pictures. You will be given 8 hex values that can be 0-255 in decimal value (so 1 byte). Each value represents a row. So 8 rows of 8 bits so a 8x8 bitmap picture.

#Input:

8 Hex values.

##example:

18 3C 7E 7E 18 18 18 18

#Output:

A 8x8 picture that represents the values you read in.

For example say you got the hex value FF. This is 1111 1111 . "1" means the bitmap at that location is on and print something. "0" means nothing is printed so put a space. 1111 1111 would output this row:

    xxxxxxxx

if the next hex value is 81 it would be 1000 0001 in binary and so the 2nd row would output (with the first row)

    xxxxxxxx
    x      x

##Example output based on example input:

       xx
      xxxx
     xxxxxx
     xxxxxx
       xx
       xx
       xx
       xx

#Challenge input:

Here are 4 pictures to process and display:

    FF 81 BD A5 A5 BD 81 FF
    AA 55 AA 55 AA 55 AA 55
    3E 7F FC F8 F8 FC 7F 3E
    93 93 93 F3 F3 93 93 93

#Output Character:

I used "x" but feel free to use any ASCII value you want. Heck if you want to display it using graphics, feel free to be creative here.

redpajama_set_name: RedPajamaGithub


text:
title: Portland Ballroom
city: Nottingham
---
This has been converted into a food court.


text:
/**
 * Engphrase model events
 */

'use strict';

import {EventEmitter} from 'events';
import Engphrase from './engphrase.model';
var EngphraseEvents = new EventEmitter();

// Set max event listeners (0 == unlimited)
EngphraseEvents.setMaxListeners(0);

// Model events
var events = {
  save: 'save',
  remove: 'remove'
};

// Register the event emitter to the model events
for(var e in events) {
  let event = events[e];
  Engphrase.schema.post(e, emitEvent(event));
}

function emitEvent(event) {
  return function(doc) {
    EngphraseEvents.emit(event + ':' + doc._id, doc);
    EngphraseEvents.emit(event, doc);
  };
}

export default EngphraseEvents;


text:
using System;
using Independentsoft.Office;
using Independentsoft.Office.Word;
using Independentsoft.Office.Word.Fields;
using Independentsoft.Office.Word.HeaderFooter;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            WordDocument doc = new WordDocument();

            Page pageNumber = new Page();
            SimpleField simpleField = new SimpleField(pageNumber);

            Paragraph footerParagraph = new Paragraph();
            footerParagraph.Add(simpleField);
            footerParagraph.HorizontalTextAlignment = HorizontalAlignmentType.Center;

            Footer footer = new Footer();
            footer.Add(footerParagraph);

            Run run1 = new Run();
            run1.AddText("Hello Word!");

            Paragraph paragraph1 = new Paragraph();
            paragraph1.Add(run1);

            doc.Body.Add(paragraph1);
            doc.Body.Footer = footer;

            doc.Save("c:\\test\\output.docx", true);
        }
    }
}


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

from case import Case
import binascii

class Case6_2_3(Case):

   PAYLOAD = "Hello-µ@ßöäüàá-UTF-8!!"

   DESCRIPTION = """Send a valid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
%s
%s""" % (PAYLOAD, binascii.b2a_hex(PAYLOAD))

   EXPECTATION = """The message is echo'ed back to us."""

   def onOpen(self):

      self.expected[Case.OK] = [("message", self.PAYLOAD, False)]
      self.expectedClose = {"closedByMe":True,"closeCode":[self.p.CLOSE_STATUS_CODE_NORMAL],"requireClean":True}
      self.p.sendMessage(self.PAYLOAD, binary = False, payload_frag_size = 1)
      self.p.closeAfter(1)


text:
//
//  SGARResponder.h
//  SGAREnvironment
//
//  Copyright (c) 2009-2010, SimpleGeo
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//  Redistributions of source code must retain the above copyright notice,
//  this list of conditions and the following disclaimer. Redistributions
//  in binary form must reproduce the above copyright notice, this list of
//  conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//
//  Neither the name of the SimpleGeo nor the names of its contributors may
//  be used to endorse or promote products derived from this software
//  without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
//  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
//  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
//  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
//  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//  Created by Derek Smith.
//

/*!
* @protocol SGARResponder
* @abstract Defines the protocol for objects to respond to gesture and touch events created in the @link //simplegeo/ooc/cl/SGARView SGARView @/link.
* @discussion There are essentially two different enviornments where touch evenets can be generated, the augmented reality enviornment and the
* normal UIResponder chain. In order to loop in the AR envoirnment with the UIResponder chain, pre-calculations of touch events need to be
* acknowledged by the the AR view before they can be released onto the normal UIResponder chain. This protocol attempts to provides callback
* notifications when gestures are created within the AR envoirnment.
*
* SGARResponders are registered with @link //simplegeo/ooc/cl/SGARView SGARView @/link via
* @link //simplegeo/ooc/instm/SGARView/addResponder: addResponder: @/link.
*/
@protocol SGARResponder <NSObject>

@optional

/*!
* @method ARSingleTap:
* @abstract Notifies the reciever when a single touch event has occurred.
* @param point The point at which the touch event occurred.
*/
- (void) ARSingleTap:(CGPoint)point;

/*!
* @method ARDoubleTap:
* @abstract Notifies the reciever when a double touch event has occurred.
* @param point The point at which the touch event occurred.
*/
- (void) ARDoubleTap:(CGPoint)point;

/*!
* @method ARSingleTapAtPoint:andPoint:
* @abstract Notifies the reciever when a single touch event occurs at two points.
* @param pointOne One of the two points at which the touch event occurred.
* @param pointTwo The other point at which the touch event occurred.
*/
- (void) ARSingleTapAtPoint:(CGPoint)pointOne andPoint:(CGPoint)pointTwo;

/*!
* @method ARPinchAtPoint:andPoint:withDistance:
* @abstract Notifies the reciever when a pinch event occurs.
* @param pointOne One of the two points at which the touch event occurred.
* @param pointTwo The other point at which the touch event occurred.
* @param distance The distance between the two points. Why? For convience.
*/
- (void) ARPinchAtPoint:(CGPoint)pointOne andPoint:(CGPoint)pointTwo withDistance:(CGFloat)distance;

/*!
* @method ARPullAtPoint:andPoint:withDistance:
* @abstract Notifies the reciever when a pull event occurs.
* @param pointOne One of the two points at which the touch event occurred.
* @param pointTwo The other point at which the touch event occurred.
* @param distance The distance between the two points. Why? Because I can.
*/
- (void) ARPullAtPoint:(CGPoint)pointOne andPoint:(CGPoint)pointTwo withDistance:(CGFloat)distance;

/*!
* @method ARMoveFromPoint:toPoint:
* @abstract Notifies the reciever when a drag event occurs.
* @param fromPoint The start point of the drag.
* @param toPoint The end point of the drag.
*/
- (void) ARMoveFromPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint;

/*!
* @method ARMoveEndedAtPoint:
* @abstract Notifies the reicever when a drag events finishs.
* @param point The point at which the drag event was completed.
*/
- (void) ARMoveEndedAtPoint:(CGPoint)point;

/*!
* @method ARViewDidShake
* @abstract Notifies the reciever when the view is shaken.
*/
- (void) ARViewDidShake;

//
// The following methods are implemented but not thoroughly tested.
//

/*!
 * @method ARTapEndedAtPoint:
 * @abstract Notifies the reciever when a tap has been released.
 * @ point The point at which the tap was released.
 */
- (void) ARTapEndedAtPoint:(CGPoint)point;

/*!
 * @method ARHorizontalSwipeAtPoint:toPoint:
 * @abstract Notifies the delegate when a horizontal swipe has occurred.
 * @param fromPoint The starting point of the swipe.
 * @param toPoint The end point of the swipe.
 */
- (void) ARHorizontalSwipeAtPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint;

/*!
 * @method ARVerticalSwipeAtPoint:toPoint:
 * @abstract Notifies the delegate when a vertical swipe has occurred.
 * @param fromPoint The starting point of the swipe.
 * @param toPoint The end point of the swipe.
 */
- (void) ARVerticalSwipeAtPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint;

@end


text:
/*
 * Copyright (C) 1998, 1999, 2000,
 *
 * Arjuna Solutions Limited,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Util.java 2342 2006-03-30 13:06:17Z  $
 */

package com.hp.mwtests.ts.jts.utils;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.arjuna.ats.arjuna.state.InputObjectState;
import com.arjuna.ats.internal.jts.utils.TxStoreLog;

public class TxStoreLogUnitTest
{
    @Test
    public void test()
    {
        TxStoreLog log = new TxStoreLog();
        InputObjectState is = new InputObjectState();

        assertTrue(TxStoreLog.getTransactions(is));
    }
}


text:
package com.elmakers.mine.bukkit;

import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;

import com.elmakers.mine.bukkit.api.magic.Messages;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

public class ChatUtils {
    // Remove some standard java punctuation, plus the unicode range from "Number Forms" to "Miscellaneous symbols"
    private static final Pattern PUNCTUATION_PATTERN = Pattern.compile("[\\s0-9\\p{Punct}\\p{IsPunctuation}\u2150-\u2BFF\uE000-\uFFFF]"); // Sorry for the unicode escapes
    private static Messages messages;
    private static Gson gson;

    public static void initialize(Messages messages, Logger logger) {
        ChatUtils.messages = messages;
    }

    protected static Gson getGson() {
        if (gson == null) {
            gson = new Gson();
        }
        return gson;
    }

    protected static void getSimpleMessage(Map<String,Object> mapped, StringBuilder plainMessage, boolean onlyText) {
        getSimpleMessage(mapped, plainMessage, onlyText, ChatColor.RESET + " " + ChatColor.GRAY, ChatColor.RESET + " ");
    }

    @SuppressWarnings("unchecked")
    protected static void getSimpleMessage(Map<String,Object> mapped, StringBuilder plainMessage, boolean onlyText, String commandPrefix, String commandSuffix) {
        for (Map.Entry<String,Object> entry : mapped.entrySet()) {
            if (entry.getKey().equals("text")) {
                plainMessage.append(entry.getValue());
            } else if (entry.getKey().equals("extra")) {
                Object rawExtra = entry.getValue();
                if (rawExtra instanceof List) {
                    List<Map<String, Object>> mapList = (List<Map<String, Object>>)rawExtra;
                    for (Map<String, Object> child : mapList) {
                        getSimpleMessage(child, plainMessage, onlyText);
                    }
                }
            } else if (entry.getKey().equals("keybind")) {
                String key = entry.getValue().toString().replace("key.", "");
                if (messages != null) {
                    key = messages.get("keybind." + key, key);
                }
                plainMessage.append(commandPrefix + key + commandSuffix);
            } else if (onlyText) {
                continue;
            } else if (entry.getKey().equals("color")) {
                String colorKey = entry.getValue().toString();
                try {
                    ChatColor color = ChatColor.valueOf(colorKey.toUpperCase());
                    plainMessage.append(color);
                } catch (Exception ignore) {
                }
            } else if (entry.getKey().equals("clickEvent")) {
                Map<String,Object> properties = (Map<String,Object>)entry.getValue();
                if (properties.containsKey("action") && properties.containsKey("value")) {
                    String value = properties.get("value").toString();
                    String action = properties.get("action").toString();
                    switch (action) {
                        case "open_url":
                        case "run_command":
                        case "suggest_command":
                            plainMessage.append(commandPrefix + value + commandSuffix);
                            break;
                    }
                }
            }
        }
    }

    public static String getSimpleMessage(String containsJson) {
        return getSimpleMessage(containsJson, false);
    }

    public static String getSimpleMessage(String containsJson, boolean onlyText) {
        return getSimpleMessage(containsJson, onlyText, ChatColor.RESET + " " + ChatColor.GRAY, ChatColor.RESET + " ");
    }

    public static String getSimpleMessage(String containsJson, boolean onlyText, String commandPrefix, String commandSuffix) {
        String[] components = getComponents(containsJson);
        StringBuilder plainMessage = new StringBuilder();
        for (String component : components) {
            if (component.startsWith("{")) {
                try {
                    JsonReader reader = new JsonReader(new StringReader(component));
                    reader.setLenient(true);
                    Map<String, Object> mapped = getGson().fromJson(reader, Map.class);
                    getSimpleMessage(mapped, plainMessage, onlyText, commandPrefix, commandSuffix);
                } catch (Exception ex) {
                    plainMessage.append(component);
                }
            } else {
                plainMessage.append(component);
            }
        }
        return plainMessage.toString();
    }

    public static String[] getComponents(String containsJson) {
        return StringUtils.split(containsJson, "`");
    }

    public static String[] getWords(String text) {
        return PUNCTUATION_PATTERN.split(text);
    }

    public static boolean hasJSON(String text) {
        return text.contains("`{");
    }

    public static boolean isDefaultFont(String font) {
        return font == null || font.isEmpty() || font.equals("default");
    }

    public static void sendToConsoleSender(String message, Logger logger) {
        CommandSender sender = Bukkit.getConsoleSender();
        if (sender == null) {
            logger.info(ChatColor.stripColor(message));
        } else {
            sender.sendMessage(message);
        }
    }

    public static String getFixedWidth(String message, int width) {
        int messageLength = getSimpleMessage(message).length();
        if (messageLength < width) {
            message = message + StringUtils.repeat(" ", width - messageLength);
        } else if (messageLength > width) {
            message = getSimpleMessage(message).substring(0, width);
        }
        return message;
    }

    public static String printPercentage(double percentage) {
        return printRatio(percentage) + "%";
    }

    public static String printRatio(double percentage) {
        return Integer.toString((int)(percentage * 100));
    }

    public static double getSimilarity(String s1, String s2) {
        String longer = s1;
        String shorter = s2;

        // Find the longer of the two strings
        if (s1.length() < s2.length()) {
            longer = s2;
            shorter = s1;
        }

        int longerLength = longer.length();
        if (longerLength == 0) {
            // Special case for two empty string
            return 1.0;
        }

        return (longerLength - StringUtils.getLevenshteinDistance(longer, shorter)) / (double)longerLength;
    }
}


text:
import React, {PureComponent} from "react";
import PropTypes from 'prop-types';
import 'materialize-css/bin/materialize.css';
// import 'materialize-css/bin/materialize.js';

class Painel extends PureComponent {

    constructor(props){
        super(props);

        this.state = {
            isOpen: props.isOpen
        };
    }

    componentDidMount() {
        // this._montaCollapsible();
    }

    componentDidUpdate(prevProps, prevState) {
        // this._montaCollapsible();
        if(prevState.isOpen !== this.state.isOpen){
            // chamada forçada par ao resize, pois tem componentes que necessitam se reorganizar
            window.dispatchEvent(new Event('resize'));
        }
    }

    // _montaCollapsible(){
    //     $(document).ready(function () {
    //         $('.collapsible').collapsible();
    //     });
    // }

    _handleHeaderClick = () => {
        // console.log('this.state.isOpen', this.state.isOpen);
        this.setState({isOpen: !this.state.isOpen});
    };

    render() {

        // todo : Fazer animação quando abrir e fechar sem Jquery

        const {header, titulo, children,} = this.props;
        const {isOpen} = this.state;

        const display = isOpen ? 'block' : 'none';

        // console.log('isOpen', isOpen);
        // console.log('display', display);
        return (

{header ? header : titulo}

                        {children}

        );
    }
}

Painel.propTypes = {
    titulo: PropTypes.string,
    header: PropTypes.any,
    children: PropTypes.any,
    isOpen: PropTypes.bool,
};

Painel.defaultProps = {
    titulo: null,
    header: null,
    children:

,
    isOpen: false
};

export default Painel;


text:
package org.apache.activemq.artemis.tests.integration.divert;

import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.DivertConfiguration;
import org.apache.activemq.artemis.core.message.impl.MessageImpl;
import org.apache.activemq.artemis.core.postoffice.Binding;
import org.apache.activemq.artemis.core.postoffice.impl.DivertBinding;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServers;
import org.apache.activemq.artemis.core.server.Divert;
import org.apache.activemq.artemis.core.server.ServerMessage;
import org.apache.activemq.artemis.core.server.cluster.Transformer;
import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl;
import org.apache.activemq.artemis.core.server.impl.ServiceRegistryImpl;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.junit.Assert;
import org.junit.Test;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

public class DivertTest extends ActiveMQTestBase
{
   private static final int TIMEOUT = 500;

   @Test
   public void testSingleNonExclusiveDivert() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("divert1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      session.createQueue(new SimpleString(forwardAddress), queueName1, null, false);

      session.createQueue(new SimpleString(testAddress), queueName2, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      final int numMessages = 1;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());
   }

   @Test
   public void testSingleDivertWithExpiry() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      final String expiryAddress = "expiryAddress";

      AddressSettings expirySettings = new AddressSettings()
              .setExpiryAddress(new SimpleString(expiryAddress));

      DivertConfiguration divertConf = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("divert1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf)
              .clearAddressesSettings()
              .addAddressesSetting("#", expirySettings);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, true));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, false, false);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      session.createQueue(new SimpleString(forwardAddress), queueName1, null, true);

      session.createQueue(new SimpleString(testAddress), queueName2, null, true);

      session.createQueue(new SimpleString(expiryAddress), new SimpleString(expiryAddress), null, true);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      final int numMessages = 1;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(true);

         message.putIntProperty(propKey, i);

         message.setExpiration(System.currentTimeMillis() + 1000);

         producer.send(message);
      }
      session.commit();

      // this context is validating if these messages are routed correctly
      {
         int count1 = 0;
         ClientMessage message = null;
         while ((message = consumer1.receiveImmediate()) != null)
         {
            message.acknowledge();
            count1++;
         }

         int count2 = 0;
         message = null;
         while ((message = consumer2.receiveImmediate()) != null)
         {
            message.acknowledge();
            count2++;
         }

         assertEquals(1, count1);
         assertEquals(1, count2);
         session.rollback();
      }
      Thread.sleep(2000);

      // it must been expired by now
      assertNull(consumer1.receiveImmediate());
      // it must been expired by now
      assertNull(consumer2.receiveImmediate());

      int countOriginal1 = 0;
      int countOriginal2 = 0;
      ClientConsumer consumerExpiry = session.createConsumer(expiryAddress);

      for (int i = 0; i < numMessages * 2; i++)
      {
         ClientMessage message = consumerExpiry.receive(5000);
         System.out.println("Received message " + message);
         assertNotNull(message);

         if (message.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE).equals("queue1"))
         {
            countOriginal1++;
         }
         else if (message.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE).equals("queue2"))
         {
            countOriginal2++;
         }
         else
         {
            System.out.println("message not part of any expired queue" + message);
         }
      }

      assertEquals(numMessages, countOriginal1);
      assertEquals(numMessages, countOriginal2);
   }

   @Test
   public void testSingleNonExclusiveDivert2() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("divert1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress), queueName1, null, false);

      session.createQueue(new SimpleString(testAddress), queueName2, null, false);

      session.createQueue(new SimpleString(testAddress), queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testSingleNonExclusiveDivert3() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("divert1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      session.createQueue(new SimpleString(forwardAddress), queueName1, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());
   }

   @Test
   public void testSingleExclusiveDivert() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("divert1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress)
         .setExclusive(true);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress), queueName1, null, false);

      session.createQueue(new SimpleString(testAddress), queueName2, null, false);
      session.createQueue(new SimpleString(testAddress), queueName3, null, false);
      session.createQueue(new SimpleString(testAddress), queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      Assert.assertNull(consumer2.receiveImmediate());

      Assert.assertNull(consumer3.receiveImmediate());

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testMultipleNonExclusiveDivert() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("divert1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress1);

      DivertConfiguration divertConf2 = new DivertConfiguration()
         .setName("divert2")
         .setRoutingName("divert2")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress2);

      DivertConfiguration divertConf3 = new DivertConfiguration()
         .setName("divert3")
         .setRoutingName("divert3")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf1)
              .addDivertConfiguration(divertConf2)
              .addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testMultipleExclusiveDivert() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("divert1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress1)
         .setExclusive(true);

      DivertConfiguration divertConf2 = new DivertConfiguration()
         .setName("divert2")
         .setRoutingName("divert2")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress2)
         .setExclusive(true);

      DivertConfiguration divertConf3 = new DivertConfiguration()
         .setName("divert3")
         .setRoutingName("divert3")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress3)
         .setExclusive(true);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf1)
              .addDivertConfiguration(divertConf2)
              .addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testMixExclusiveAndNonExclusiveDiverts() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("divert1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress1)
         .setExclusive(true);

      DivertConfiguration divertConf2 = new DivertConfiguration()
         .setName("divert2")
         .setRoutingName("divert2")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress2)
         .setExclusive(true);

      DivertConfiguration divertConf3 = new DivertConfiguration()
         .setName("divert3")
         .setRoutingName("divert3")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf1)
              .addDivertConfiguration(divertConf2)
              .addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      Assert.assertNull(consumer3.receiveImmediate());

      Assert.assertNull(consumer4.receiveImmediate());
   }

   // If no exclusive diverts match then non exclusive ones should be called
   @Test
   public void testSingleExclusiveNonMatchingAndNonExclusiveDiverts() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      final String filter = "animal='antelope'";

      DivertConfiguration divertConf1 = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("divert1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress1)
         .setExclusive(true)
         .setFilterString(filter);

      DivertConfiguration divertConf2 = new DivertConfiguration()
         .setName("divert2")
         .setRoutingName("divert2")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress2);

      DivertConfiguration divertConf3 = new DivertConfiguration()
         .setName("divert3")
         .setRoutingName("divert3")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf1)
              .addDivertConfiguration(divertConf2)
              .addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putStringProperty(new SimpleString("animal"), new SimpleString("giraffe"));

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      // for (int i = 0; i < numMessages; i++)
      // {
      // ClientMessage message = consumer1.receive(200);
      //
      // assertNotNull(message);
      //
      // assertEquals((Integer)i, (Integer)message.getProperty(propKey));
      //
      // message.acknowledge();
      // }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putStringProperty(new SimpleString("animal"), new SimpleString("antelope"));

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      Assert.assertNull(consumer2.receiveImmediate());

      Assert.assertNull(consumer3.receiveImmediate());

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testRoundRobinDiverts() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("thename")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress1);

      DivertConfiguration divertConf2 = new DivertConfiguration()
         .setName("divert2")
         .setRoutingName("thename")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress2);

      DivertConfiguration divertConf3 = new DivertConfiguration()
         .setName("divert3")
         .setRoutingName("thename")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf1)
              .addDivertConfiguration(divertConf2)
              .addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; )
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();

         i++;

         if (i == numMessages)
         {
            break;
         }

         message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();

         i++;

         if (i == numMessages)
         {
            break;
         }

         message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();

         i++;
      }

      Assert.assertNull(consumer1.receiveImmediate());
      Assert.assertNull(consumer2.receiveImmediate());
      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testDeployDivertsSameUniqueName() throws Exception
   {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("thename1")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress1);

      DivertConfiguration divertConf2 = new DivertConfiguration()
         .setName("divert1")
         .setRoutingName("thename2")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress2);

      DivertConfiguration divertConf3 = new DivertConfiguration()
         .setName("divert2")
         .setRoutingName("thename3")
         .setAddress(testAddress)
         .setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig()
              .addDivertConfiguration(divertConf1)
              .addDivertConfiguration(divertConf2)
              .addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      // Only the first and third should be deployed

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++)
      {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testInjectedTransformer() throws Exception
   {
      final SimpleString ADDRESS = new SimpleString("myAddress");
      final String DIVERT = "myDivert";

      ServiceRegistryImpl serviceRegistry = new ServiceRegistryImpl();
      Transformer transformer = new Transformer()
      {
         @Override
         public ServerMessage transform(ServerMessage message)
         {
            return null;
         }
      };
      serviceRegistry.addDivertTransformer(DIVERT, transformer);

      ActiveMQServer server = addServer(new ActiveMQServerImpl(null, null, null, null, serviceRegistry));
      server.start();
      server.waitForActivation(100, TimeUnit.MILLISECONDS);
      server.deployQueue(ADDRESS, SimpleString.toSimpleString("myQueue"), null, false, false);
      server.deployDivert(new DivertConfiguration()
                                  .setName(DIVERT)
                                  .setAddress(ADDRESS.toString())
                                  .setForwardingAddress(ADDRESS.toString()));
      Collection<Binding> bindings = server.getPostOffice().getBindingsForAddress(ADDRESS).getBindings();
      Divert divert = null;
      for (Binding binding : bindings)
      {
         if (binding instanceof DivertBinding)
         {
            divert = ((DivertBinding)binding).getDivert();
         }
      }
      assertNotNull(divert);
      assertEquals(transformer, divert.getTransformer());
   }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace Library
{
    public class PortScannerInputParser
    {
        private int portTimeoutTreshold = 10;
        public int PortTimeoutTreshold { get { return portTimeoutTreshold; } private set { portTimeoutTreshold = value; } }
        public int PortStart { get; private set; }
        public int PortEnd { get; private set; }
        public string IPAddressString { get; private set; }
        public IPAddress IPAddress { get; private set; }
        public EPortType PortType { get; private set; }

        private string[] data = null;

        public PortScannerInputParser(string input)
        {
            ParseIPAddress("127.0.0.1");
            PortType = EPortType.TCP;
            data = !string.IsNullOrEmpty(input) ? Regex.Replace(input, @"\s+", "").Split(';') : null;
            Parse();
        }

        /*
         * 80
         * 80-1024
         * 80;192.168.100.10
         * 80-1024;192.168.100.10
         * 80;192.168.100.10;TCP
         * 80-1024;192.168.100.10;UDP
         * 80;192.168.100.10;TCP;10
         * 80-1024;192.168.100.10;UDP;100
         */
        void Parse()
        {
            if (data == null)
                return;

            if (data.Length >= 1)
            {
                ParsePorts(data[0]);
            }
            if (data.Length >= 2)
            {
                ParseIPAddress(data[1]);
            }
            if (data.Length >= 3)
            {
                PortType = data[2].ToLower().Equals("tcp") ? EPortType.TCP : EPortType.UDP;
            }
            if (data.Length >= 4)
            {
                ParseTimeoutTreshold(data[3]);
            }
        }

        void ParseIPAddress(string input)
        {
            if (NetUtility.isValidUrl(input) || NetUtility.IsValidIP(input))
            {
                IPAddressString = NetUtility.HostToIp(input).ToString();
                IPAddress = IPAddress.Parse(IPAddressString);
            }
        }

        void ParsePorts(string input)
        {
            var ports = input.Split('-');
            if (ports.Length == 1)
            {
                int portStart = 80;
                if (int.TryParse(ports[0], out portStart))
                {
                    PortStart = portStart;
                }
                PortEnd = PortStart;
            }
            else if (ports.Length == 2)
            {
                int portStart = 80;
                if (int.TryParse(ports[0], out portStart))
                {
                    PortStart = portStart;
                }
                int portEnd = 80;
                if (int.TryParse(ports[1], out portEnd))
                {
                    PortEnd = portEnd;
                }
            }
            //var portMax = (int)Math.Pow(8, 2) * 1024 - 1;
            //Check wether if the specified minPort and maxPort are within the bounds of available ports.
            PortStart = PortStart >= IPEndPoint.MinPort && PortStart <= IPEndPoint.MaxPort ? PortStart : 80;
            PortEnd = PortEnd >= IPEndPoint.MinPort && PortEnd <= IPEndPoint.MaxPort ? PortEnd : 80;
            PortEnd = PortEnd >= PortStart ? PortEnd : PortStart;
        }

        void ParseTimeoutTreshold(string input)
        {
            int.TryParse(input, out portTimeoutTreshold);
            PortTimeoutTreshold = portTimeoutTreshold > 1 ? portTimeoutTreshold : 10;
        }
    }
}


text:
package com.adms.mglplanreport.service.planlv.factory;

import com.adms.mglplanreport.service.planlv.PlanLevelGenerator;
import com.adms.mglplanreport.service.planlv.impl.FWDTVDPlanLvGenImpl;
import com.adms.mglplanreport.service.planlv.impl.MSIGBrokerPlanLvGenImpl;
import com.adms.mglplanreport.service.planlv.impl.MSIGUOBPlanLvGenImpl;
import com.adms.mglplanreport.service.planlv.impl.MTIKBankPlanLvGenImpl;
import com.adms.mglplanreport.service.planlv.impl.MTLBrokerPlanLvGenImpl;
import com.adms.mglplanreport.service.planlv.impl.MTLKbankPlanLvGenImpl;

public class PlanLevelGeneratorFactory {

	public static PlanLevelGenerator getGenerator(String campaign) throws Exception {

		if(campaign.toUpperCase().contains("MTLIFE KBANK")) {
			return new MTLKbankPlanLvGenImpl();

		} else if(campaign.toUpperCase().contains("MTLIFE BROKER")
				|| campaign.contains("V-Club")) {
			return new MTLBrokerPlanLvGenImpl();

		} else if(campaign.toUpperCase().contains("MSIG BROKER")) {
			return new MSIGBrokerPlanLvGenImpl();

		} else if(campaign.toUpperCase().contains("MTI KBANK")) {
			return new MTIKBankPlanLvGenImpl();

		} else if(campaign.toUpperCase().contains("MSIG UOB")) {
			return new MSIGUOBPlanLvGenImpl();

		} else if(campaign.toUpperCase().contains("FWD TVD")) {
			return new FWDTVDPlanLvGenImpl();

		} else {
			throw new Exception("Class for: \"" + campaign + "\" not found");
		}

	}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Antonie van Leeuwenhoek 6: 36 (1940)

#### Original name
Verticillium albo-atrum var. medium Wollenw., 1929

### Remarks
null


text:
class NonRecursiveBenaphore
{
private:
    std::atomic<int> m_contentionCount;
    DefaultSemaphoreType m_sema;

public:
    NonRecursiveBenaphore() : m_contentionCount(0) {}

    void lock()
    {
        if (m_contentionCount.fetch_add(1, std::memory_order_acquire) > 0)
        {
            m_sema.wait();
        }
    }

    bool tryLock()
    {
        if (m_contentionCount.load(std::memory_order_relaxed) != 0)
            return false;
        int expected = 0;
        return m_contentionCount.compare_exchange_strong(expected, 1, std::memory_order_acquire);
    }

    void unlock()
    {
        int oldCount = m_contentionCount.fetch_sub(1, std::memory_order_release);
        assert(oldCount > 0);
        if (oldCount > 1)
        {
            m_sema.signal();
        }
    }
};

//---------------------------------------------------------
// RecursiveBenaphore
//---------------------------------------------------------
class RecursiveBenaphore
{
private:
    std::atomic<int> m_contentionCount;
    std::atomic<int> m_owner;
    int m_recursion;
    DefaultSemaphoreType m_sema;

public:
    RecursiveBenaphore()
    : m_contentionCount(0)
    , m_recursion(0)
    {
        m_owner = ::dsn::utils::get_invalid_tid();
    }

    void lock()
    {
        auto tid = ::dsn::utils::get_current_tid();
        if (m_contentionCount.fetch_add(1, std::memory_order_acquire) > 0)
        {
            if (tid != m_owner.load(std::memory_order_relaxed))
                m_sema.wait();
        }
        //--- We are now inside the lock ---
        m_owner.store(tid, std::memory_order_relaxed);
        m_recursion++;
    }

    bool tryLock()
    {
        auto tid = ::dsn::utils::get_current_tid();
        if (m_owner.load(std::memory_order_relaxed) == tid)
        {
            // Already inside the lock
            m_contentionCount.fetch_add(1, std::memory_order_relaxed);
        }
        else
        {
            if (m_contentionCount.load(std::memory_order_relaxed) != 0)
                return false;
            int expected = 0;
            if (!m_contentionCount.compare_exchange_strong(expected, 1, std::memory_order_acquire))
                return false;
            //--- We are now inside the lock ---
            m_owner.store(tid, std::memory_order_relaxed);
        }
        m_recursion++;
        return true;
    }

    void unlock()
    {
#ifndef NDEBUG
        auto tid = ::dsn::utils::get_current_tid();
        assert(tid == m_owner.load(std::memory_order_relaxed));
#endif
        int recur = --m_recursion;
        if (recur == 0)
            m_owner.store(::dsn::utils::get_invalid_tid(), std::memory_order_relaxed);
        if (m_contentionCount.fetch_sub(1, std::memory_order_release) > 1)
        {
            if (recur == 0)
                m_sema.signal();
        }
        //--- We are now outside the lock ---
    }
};

#endif // __CPP11OM_BENAPHORE_H__