text:
"""
The definition of PyMeta's language is itself a PyMeta grammar, but something
has to be able to read that. Most of the code in this module is generated from
that grammar (in future versions, it will hopefully all be generated).
"""
import string
from pymeta.runtime import OMetaBase, ParseError, EOFError, expected

class BootOMetaGrammar(OMetaBase):
    """
    The bootstrap grammar, generated from L{pymeta.grammar.OMetaGrammar} via
    L{pymeta.builder.PythonBuilder}.
    """
    globals = globals()

    def __init__(self, input):
        OMetaBase.__init__(self, input)
        self._ruleNames = []

    def parseGrammar(self, name, builder, *args):
        """
        Entry point for converting a grammar to code (of some variety).

        @param name: The name for this grammar.

        @param builder: A class that implements the grammar-building interface
        (interface to be explicitly defined later)
        """
        self.builder = builder(name, self, *args)
        res, err = self.apply("grammar")
        try:
            x = self.input.head()
        except EOFError:
            pass
        else:
            raise err
        return res

    def applicationArgs(self):
        args = []
        while True:
            try:
                (arg, endchar), err = self.pythonExpr(" >")
                if not arg:
                    break
                args.append(self.builder.expr(arg))
                if endchar == '>':
                    break
            except ParseError:
                break
        if args:
            return args
        else:
            raise ParseError(self.input.position, expected("python expression"))

    def ruleValueExpr(self):
        (expr, endchar), err = self.pythonExpr(endChars="\r\n)]")
        if str(endchar) in ")]":
            self.input = self.input.prev()
        return self.builder.expr(expr)

    def semanticActionExpr(self):
        return self.builder.action(self.pythonExpr(')')[0][0])

    def semanticPredicateExpr(self):
        expr = self.builder.expr(self.pythonExpr(')')[0][0])
        return self.builder.pred(expr)

    def eatWhitespace(self):
        """
        Consume input until a non-whitespace character is reached.
        """
        consumingComment = False
        e = None
        while True:
            try:
                c, e = self.input.head()
            except EOFError:
                break
            t = self.input.tail()
            if c.isspace() or consumingComment:
                self.input = t
                if c == '\n':
                    consumingComment = False
            elif c == '#':
                consumingComment = True
            else:
                break
        return True, e
    rule_spaces = eatWhitespace

    def rule_number(self):
        _locals = {'self': self}
        self.locals['number'] = _locals
        _G_apply_1, lastError = self._apply(self.rule_spaces, "spaces", [])
        self.considerError(lastError)
        def _G_or_2():
            _G_exactly_1, lastError = self.exactly('-')
            self.considerError(lastError)
            _G_apply_2, lastError = self._apply(self.rule_barenumber, "barenumber", [])
            self.considerError(lastError)
            _locals['x'] = _G_apply_2
            _G_python_3, lastError = eval('self.builder.exactly(-x)', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_3, self.currentError)
        def _G_or_3():
            _G_apply_1, lastError = self._apply(self.rule_barenumber, "barenumber", [])
            self.considerError(lastError)
            _locals['x'] = _G_apply_1
            _G_python_2, lastError = eval('self.builder.exactly(x)', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_2, self.currentError)
        _G_or_4, lastError = self._or([_G_or_2, _G_or_3])
        self.considerError(lastError)
        return (_G_or_4, self.currentError)

    def rule_barenumber(self):
        _locals = {'self': self}
        self.locals['barenumber'] = _locals
        def _G_or_1():
            _G_exactly_1, lastError = self.exactly('0')
            self.considerError(lastError)
            def _G_or_2():
                def _G_or_1():
                    _G_exactly_1, lastError = self.exactly('x')
                    self.considerError(lastError)
                    return (_G_exactly_1, self.currentError)
                def _G_or_2():
                    _G_exactly_1, lastError = self.exactly('X')
                    self.considerError(lastError)
                    return (_G_exactly_1, self.currentError)
                _G_or_3, lastError = self._or([_G_or_1, _G_or_2])
                self.considerError(lastError)
                def _G_many_4():
                    _G_apply_1, lastError = self._apply(self.rule_hexdigit, "hexdigit", [])
                    self.considerError(lastError)
                    return (_G_apply_1, self.currentError)
                _G_many_5, lastError = self.many(_G_many_4)
                self.considerError(lastError)
                _locals['hs'] = _G_many_5
                _G_python_6, lastError = eval("int(''.join(hs), 16)", self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_6, self.currentError)
            def _G_or_3():
                def _G_many_1():
                    _G_apply_1, lastError = self._apply(self.rule_octaldigit, "octaldigit", [])
                    self.considerError(lastError)
                    return (_G_apply_1, self.currentError)
                _G_many_2, lastError = self.many(_G_many_1)
                self.considerError(lastError)
                _locals['ds'] = _G_many_2
                _G_python_3, lastError = eval("int('0'+''.join(ds), 8)", self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_3, self.currentError)
            _G_or_4, lastError = self._or([_G_or_2, _G_or_3])
            self.considerError(lastError)
            return (_G_or_4, self.currentError)
        def _G_or_2():
            def _G_many1_1():
                _G_apply_1, lastError = self._apply(self.rule_digit, "digit", [])
                self.considerError(lastError)
                return (_G_apply_1, self.currentError)
            _G_many1_2, lastError = self.many(_G_many1_1, _G_many1_1())
            self.considerError(lastError)
            _locals['ds'] = _G_many1_2
            _G_python_3, lastError = eval("int(''.join(ds))", self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_3, self.currentError)
        _G_or_3, lastError = self._or([_G_or_1, _G_or_2])
        self.considerError(lastError)
        return (_G_or_3, self.currentError)

    def rule_octaldigit(self):
        _locals = {'self': self}
        self.locals['octaldigit'] = _locals
        _G_apply_1, lastError = self._apply(self.rule_anything, "anything", [])
        self.considerError(lastError)
        _locals['x'] = _G_apply_1
        def _G_pred_2():
            _G_python_1, lastError = eval('x in string.octdigits', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_1, self.currentError)
        _G_pred_3, lastError = self.pred(_G_pred_2)
        self.considerError(lastError)
        _G_python_4, lastError = eval('x', self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_4, self.currentError)

    def rule_hexdigit(self):
        _locals = {'self': self}
        self.locals['hexdigit'] = _locals
        _G_apply_1, lastError = self._apply(self.rule_anything, "anything", [])
        self.considerError(lastError)
        _locals['x'] = _G_apply_1
        def _G_pred_2():
            _G_python_1, lastError = eval('x in string.hexdigits', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_1, self.currentError)
        _G_pred_3, lastError = self.pred(_G_pred_2)
        self.considerError(lastError)
        _G_python_4, lastError = eval('x', self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_4, self.currentError)

    def rule_escapedChar(self):
        _locals = {'self': self}
        self.locals['escapedChar'] = _locals
        _G_exactly_1, lastError = self.exactly('\\')
        self.considerError(lastError)
        def _G_or_2():
            _G_exactly_1, lastError = self.exactly('n')
            self.considerError(lastError)
            _G_python_2, lastError = eval('"\\n"', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_2, self.currentError)
        def _G_or_3():
            _G_exactly_1, lastError = self.exactly('r')
            self.considerError(lastError)
            _G_python_2, lastError = eval('"\\r"', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_2, self.currentError)
        def _G_or_4():
            _G_exactly_1, lastError = self.exactly('t')
            self.considerError(lastError)
            _G_python_2, lastError = eval('"\\t"', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_2, self.currentError)
        def _G_or_5():
            _G_exactly_1, lastError = self.exactly('b')
            self.considerError(lastError)
            _G_python_2, lastError = eval('"\\b"', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_2, self.currentError)
        def _G_or_6():
            _G_exactly_1, lastError = self.exactly('f')
            self.considerError(lastError)
            _G_python_2, lastError = eval('"\\f"', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_2, self.currentError)
        def _G_or_7():
            _G_exactly_1, lastError = self.exactly('"')
            self.considerError(lastError)
            _G_python_2, lastError = eval('\'"\'', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_2, self.currentError)
        def _G_or_8():
            _G_exactly_1, lastError = self.exactly("'")
            self.considerError(lastError)
            _G_python_2, lastError = eval('"\'"', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_2, self.currentError)
        def _G_or_9():
            _G_exactly_1, lastError = self.exactly('\\')
            self.considerError(lastError)
            _G_python_2, lastError = eval('"\\\\"', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_2, self.currentError)
        _G_or_10, lastError = self._or([_G_or_2, _G_or_3, _G_or_4, _G_or_5, _G_or_6, _G_or_7, _G_or_8, _G_or_9])
        self.considerError(lastError)
        return (_G_or_10, self.currentError)

    def rule_character(self):
        _locals = {'self': self}
        self.locals['character'] = _locals
        _G_python_1, lastError = eval('"\'"', self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
        self.considerError(lastError)
        def _G_or_3():
            _G_apply_1, lastError = self._apply(self.rule_escapedChar, "escapedChar", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        def _G_or_4():
            _G_apply_1, lastError = self._apply(self.rule_anything, "anything", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        _G_or_5, lastError = self._or([_G_or_3, _G_or_4])
        self.considerError(lastError)
        _locals['c'] = _G_or_5
        _G_python_6, lastError = eval('"\'"', self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_7, lastError = self._apply(self.rule_token, "token", [_G_python_6])
        self.considerError(lastError)
        _G_python_8, lastError = eval('self.builder.exactly(c)', self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_8, self.currentError)

    def rule_string(self):
        _locals = {'self': self}
        self.locals['string'] = _locals
        _G_python_1, lastError = eval('\'"\'', self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
        self.considerError(lastError)
        def _G_many_3():
            def _G_or_1():
                _G_apply_1, lastError = self._apply(self.rule_escapedChar, "escapedChar", [])
                self.considerError(lastError)
                return (_G_apply_1, self.currentError)
            def _G_or_2():
                def _G_not_1():
                    _G_exactly_1, lastError = self.exactly('"')
                    self.considerError(lastError)
                    return (_G_exactly_1, self.currentError)
                _G_not_2, lastError = self._not(_G_not_1)
                self.considerError(lastError)
                _G_apply_3, lastError = self._apply(self.rule_anything, "anything", [])
                self.considerError(lastError)
                return (_G_apply_3, self.currentError)
            _G_or_3, lastError = self._or([_G_or_1, _G_or_2])
            self.considerError(lastError)
            return (_G_or_3, self.currentError)
        _G_many_4, lastError = self.many(_G_many_3)
        self.considerError(lastError)
        _locals['c'] = _G_many_4
        _G_python_5, lastError = eval('\'"\'', self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_6, lastError = self._apply(self.rule_token, "token", [_G_python_5])
        self.considerError(lastError)
        _G_python_7, lastError = eval("self.builder.exactly(''.join(c))", self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_7, self.currentError)

    def rule_name(self):
        _locals = {'self': self}
        self.locals['name'] = _locals
        _G_apply_1, lastError = self._apply(self.rule_letter, "letter", [])
        self.considerError(lastError)
        _locals['x'] = _G_apply_1
        def _G_many_2():
            _G_apply_1, lastError = self._apply(self.rule_letterOrDigit, "letterOrDigit", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        _G_many_3, lastError = self.many(_G_many_2)
        self.considerError(lastError)
        _locals['xs'] = _G_many_3
        _G_python_4, lastError = eval('xs.insert(0, x)', self.globals, _locals), None
        self.considerError(lastError)
        _G_python_5, lastError = eval("''.join(xs)", self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_5, self.currentError)

    def rule_application(self):
        _locals = {'self': self}
        self.locals['application'] = _locals
        _G_python_1, lastError = eval("'<'", self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
        self.considerError(lastError)
        _G_apply_3, lastError = self._apply(self.rule_spaces, "spaces", [])
        self.considerError(lastError)
        _G_apply_4, lastError = self._apply(self.rule_name, "name", [])
        self.considerError(lastError)
        _locals['name'] = _G_apply_4
        def _G_or_5():
            _G_exactly_1, lastError = self.exactly(' ')
            self.considerError(lastError)
            _G_python_2, lastError = eval('self.applicationArgs()', self.globals, _locals), None
            self.considerError(lastError)
            _locals['args'] = _G_python_2
            _G_python_3, lastError = eval('self.builder.apply(name, self.name, *args)', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_3, self.currentError)
        def _G_or_6():
            _G_python_1, lastError = eval("'>'", self.globals, _locals), None
            self.considerError(lastError)
            _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
            self.considerError(lastError)
            _G_python_3, lastError = eval('self.builder.apply(name, self.name)', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_3, self.currentError)
        _G_or_7, lastError = self._or([_G_or_5, _G_or_6])
        self.considerError(lastError)
        return (_G_or_7, self.currentError)

    def rule_expr1(self):
        _locals = {'self': self}
        self.locals['expr1'] = _locals
        def _G_or_1():
            _G_apply_1, lastError = self._apply(self.rule_application, "application", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        def _G_or_2():
            _G_apply_1, lastError = self._apply(self.rule_ruleValue, "ruleValue", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        def _G_or_3():
            _G_apply_1, lastError = self._apply(self.rule_semanticPredicate, "semanticPredicate", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        def _G_or_4():
            _G_apply_1, lastError = self._apply(self.rule_semanticAction, "semanticAction", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        def _G_or_5():
            _G_apply_1, lastError = self._apply(self.rule_number, "number", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        def _G_or_6():
            _G_apply_1, lastError = self._apply(self.rule_character, "character", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        def _G_or_7():
            _G_apply_1, lastError = self._apply(self.rule_string, "string", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        def _G_or_8():
            _G_python_1, lastError = eval("'('", self.globals, _locals), None
            self.considerError(lastError)
            _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
            self.considerError(lastError)
            _G_apply_3, lastError = self._apply(self.rule_expr, "expr", [])
            self.considerError(lastError)
            _locals['e'] = _G_apply_3
            _G_python_4, lastError = eval("')'", self.globals, _locals), None
            self.considerError(lastError)
            _G_apply_5, lastError = self._apply(self.rule_token, "token", [_G_python_4])
            self.considerError(lastError)
            _G_python_6, lastError = eval('e', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_6, self.currentError)
        def _G_or_9():
            _G_python_1, lastError = eval("'['", self.globals, _locals), None
            self.considerError(lastError)
            _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
            self.considerError(lastError)
            _G_apply_3, lastError = self._apply(self.rule_expr, "expr", [])
            self.considerError(lastError)
            _locals['e'] = _G_apply_3
            _G_python_4, lastError = eval("']'", self.globals, _locals), None
            self.considerError(lastError)
            _G_apply_5, lastError = self._apply(self.rule_token, "token", [_G_python_4])
            self.considerError(lastError)
            _G_python_6, lastError = eval('self.builder.listpattern(e)', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_6, self.currentError)
        _G_or_10, lastError = self._or([_G_or_1, _G_or_2, _G_or_3, _G_or_4, _G_or_5, _G_or_6, _G_or_7, _G_or_8, _G_or_9])
        self.considerError(lastError)
        return (_G_or_10, self.currentError)

    def rule_expr2(self):
        _locals = {'self': self}
        self.locals['expr2'] = _locals
        def _G_or_1():
            _G_python_1, lastError = eval("'~'", self.globals, _locals), None
            self.considerError(lastError)
            _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
            self.considerError(lastError)
            def _G_or_3():
                _G_python_1, lastError = eval("'~'", self.globals, _locals), None
                self.considerError(lastError)
                _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
                self.considerError(lastError)
                _G_apply_3, lastError = self._apply(self.rule_expr2, "expr2", [])
                self.considerError(lastError)
                _locals['e'] = _G_apply_3
                _G_python_4, lastError = eval('self.builder.lookahead(e)', self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_4, self.currentError)
            def _G_or_4():
                _G_apply_1, lastError = self._apply(self.rule_expr2, "expr2", [])
                self.considerError(lastError)
                _locals['e'] = _G_apply_1
                _G_python_2, lastError = eval('self.builder._not(e)', self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_2, self.currentError)
            _G_or_5, lastError = self._or([_G_or_3, _G_or_4])
            self.considerError(lastError)
            return (_G_or_5, self.currentError)
        def _G_or_2():
            _G_apply_1, lastError = self._apply(self.rule_expr1, "expr1", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        _G_or_3, lastError = self._or([_G_or_1, _G_or_2])
        self.considerError(lastError)
        return (_G_or_3, self.currentError)

    def rule_expr3(self):
        _locals = {'self': self}
        self.locals['expr3'] = _locals
        def _G_or_1():
            _G_apply_1, lastError = self._apply(self.rule_expr2, "expr2", [])
            self.considerError(lastError)
            _locals['e'] = _G_apply_1
            def _G_or_2():
                _G_exactly_1, lastError = self.exactly('*')
                self.considerError(lastError)
                _G_python_2, lastError = eval('self.builder.many(e)', self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_2, self.currentError)
            def _G_or_3():
                _G_exactly_1, lastError = self.exactly('+')
                self.considerError(lastError)
                _G_python_2, lastError = eval('self.builder.many1(e)', self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_2, self.currentError)
            def _G_or_4():
                _G_exactly_1, lastError = self.exactly('?')
                self.considerError(lastError)
                _G_python_2, lastError = eval('self.builder.optional(e)', self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_2, self.currentError)
            def _G_or_5():
                _G_python_1, lastError = eval('e', self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_1, self.currentError)
            _G_or_6, lastError = self._or([_G_or_2, _G_or_3, _G_or_4, _G_or_5])
            self.considerError(lastError)
            _locals['r'] = _G_or_6
            def _G_or_7():
                _G_exactly_1, lastError = self.exactly(':')
                self.considerError(lastError)
                _G_apply_2, lastError = self._apply(self.rule_name, "name", [])
                self.considerError(lastError)
                _locals['n'] = _G_apply_2
                _G_python_3, lastError = eval('self.builder.bind(r, n)', self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_3, self.currentError)
            def _G_or_8():
                _G_python_1, lastError = eval('r', self.globals, _locals), None
                self.considerError(lastError)
                return (_G_python_1, self.currentError)
            _G_or_9, lastError = self._or([_G_or_7, _G_or_8])
            self.considerError(lastError)
            return (_G_or_9, self.currentError)
        def _G_or_2():
            _G_python_1, lastError = eval("':'", self.globals, _locals), None
            self.considerError(lastError)
            _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
            self.considerError(lastError)
            _G_apply_3, lastError = self._apply(self.rule_name, "name", [])
            self.considerError(lastError)
            _locals['n'] = _G_apply_3
            _G_python_4, lastError = eval('self.builder.bind(self.builder.apply("anything", self.name), n)', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_4, self.currentError)
        _G_or_3, lastError = self._or([_G_or_1, _G_or_2])
        self.considerError(lastError)
        return (_G_or_3, self.currentError)

    def rule_expr4(self):
        _locals = {'self': self}
        self.locals['expr4'] = _locals
        def _G_many_1():
            _G_apply_1, lastError = self._apply(self.rule_expr3, "expr3", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        _G_many_2, lastError = self.many(_G_many_1)
        self.considerError(lastError)
        _locals['es'] = _G_many_2
        _G_python_3, lastError = eval('self.builder.sequence(es)', self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_3, self.currentError)

    def rule_expr(self):
        _locals = {'self': self}
        self.locals['expr'] = _locals
        _G_apply_1, lastError = self._apply(self.rule_expr4, "expr4", [])
        self.considerError(lastError)
        _locals['e'] = _G_apply_1
        def _G_many_2():
            _G_python_1, lastError = eval("'|'", self.globals, _locals), None
            self.considerError(lastError)
            _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
            self.considerError(lastError)
            _G_apply_3, lastError = self._apply(self.rule_expr4, "expr4", [])
            self.considerError(lastError)
            return (_G_apply_3, self.currentError)
        _G_many_3, lastError = self.many(_G_many_2)
        self.considerError(lastError)
        _locals['es'] = _G_many_3
        _G_python_4, lastError = eval('es.insert(0, e)', self.globals, _locals), None
        self.considerError(lastError)
        _G_python_5, lastError = eval('self.builder._or(es)', self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_5, self.currentError)

    def rule_ruleValue(self):
        _locals = {'self': self}
        self.locals['ruleValue'] = _locals
        _G_python_1, lastError = eval('"=>"', self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
        self.considerError(lastError)
        _G_python_3, lastError = eval('self.ruleValueExpr()', self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_3, self.currentError)

    def rule_semanticPredicate(self):
        _locals = {'self': self}
        self.locals['semanticPredicate'] = _locals
        _G_python_1, lastError = eval('"?("', self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
        self.considerError(lastError)
        _G_python_3, lastError = eval('self.semanticPredicateExpr()', self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_3, self.currentError)

    def rule_semanticAction(self):
        _locals = {'self': self}
        self.locals['semanticAction'] = _locals
        _G_python_1, lastError = eval('"!("', self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
        self.considerError(lastError)
        _G_python_3, lastError = eval('self.semanticActionExpr()', self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_3, self.currentError)

    def rule_rulePart(self):
        _locals = {'self': self}
        self.locals['rulePart'] = _locals
        _G_apply_1, lastError = self._apply(self.rule_anything, "anything", [])
        self.considerError(lastError)
        _locals['requiredName'] = _G_apply_1
        _G_apply_2, lastError = self._apply(self.rule_spaces, "spaces", [])
        self.considerError(lastError)
        _G_apply_3, lastError = self._apply(self.rule_name, "name", [])
        self.considerError(lastError)
        _locals['n'] = _G_apply_3
        def _G_pred_4():
            _G_python_1, lastError = eval('n == requiredName', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_1, self.currentError)
        _G_pred_5, lastError = self.pred(_G_pred_4)
        self.considerError(lastError)
        _G_python_6, lastError = eval('setattr(self, "name", n)', self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_7, lastError = self._apply(self.rule_expr4, "expr4", [])
        self.considerError(lastError)
        _locals['args'] = _G_apply_7
        def _G_or_8():
            _G_python_1, lastError = eval('"::="', self.globals, _locals), None
            self.considerError(lastError)
            _G_apply_2, lastError = self._apply(self.rule_token, "token", [_G_python_1])
            self.considerError(lastError)
            _G_apply_3, lastError = self._apply(self.rule_expr, "expr", [])
            self.considerError(lastError)
            _locals['e'] = _G_apply_3
            _G_python_4, lastError = eval('self.builder.sequence([args, e])', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_4, self.currentError)
        def _G_or_9():
            _G_python_1, lastError = eval('args', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_1, self.currentError)
        _G_or_10, lastError = self._or([_G_or_8, _G_or_9])
        self.considerError(lastError)
        return (_G_or_10, self.currentError)

    def rule_rule(self):
        _locals = {'self': self}
        self.locals['rule'] = _locals
        _G_apply_1, lastError = self._apply(self.rule_spaces, "spaces", [])
        self.considerError(lastError)
        def _G_lookahead_2():
            _G_apply_1, lastError = self._apply(self.rule_name, "name", [])
            self.considerError(lastError)
            _locals['n'] = _G_apply_1
            return (_locals['n'], self.currentError)
        _G_lookahead_3, lastError = self.lookahead(_G_lookahead_2)
        self.considerError(lastError)
        _G_python_4, lastError = eval('n', self.globals, _locals), None
        self.considerError(lastError)
        _G_apply_5, lastError = self._apply(self.rule_rulePart, "rulePart", [_G_python_4])
        self.considerError(lastError)
        _locals['r'] = _G_apply_5
        def _G_or_6():
            def _G_many1_1():
                _G_python_1, lastError = eval('n', self.globals, _locals), None
                self.considerError(lastError)
                _G_apply_2, lastError = self._apply(self.rule_rulePart, "rulePart", [_G_python_1])
                self.considerError(lastError)
                return (_G_apply_2, self.currentError)
            _G_many1_2, lastError = self.many(_G_many1_1, _G_many1_1())
            self.considerError(lastError)
            _locals['rs'] = _G_many1_2
            _G_python_3, lastError = eval('self.builder.rule(n, self.builder._or([r] + rs))', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_3, self.currentError)
        def _G_or_7():
            _G_python_1, lastError = eval('self.builder.rule(n, r)', self.globals, _locals), None
            self.considerError(lastError)
            return (_G_python_1, self.currentError)
        _G_or_8, lastError = self._or([_G_or_6, _G_or_7])
        self.considerError(lastError)
        return (_G_or_8, self.currentError)

    def rule_grammar(self):
        _locals = {'self': self}
        self.locals['grammar'] = _locals
        def _G_many_1():
            _G_apply_1, lastError = self._apply(self.rule_rule, "rule", [])
            self.considerError(lastError)
            return (_G_apply_1, self.currentError)
        _G_many_2, lastError = self.many(_G_many_1)
        self.considerError(lastError)
        _locals['rs'] = _G_many_2
        _G_apply_3, lastError = self._apply(self.rule_spaces, "spaces", [])
        self.considerError(lastError)
        _G_python_4, lastError = eval('self.builder.makeGrammar(rs)', self.globals, _locals), None
        self.considerError(lastError)
        return (_G_python_4, self.currentError)


text:
/**
 * Created by Administrator on 2017/6/29.
 */
const chalk = require('chalk');
const log = console.log;

// Modifiers
log(chalk.reset('reset'));
log(chalk.bold('bold'));
log(chalk.dim('dim'));
log(chalk.italic('italic'));
log(chalk.underline('underline'));
log(chalk.inverse('inverse'));
log(chalk.hidden('hidden'));
log(chalk.strikethrough('strikethrough'));

// Colors
log(chalk.black('black'));
log(chalk.red('red'));
log(chalk.green('green'));
log(chalk.yellow('yellow'));
log(chalk.blue('blue'));
log(chalk.magenta('magenta'));
log(chalk.cyan('cyan'));
log(chalk.white('white'));
log(chalk.gray('gray'));

// Background colors
log(chalk.bgBlack('bgBlack'));
log(chalk.bgRed('bgRed'));
log(chalk.bgGreen('bgGreen'));
log(chalk.bgYellow('bgYellow'));
log(chalk.bgBlue('bgBlue'));
log(chalk.bgMagenta('bgMagenta'));
log(chalk.bgCyan('bgCyan'));
log(chalk.bgWhite('bgWhite'));

//  Multiple styles
log(chalk.green.underline.bold('Hello world!'));
log(chalk.yellow.bgRed.bold('Hello world!'));

redpajama_set_name: RedPajamaGithub


text:
using System.Text.RegularExpressions;
using Thrinax.Enums;

namespace Thrinax.Utility
{
    public static class LanguageUtility
    {
        public static Language DetectedLanguage(string content)
        {
            if (string.IsNullOrEmpty(content)) return Language.CHINESE;

            string chineseRegex = @"[\u4E00-\u9FFF]+";

            var containChinese = Regex.IsMatch(content, chineseRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase);
            if (containChinese)
            {
                return Language.CHINESE;
            }
            else
            {
                return Language.ENGLISH;
            }
        }
    }
}


text:
package com.twosigma.beakerx;

public class BeakerXCommRepositoryMock extends BeakerXCommRepository {

}


text:
#ifndef _QFUFBV_TACTIC_
#define _QFUFBV_TACTIC_

#include"params.h"
class ast_manager;
class tactic;

tactic * mk_qfufbv_tactic(ast_manager & m, params_ref const & p = params_ref());

#endif


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Cdn.Models
{
    public partial class SupportedOptimizationTypesListResult
    {
        internal static SupportedOptimizationTypesListResult DeserializeSupportedOptimizationTypesListResult(JsonElement element)
        {
            Optional<IReadOnlyList<OptimizationType>> supportedOptimizationTypes = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("supportedOptimizationTypes"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<OptimizationType> array = new List<OptimizationType>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(new OptimizationType(item.GetString()));
                    }
                    supportedOptimizationTypes = array;
                    continue;
                }
            }
            return new SupportedOptimizationTypesListResult(Optional.ToList(supportedOptimizationTypes));
        }
    }
}


text:
myControllerModule.controller('ResourcesGroupController', function(alertService,
$scope, ResourcesGroupFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $filter) {

  //GUI page settings
  $scope.headerStringList = $filter('translate')('RESOURCE_GROUPS_DETAIL');
  $scope.noItemsSystemMsg = $filter('translate')('NO_RESOURCE_GROUPS_SETUP');
  $scope.noItemsSystemIcon = "pficon pficon-replicator";

  //load empty, configuration, etc.,
  $scope.mchelper = mchelper;
  $scope.filteredList=[];

  //data query details
  $scope.currentPage = 1;
  $scope.query = CommonServices.getQuery();
  $scope.queryResponse = {};

  //Get min number
  $scope.getMin = function(item1, item2){
    return CommonServices.getMin(item1, item2);
  };

  //get all Sensors
  $scope.getAllItems = function(){
    ResourcesGroupFactory.getAll($scope.query, function(response) {
      $scope.queryResponse = response;
      $scope.filteredList = $scope.queryResponse.data;
      $scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
    },function(error){
      displayRestError.display(error);
    });
  }

  //Hold all the selected item ids
  $scope.itemIds = [];

  $scope.selectAllItems = function(){
    CommonServices.selectAllItems($scope);
  };

  $scope.selectItem = function(item){
    CommonServices.selectItem($scope, item);
  };

  //On page change
  $scope.pageChanged = function(newPage){
    CommonServices.updatePageChange($scope, newPage);
  };

  //Filter change method
  var filterChange = function (filters) {
    //Reset filter fields and update items
    CommonServices.updateFiltersChange($scope, filters);
  };

  $scope.filterConfig = {
    fields: [
      {
        id: 'name',
        title: $filter('translate')('NAME'),
        placeholder: $filter('translate')('FILTER_BY_NAME'),
        filterType: 'text'
      },
      {
        id: 'description',
        title: $filter('translate')('DESCRIPTION'),
        placeholder: $filter('translate')('FILTER_BY_DESCRIPTION'),
        filterType: 'integer',
      }
    ],
    resultsCount: $scope.filteredList.length,
    appliedFilters: [],
    onFilterChange: filterChange
  };

  //Sort columns
  var sortChange = function (sortId, isAscending) {
    //Reset sort type and update items
    CommonServices.updateSortChange($scope, sortId, isAscending);
  };

  $scope.sortConfig = {
    fields: [
      {
        id: 'name',
        title:  $filter('translate')('NAME'),
        sortType: 'text'
      },{
        id: 'description',
        title:  $filter('translate')('DESCRIPTION'),
        sortType: 'text'
      },{
        id: 'state',
        title:  $filter('translate')('STATUS'),
        sortType: 'text'
      },{
        id: 'stateSince',
        title:  $filter('translate')('STATUS_SINCE'),
        sortType: 'text'
      }
    ],
    onSortChange: sortChange
  };

  //On,Off switch control
  $scope.changeMystate = function(item, state){
    var itemArray = [item.id];
    if(state){
      ResourcesGroupFactory.turnOnIds(itemArray, function(response) {
        alertService.success($filter('translate')('RESOURCE_GROUP_TURNED_ON'));
        //Update display table
        //$scope.getAllItems();
      },function(error){
        displayRestError.display(error);
      });
    }else{
      ResourcesGroupFactory.turnOffIds(itemArray, function(response) {
        alertService.success($filter('translate')('RESOURCE_GROUP_TURNED_OFF'));
        //Update display table
        //$scope.getAllItems();
      },function(error){
        displayRestError.display(error);
      });
    }
  }

  //Edit item
  $scope.edit = function () {
    if($scope.itemIds.length == 1){
      $state.go("resourcesGroupAddEdit", {'id':$scope.itemIds[0]});
    }
  };

  //Turm ON items
  $scope.turnOn = function () {
    if($scope.itemIds.length > 0){
      ResourcesGroupFactory.turnOnIds($scope.itemIds, function(response) {
        alertService.success($filter('translate')('RESOURCE_GROUPS_TURNED_ON'));
        //Update display table
        $scope.getAllItems();
        $scope.itemIds = [];
      },function(error){
        displayRestError.display(error);
      });
    }
  };

  //Turm OFF items
  $scope.turnOff = function () {
    if($scope.itemIds.length > 0){
      ResourcesGroupFactory.turnOffIds($scope.itemIds, function(response) {
        alertService.success($filter('translate')('RESOURCE_GROUPS_TURNED_OFF'));
        //Update display table
        $scope.getAllItems();
        $scope.itemIds = [];
      },function(error){
        displayRestError.display(error);
      });
    }
  };

  //Delete item(s)
  $scope.delete = function (size) {
    var modalInstance = $uibModal.open({
    templateUrl: 'partials/common-html/delete-modal.html',
    controller: 'ControllerDeleteModal',
    size: size,
    resolve: {}
    });

    modalInstance.result.then(function () {
      ResourcesGroupFactory.deleteIds($scope.itemIds, function(response) {
        alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
        //Update display table
        $scope.getAllItems();
        $scope.itemIds = [];
      },function(error){
        displayRestError.display(error);
      });
    }),
    function () {
      //console.log('Modal dismissed at: ' + new Date());
    }
  };

});

//Add Edit item controller
myControllerModule.controller('ResourcesGroupControllerAddEdit', function ($scope, $stateParams, $state, ResourcesGroupFactory,  mchelper, alertService, displayRestError, $filter) {
  //GUI page settings
  $scope.showHeaderUpdate = $stateParams.id;
  $scope.headerStringAdd = $filter('translate')('ADD_RESOURCES_GROUP');
  $scope.headerStringUpdate = $filter('translate')('UPDATE_RESOURCES_GROUP');
  $scope.cancelButtonState = "resourcesGroupList"; //Cancel button state
  $scope.saveProgress = false;
  //$scope.isSettingChange = false;

  $scope.mchelper = mchelper;
  $scope.group = {};
  $scope.id = $stateParams.id;

  if($stateParams.id){
    ResourcesGroupFactory.get({"id":$stateParams.id},function(response) {
        $scope.group = response;
      },function(error){
        displayRestError.display(error);
      });
  }

  $scope.save = function(){
    $scope.saveProgress = true;
    if($stateParams.id){
      ResourcesGroupFactory.update($scope.group,function(response) {
        alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
        $state.go("resourcesGroupList");
      },function(error){
        displayRestError.display(error);
        $scope.saveProgress = false;
      });
    }else{
      ResourcesGroupFactory.create($scope.group,function(response) {
        alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
        $state.go("resourcesGroupList");
      },function(error){
        displayRestError.display(error);
        $scope.saveProgress = false;
      });
    }
  }
});

//ResourcesGroup Map
//------------------------------------------------------------------------------

myControllerModule.controller('ResourcesGroupMapController', function(alertService,
$scope, ResourcesGroupFactory, ResourcesGroupMapFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $stateParams, $filter) {

  //GUI page settings
  $scope.headerStringList = $filter('translate')('RESOURCE_GROUPS_MAPS_DETAIL');
  $scope.noItemsSystemMsg = $filter('translate')('NO_RESOURCE_GROUPS_MAP_SETUP');
  $scope.noItemsSystemIcon = "pficon pficon-replicator";

  //load empty, configuration, etc.,
  $scope.mchelper = mchelper;
  $scope.filteredList=[];

  //data query details
  $scope.currentPage = 1;
  $scope.query = CommonServices.getQuery();
  $scope.queryResponse = {};

  //Get min number
  $scope.getMin = function(item1, item2){
    return CommonServices.getMin(item1, item2);
  };

  //redirect to groups list if id not found
  if(!$stateParams){
    $state.go("resourcesGroupList");
  }

  //always lock with group id
  $scope.query.groupId = $stateParams.id;

  $scope.resourcesGroup = ResourcesGroupFactory.get({"id":$stateParams.id});

  //get all items
  $scope.getAllItems = function(){
    ResourcesGroupMapFactory.getAll($scope.query, function(response) {
      $scope.queryResponse = response;
      $scope.filteredList = $scope.queryResponse.data;
      $scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
    },function(error){
      displayRestError.display(error);
    });
  }

  //Hold all the selected item ids
  $scope.itemIds = [];

  $scope.selectAllItems = function(){
    CommonServices.selectAllItems($scope);
  };

  $scope.selectItem = function(item){
    CommonServices.selectItem($scope, item);
  };

  //On page change
  $scope.pageChanged = function(newPage){
    CommonServices.updatePageChange($scope, newPage);
  };

  //Filter change method
  var filterChange = function (filters) {
    //Reset filter fields and update items
    CommonServices.updateFiltersChange($scope, filters);
  };

  $scope.filterConfig = {
    fields: [
      {
        id: 'resourceType',
        title:  $filter('translate')('RESOURCE_TYPE'),
        placeholder: $filter('translate')('FILTER_BY_RESOURCE_TYPE'),
        filterType: 'text'
      },
      {
        id: 'payloadOn',
        title:  $filter('translate')('PAYLOAD_ON'),
        placeholder: $filter('translate')('FILTER_BY_PAYLOAD_ON'),
        filterType: 'integer',
      },
      {
        id: 'payloadOff',
        title:  $filter('translate')('PAYLOAD_OFF'),
        placeholder: $filter('translate')('FILTER_BY_PAYLOAD_OFF'),
        filterType: 'text',
      }
    ],
    resultsCount: $scope.filteredList.length,
    appliedFilters: [],
    onFilterChange: filterChange
  };

  //Sort columns
  var sortChange = function (sortId, isAscending) {
    //Reset sort type and update items
    CommonServices.updateSortChange($scope, sortId, isAscending);
  };

  $scope.sortConfig = {
    fields: [
      {
        id: 'resourceType',
        title:  $filter('translate')('RESOURCE_TYPE'),
        sortType: 'text'
      },{
        id: 'payloadOn',
        title:  $filter('translate')('PAYLOAD_ON'),
        sortType: 'text'
      },
      {
        id: 'payloadOff',
        title:  $filter('translate')('PAYLOAD_OFF'),
        sortType: 'text'
      }
    ],
    onSortChange: sortChange
  };

  //Edit item
  $scope.edit = function () {
    if($scope.itemIds.length == 1){
      $state.go("resourcesGroupMapAddEdit", {'groupId':$scope.query.groupId, 'id':$scope.itemIds[0]});
    }
  };

  //Delete item(s)
  $scope.delete = function (size) {
    var modalInstance = $uibModal.open({
    templateUrl: 'partials/common-html/delete-modal.html',
    controller: 'ControllerDeleteModal',
    size: size,
    resolve: {}
    });

    modalInstance.result.then(function () {
      ResourcesGroupMapFactory.deleteIds($scope.itemIds, function(response) {
        alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
        //Update display table
        $scope.getAllItems();
        $scope.itemIds = [];
      },function(error){
        displayRestError.display(error);
      });
    }),
    function () {
      //console.log('Modal dismissed at: ' + new Date());
    }
  };

});

//Add Edit item controller
myControllerModule.controller('ResourcesGroupMapControllerAddEdit', function ($scope, $stateParams, $state, TypesFactory, CommonServices, ResourcesGroupMapFactory, mchelper, alertService, displayRestError, $filter) {
  $scope.mchelper = mchelper;
  $scope.groupMap = {};

  if($stateParams.id){
    ResourcesGroupMapFactory.get({"id":$stateParams.id},function(response) {
        $scope.groupMap = response;
        //Update Resources
        $scope.dspResources = $scope.getResources($scope.groupMap.resourceType);
      },function(error){
        displayRestError.display(error);
      });
  }else if($stateParams.groupId){
    $scope.groupMap.resourcesGroup = {};
    $scope.groupMap.resourcesGroup.id = $stateParams.groupId;
  }else{
    $state.go("resourcesGroupList");
  }

  //pre load
  $scope.resourceTypes = TypesFactory.getResourceTypes({"resourceType": "resources group"});

  //Get resources
  $scope.getResources = function(resourceType){
    return CommonServices.getResources(resourceType);
  }

  //GUI page settings
  $scope.showHeaderUpdate = $stateParams.id;
  $scope.headerStringAdd = $filter('translate')('ADD_AN_ENTRY');
  $scope.headerStringUpdate = $filter('translate')('UPDATE_AN_ENTRY');
  $scope.cancelButtonState = "resourcesGroupMapList({id:"+$stateParams.groupId+"})"; //Cancel button state
  $scope.saveProgress = false;
  //$scope.isSettingChange = false;

  $scope.save = function(){
    $scope.saveProgress = true;
    if($stateParams.id){
      ResourcesGroupMapFactory.update($scope.groupMap,function(response) {
        alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
        $state.go("resourcesGroupMapList",{id:$stateParams.groupId});
      },function(error){
        displayRestError.display(error);
        $scope.saveProgress = false;
      });
    }else{
      ResourcesGroupMapFactory.create($scope.groupMap,function(response) {
        alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
        $state.go("resourcesGroupMapList",{id:$stateParams.groupId});
      },function(error){
        displayRestError.display(error);
        $scope.saveProgress = false;
      });
    }
  }
});


text:
package org.sleuthkit.autopsy.experimental.volatilityDSP;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeSet;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import org.openide.util.NbBundle.Messages;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataSourceProcessor;
import org.sleuthkit.autopsy.coreutils.ModuleSettings;
import org.sleuthkit.autopsy.coreutils.PathValidator;

@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
final class MemoryDSInputPanel extends JPanel implements DocumentListener {

    private static final long serialVersionUID = 1L;    //default
    private final String PROP_LASTINPUT_PATH = "LBL_LastInputFile_PATH";
    private final JFileChooser fc = new JFileChooser();
    // Externally supplied name is used to store settings
    private final String contextName;
    private final String[] pluginList;
    private final PluginListTableModel tableModel = new PluginListTableModel();
    private final List<String> PluginListNames = new ArrayList<>();
    private final Map<String, Boolean> pluginListStates = new HashMap<>(); // is set by listeners when users select and deselect items

    private final SortedSet<String> profileList = new TreeSet<>(Arrays.asList(
            "VistaSP0x64", "VistaSP0x86", "VistaSP1x64", "VistaSP1x86",
            "VistaSP2x64", "VistaSP2x86", "Win10x64", "Win10x64_10586",
            "Win10x64_14393", "Win10x86", "Win10x86_10586", "Win10x86_14393",
            "Win2003SP0x86", "Win2003SP1x64", "Win2003SP1x86", "Win2003SP2x64",
            "Win2003SP2x86", "Win2008R2SP0x64", "Win2008R2SP1x64", "Win2008R2SP1x64_23418",
            "Win2008SP1x64", "Win2008SP1x86", "Win2008SP2x64", "Win2008SP2x86",
            "Win2012R2x64", "Win2012R2x64_18340", "Win2012x64", "Win2016x64_14393",
            "Win7SP0x64", "Win7SP0x86", "Win7SP1x64", "Win7SP1x64_23418", "Win7SP1x86_23418",
            "Win81U1x64", "Win81U1x86", "Win8SP0x64", "Win8SP0x86", "Win8SP1x64",
            "Win8SP1x64_18340", "Win8SP1x86", "WinXPSP1x64", "WinXPSP2x64", "WinXPSP2x86",
            "WinXPSP3x86"));
    private final static String AUTODETECT_PROFILE = "Auto Detect";

    /**
     * Creates new MemoryDSInputPanel panel for user input
     */
    private MemoryDSInputPanel(String context) {
        this.pluginList = new String[]{"amcache", "cmdline", "cmdscan", "consoles", "malfind", "netscan", "notepad", "pslist", "psxview", "shellbags", "shimcache", "shutdown", "userassist", "apihooks", "connscan", "devicetree", "dlllist", "envars", "filescan", "gahti", "getservicesids", "getsids", "handles", "hashdump", "hivelist", "hivescan", "impscan", "ldrmodules", "lsadump", "modules", "mutantscan", "privs", "psscan", "pstree", "sockets", "svcscan", "shimcache", "timeliner", "unloadedmodules", "userhandles", "vadinfo", "verinfo",  "dlldump", "moddump", "procdump", "dumpfiles", "dumpregistry"};
        Arrays.sort(this.pluginList);

        initComponents();

        errorLabel.setVisible(false);

        fc.setDragEnabled(false);
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setMultiSelectionEnabled(false);

        this.contextName = context;
    }

    /**
     * Creates and returns an instance the panel
     */
    static synchronized MemoryDSInputPanel createInstance(String context) {
        MemoryDSInputPanel instance = new MemoryDSInputPanel(context);

        instance.postInit();
        instance.customizePluginListTable();
        instance.createTimeZoneList();
        instance.populateProfileCombobox();
        instance.createPluginList();

        return instance;
    }

    //post-constructor initialization to properly initialize listener support
    //without leaking references of uninitialized objects
    private void postInit() {
        pathTextField.getDocument().addDocumentListener(this);
    }

    private void customizePluginListTable() {
        pluginTable.setModel(tableModel);
        pluginTable.setTableHeader(null);
        pluginTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final int width = listsScrollPane.getPreferredSize().width;
        pluginTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
        TableColumn column;
        for (int i = 0; i < pluginTable.getColumnCount(); i++) {
            column = pluginTable.getColumnModel().getColumn(i);
            if (i == 0) {
                column.setPreferredWidth(((int) (width * 0.07)));
            } else {
                column.setPreferredWidth(((int) (width * 0.92)));
            }
        }
    }

    /**
     * Creates the drop down list for the time zones and then makes the local
     * machine time zone to be selected.
     */
    private void createTimeZoneList() {
        // load and add all timezone
        String[] ids = SimpleTimeZone.getAvailableIDs();
        for (String id : ids) {
            TimeZone zone = TimeZone.getTimeZone(id);
            int offset = zone.getRawOffset() / 1000;
            int hour = offset / 3600;
            int minutes = (offset % 3600) / 60;
            String item = String.format("(GMT%+d:%02d) %s", hour, minutes, id);

            timeZoneComboBox.addItem(item);
        }
        // get the current timezone
        TimeZone thisTimeZone = Calendar.getInstance().getTimeZone();
        int thisOffset = thisTimeZone.getRawOffset() / 1000;
        int thisHour = thisOffset / 3600;
        int thisMinutes = (thisOffset % 3600) / 60;
        String formatted = String.format("(GMT%+d:%02d) %s", thisHour, thisMinutes, thisTimeZone.getID());

        // set the selected timezone
        timeZoneComboBox.setSelectedItem(formatted);
    }

    private void populateProfileCombobox() {
        profileComboBox.addItem(AUTODETECT_PROFILE);
        profileList.forEach((profile) -> {
            profileComboBox.addItem(profile);
        });
    }

    private void createPluginList() {
        PluginListNames.clear();
        pluginListStates.clear();

        // if the config file doesn't exist, then set them all to enabled
        boolean allEnabled = !ModuleSettings.configExists(this.contextName);
        Map<String, String> pluginMap = ModuleSettings.getConfigSettings(this.contextName);

        for (String plugin : pluginList) {
            PluginListNames.add(plugin);
            if (allEnabled) {
                pluginListStates.put(plugin, true);
            } else if ((pluginMap.containsKey(plugin) && pluginMap.get(plugin).equals("false"))) {
                pluginListStates.put(plugin, false);
            } else {
                pluginListStates.put(plugin, true);
            }
        }
        tableModel.fireTableDataChanged();
        //this.tableModel = pluginsToRun.getModel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        infileTypeButtonGroup = new javax.swing.ButtonGroup();
        pathLabel = new javax.swing.JLabel();
        pathTextField = new javax.swing.JTextField();
        browseButton = new javax.swing.JButton();
        errorLabel = new javax.swing.JLabel();
        timeZoneLabel = new javax.swing.JLabel();
        timeZoneComboBox = new javax.swing.JComboBox<>();
        PluginsToRunLabel = new javax.swing.JLabel();
        listsScrollPane = new javax.swing.JScrollPane();
        pluginTable = new javax.swing.JTable();
        profileLabel = new javax.swing.JLabel();
        profileComboBox = new javax.swing.JComboBox<>();

        org.openide.awt.Mnemonics.setLocalizedText(pathLabel, org.openide.util.NbBundle.getMessage(MemoryDSInputPanel.class, "MemoryDSInputPanel.pathLabel.text")); // NOI18N

        pathTextField.setText(org.openide.util.NbBundle.getMessage(MemoryDSInputPanel.class, "MemoryDSInputPanel.pathTextField.text")); // NOI18N
        pathTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pathTextFieldActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(browseButton, org.openide.util.NbBundle.getMessage(MemoryDSInputPanel.class, "MemoryDSInputPanel.browseButton.text")); // NOI18N
        browseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseButtonActionPerformed(evt);
            }
        });

        errorLabel.setForeground(new java.awt.Color(255, 0, 0));
        org.openide.awt.Mnemonics.setLocalizedText(errorLabel, org.openide.util.NbBundle.getMessage(MemoryDSInputPanel.class, "MemoryDSInputPanel.errorLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(timeZoneLabel, org.openide.util.NbBundle.getMessage(MemoryDSInputPanel.class, "MemoryDSInputPanel.timeZoneLabel.text")); // NOI18N

        timeZoneComboBox.setMaximumRowCount(30);

        org.openide.awt.Mnemonics.setLocalizedText(PluginsToRunLabel, org.openide.util.NbBundle.getMessage(MemoryDSInputPanel.class, "MemoryDSInputPanel.PluginsToRunLabel.text")); // NOI18N

        pluginTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        listsScrollPane.setViewportView(pluginTable);

        org.openide.awt.Mnemonics.setLocalizedText(profileLabel, org.openide.util.NbBundle.getMessage(MemoryDSInputPanel.class, "MemoryDSInputPanel.profileLabel.text")); // NOI18N

        profileComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                profileComboBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(pathTextField)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(browseButton, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pathLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(timeZoneLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(listsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(profileComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, 243, Short.MAX_VALUE)
                                .addComponent(timeZoneComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
                .addGap(0, 163, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(errorLabel)
                    .addComponent(PluginsToRunLabel)
                    .addComponent(profileLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(pathLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browseButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(timeZoneLabel)
                    .addComponent(timeZoneComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(errorLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(profileLabel)
                    .addComponent(profileComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(PluginsToRunLabel)
                    .addComponent(listsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(73, Short.MAX_VALUE))
        );

        pathLabel.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(MemoryDSInputPanel.class, "MemoryDSInputPanel.pathLabel.AccessibleContext.accessibleName")); // NOI18N
    }// </editor-fold>//GEN-END:initComponents
    @SuppressWarnings("deprecation")
    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
        String oldText = pathTextField.getText();
        // set the current directory of the FileChooser if the ImagePath Field is valid
        File currentDir = new File(oldText);
        if (currentDir.exists()) {
            fc.setCurrentDirectory(currentDir);
        }

        int retval = fc.showOpenDialog(this);
        if (retval == JFileChooser.APPROVE_OPTION) {
            String path = fc.getSelectedFile().getPath();
            pathTextField.setText(path);
        }
    }//GEN-LAST:event_browseButtonActionPerformed

    private void profileComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_profileComboBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_profileComboBoxActionPerformed

    private void pathTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pathTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_pathTextFieldActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel PluginsToRunLabel;
    private javax.swing.JButton browseButton;
    private javax.swing.JLabel errorLabel;
    private javax.swing.ButtonGroup infileTypeButtonGroup;
    private javax.swing.JScrollPane listsScrollPane;
    private javax.swing.JLabel pathLabel;
    private javax.swing.JTextField pathTextField;
    private javax.swing.JTable pluginTable;
    private javax.swing.JComboBox<String> profileComboBox;
    private javax.swing.JLabel profileLabel;
    private javax.swing.JComboBox<String> timeZoneComboBox;
    private javax.swing.JLabel timeZoneLabel;
    // End of variables declaration//GEN-END:variables
    /**
     * Get the path of the user selected image.
     *
     * @return the image path
     */
    String getImageFilePath() {
        return pathTextField.getText();
    }

    /**
     *
     * @return Profile or empty string if auto detect
     */
    String getProfile() {
        String profile = (String)profileComboBox.getSelectedItem();
        if (profile.equals(AUTODETECT_PROFILE)) {
            return "";
        }
        return profile;
    }

    List<String> getPluginsToRun() {
        List<String> enabledPlugins = new ArrayList<>();
        Map<String, String> pluginSettingsToSave = new HashMap<>();
        for (String plugin : PluginListNames) {
            if (pluginListStates.get(plugin)) {
                enabledPlugins.add(plugin);
            }
            pluginSettingsToSave.put(plugin, pluginListStates.get(plugin).toString());
        }
        ModuleSettings.setConfigSettings(this.contextName, pluginSettingsToSave);
        // @@ Could return keys of set
        return enabledPlugins;
    }

    void reset() {
        //reset the UI elements to default
        pathTextField.setText(null);
    }

    String getTimeZone() {
        String tz = timeZoneComboBox.getSelectedItem().toString();
        return tz.substring(tz.indexOf(")") + 2).trim();
    }

    /**
     * Should we enable the next button of the wizard?
     *
     * @return true if a proper image has been selected, false otherwise
     */
    boolean validatePanel() {
        errorLabel.setVisible(false);
        String path = getImageFilePath();
        if (path == null || path.isEmpty()) {
            return false;
        }

        // display warning if there is one (but don't disable "next" button)
        warnIfPathIsInvalid(path);

        boolean isFile = new File(path).isFile();

        return (isFile);
    }

    /**
     * Validates path to selected data source and displays warning if it is
     * invalid.
     *
     * @param path Absolute path to the selected data source
     */
    @Messages({
        "MemoryDSInputPanel_errorMsg_noOpenCase=No open case",
        "MemoryDSInputPanel_errorMsg_dataSourcePathOnCdrive=Path to multi-user data source is on \"C:\" drive"
    })
    private void warnIfPathIsInvalid(String path) {
        try {
            if (!PathValidator.isValid(path, Case.getCurrentCaseThrows().getCaseType())) {
                errorLabel.setVisible(true);
                errorLabel.setText(Bundle.MemoryDSInputPanel_errorMsg_dataSourcePathOnCdrive());
            }
        } catch (NoCurrentCaseException unused) {
            errorLabel.setVisible(true);
            errorLabel.setText(Bundle.MemoryDSInputPanel_errorMsg_dataSourcePathOnCdrive());
        }
    }

    void storeSettings() {
        String inFilePath = getImageFilePath();
        //String<List> inPlugins =
        if (null != inFilePath) {
            String imagePath = inFilePath.substring(0, inFilePath.lastIndexOf(File.separator) + 1);
            ModuleSettings.setConfigSetting(contextName, PROP_LASTINPUT_PATH, imagePath);
        }
    }

    void readSettings() {
        String inFilePath = ModuleSettings.getConfigSetting(contextName, PROP_LASTINPUT_PATH);
        if (null != inFilePath) {
            if (!inFilePath.isEmpty()) {
                pathTextField.setText(inFilePath);
            }
        }
    }

    /**
     * Update functions are called by the pathTextField which has this set as
     * it's DocumentEventListener. Each update function fires a property change
     * to be caught by the parent panel.
     *
     * @param e the event, which is ignored
     */
    @Override
    public void insertUpdate(DocumentEvent e) {
        firePropertyChange(DataSourceProcessor.DSP_PANEL_EVENT.UPDATE_UI.toString(), false, true);
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        firePropertyChange(DataSourceProcessor.DSP_PANEL_EVENT.UPDATE_UI.toString(), false, true);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        firePropertyChange(DataSourceProcessor.DSP_PANEL_EVENT.UPDATE_UI.toString(), false, true);
    }

    /**
     * Set the focus to the pathTextField.
     */
    void select() {
        pathTextField.requestFocusInWindow();
    }

    private class PluginListTableModel extends AbstractTableModel {

        @Override
        public int getRowCount() {
            return MemoryDSInputPanel.this.PluginListNames.size();
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            String listName = MemoryDSInputPanel.this.PluginListNames.get(rowIndex);
            if (columnIndex == 0) {
                return pluginListStates.get(listName);
            } else {
                return listName;
            }
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return columnIndex == 0;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            String listName = MemoryDSInputPanel.this.PluginListNames.get(rowIndex);
            if (columnIndex == 0) {
                pluginListStates.put(listName, (Boolean) aValue);
            }
        }

        @Override
        public Class<?> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

}


text:
package cc.liyongzhi.bluetoothselector;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class ChooseBluetoothActivity extends AppCompatActivity {

    private Context mContext;
    private BluetoothAdapter mBluetoothAdapter;
    private final int REQUEST_ENABLE_BT = 0x01;
    private RecyclerView mRecyclerView;
    private DeviceListAdapter mAdapter;
    private AppCompatTextView mTvRefresh;
    private ArrayList<String> mPairedDeviceList = new ArrayList<>();
    private ArrayList<String> mFoundDeviceList = new ArrayList<>();//0:开始搜索
    private int state = 0;
    private String mKey = "";

    // Create a BroadcastReceiver for ACTION_FOUND
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String s = device.getName() + "\n" + device.getAddress();
                if (!mFoundDeviceList.contains(s)) {
                    // Add the name and address to an array adapter to show in a ListView
                    mFoundDeviceList.add(device.getName() + "\n" + device.getAddress());
                    mAdapter.notifyDataSetChanged();
                }
            } else if (MedBluetooth.INTENT_ACTION_BLUETOOTH_ADAPTER_CANCEL_DISCOVERY.equals(action)) {
                mBluetoothAdapter.cancelDiscovery();
                mTvRefresh.setText("重新搜索");
                state = 2;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_bluetooth);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {

            getSupportActionBar().setTitle(R.string.choose_bluetooth_activity_title);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
        mContext = this;

        BluetoothScreenManger.getScreenManger().pushActivity(this);

        mKey = getIntent().getStringExtra("callback_key");

        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(MedBluetooth.INTENT_ACTION_BLUETOOTH_ADAPTER_CANCEL_DISCOVERY);
        registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "获取蓝牙适配器失败", Toast.LENGTH_SHORT).show();
            BluetoothScreenManger.getScreenManger().popAllActivity();
        }
        checkBluetoothIsEnable();
        initData();
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
    }

    private Boolean checkBluetoothIsEnable() {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBtIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            Toast.makeText(this, "蓝牙未打开", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    private void initData() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        // If there are paired devices
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                // Add the name and address to an array adapter to show in a ListView
                String s = device.getName() + "\n" + device.getAddress();
                if (!mPairedDeviceList.contains(s)) {
                    mPairedDeviceList.add(device.getName() + "\n" + device.getAddress());
                }
            }
        }
    }

    private void initView() {

        mRecyclerView = (RecyclerView) findViewById(R.id.rv_bluetooth_device_list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new DeviceListAdapter(mContext,mPairedDeviceList, mFoundDeviceList, mBluetoothAdapter, mKey);
        mRecyclerView.setAdapter(mAdapter);

        mTvRefresh = (AppCompatTextView) findViewById(R.id.tv_refresh);
        mTvRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!checkBluetoothIsEnable()) {
                    return;
                };

                switch (state) {
                    case 0:
                        mBluetoothAdapter.startDiscovery();
                        Toast.makeText(mContext, "开始搜索", Toast.LENGTH_SHORT).show();
                        mTvRefresh.setText("停止");
                        state = 1;
                        break;
                    case 1:
                        mBluetoothAdapter.cancelDiscovery();
                        Toast.makeText(mContext, "停止搜索", Toast.LENGTH_SHORT).show();
                        mTvRefresh.setText("重新搜索");
                        state = 2;
                        break;
                    case 2:
                        mFoundDeviceList.clear();
                        mAdapter.notifyDataSetChanged();
                        mBluetoothAdapter.startDiscovery();
                        Toast.makeText(mContext, "开始搜索", Toast.LENGTH_SHORT).show();
                        mTvRefresh.setText("停止");
                        state = 1;
                        break;
                }
                mBluetoothAdapter.startDiscovery();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "蓝牙打开失败", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "蓝牙打开成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            BluetoothScreenManger.getScreenManger().popAllActivity();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}


text:
package com.amazonaws.services.kinesis.aggregators.configuration;

public enum DataExtractor {
    JSON("com.amazonaws.services.kinesis.io.JsonDataExtractor"), CSV(
            "com.amazonaws.services.kinesis.io.CsvDataExtractor"), OBJECT(
            "com.amazonaws.services.kinesis.io.ObjectExtractor"), REGEX(
            "com.amazonaws.services.kinesis.io.RegexDataExtractor");

    private DataExtractor(String linkedClass) {
        this.linkedClass = linkedClass;
    }

    private String linkedClass;

    public String getLinkedClass() {
        return this.linkedClass;
    }
}


text:
package com.flowpowered.caustic.api.model;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import gnu.trove.impl.Constants;
import gnu.trove.list.TFloatList;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TFloatArrayList;
import gnu.trove.map.TCharFloatMap;
import gnu.trove.map.TCharIntMap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TCharFloatHashMap;
import gnu.trove.map.hash.TCharIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;

import com.flowpowered.math.GenericMath;
import com.flowpowered.math.vector.Vector2f;
import com.flowpowered.math.vector.Vector4f;

import com.flowpowered.caustic.api.Material;
import com.flowpowered.caustic.api.data.VertexAttribute;
import com.flowpowered.caustic.api.data.VertexAttribute.DataType;
import com.flowpowered.caustic.api.data.VertexData;
import com.flowpowered.caustic.api.gl.Context;
import com.flowpowered.caustic.api.gl.Program;
import com.flowpowered.caustic.api.gl.Texture;
import com.flowpowered.caustic.api.gl.Texture.FilterMode;
import com.flowpowered.caustic.api.gl.Texture.Format;
import com.flowpowered.caustic.api.gl.Texture.InternalFormat;
import com.flowpowered.caustic.api.gl.VertexArray;
import com.flowpowered.caustic.api.util.CausticUtil;

/**
 * A model for rendering strings with a desired font. This model will work with both OpenGL versions. To render a string, set it with {@link #setString(String)}. Glyphs in the string that have not
 * been declared when constructing the model will be ignored.
 *

 * Colors are supported. Use #aarrggbb, where aa is the alpha hexadecimal value, rr is the red hexadecimal value, gg is the green hexadecimal value
 * and bb is the blue hexadecimal value. Color codes can be escaped with \.
 *

 * As for the implementation, this model wraps a model of the desired OpenGL version. The model contains a mesh of tiles, all at (0,0). Each tile has one glyph on it. When rendering, the desired tile
 * is selected, placed at the origin and rendered. The next glyph will be rendered in the same fashion, but offset on the x axis by the width of the last glyph. The mesh and indices are only uploaded
 * once; the renderer uses the indices for the desired glyph.
 */
public class StringModel extends Model {
    private static final int GLYPH_INDEX_COUNT = 6;
    private static final Pattern COLOR_PATTERN = Pattern.compile("#[a-fA-F\\d]{1,8}");
    private final TCharIntMap glyphIndexes;
    private final TCharFloatMap glyphOffsets;
    private final int glyphPadding;
    private final float lineHeight;
    private float pixelSize;
    private String rawString;
    private String string;
    private final TIntObjectMap<Vector4f> colorIndices = new TIntObjectHashMap<>();

    /**
     * Constructs a new string model from the provided one. The glyph indexes, offsets, padding and line heights are reused. The string and color information remain empty.
     *
     * @param model The model to derive this one from
     */
    protected StringModel(StringModel model) {
        super(model);
        this.glyphIndexes = model.glyphIndexes;
        this.glyphOffsets = model.glyphOffsets;
        this.glyphPadding = model.glyphPadding;
        this.lineHeight = model.lineHeight;
        this.pixelSize = model.pixelSize;
    }

    /**
     * Creates a new string model, from the OpenGL context, the font shader program, the glyphs to support, the font to render with and the window width (used to get scale for the model).
     * Anti-aliasing will be automatically done based on the font size.
     *
     * @param context The OpenGL context
     * @param fontProgram The program of shaders responsible to for rendering the font
     * @param glyphs The glyphs
     * @param font The font
     * @param windowWidth The window with
     */
    public StringModel(Context context, Program fontProgram, CharSequence glyphs, Font font, int windowWidth) {
        this(context, fontProgram, glyphs, font, AntiAliasing.AUTO, windowWidth);
    }

    /**
     * Creates a new string model, from the OpenGL context, the font shader program, the glyphs to support, the font to render with, the window width (used to get scale for the model) and the
     * anti-aliasing mode.
     *
     * @param context The OpenGL context
     * @param fontProgram The program of shaders responsible to for rendering the font
     * @param glyphs The glyphs
     * @param font The font
     * @param antiAliasing The anti-aliasing mode
     * @param windowWidth The window with
     */
    public StringModel(Context context, Program fontProgram, CharSequence glyphs, Font font, AntiAliasing antiAliasing, int windowWidth) {
        if (context == null) {
            throw new IllegalStateException("GL version cannot be null");
        }
        if (fontProgram == null) {
            throw new IllegalStateException("Font program cannot be null");
        }
        if (glyphs == null) {
            throw new IllegalStateException("Glyphs cannot be null");
        }
        if (font == null) {
            throw new IllegalStateException("Font cannot be null");
        }
        if (windowWidth <= 0) {
            throw new IllegalStateException("The window width must be greater than zero");
        }
        // Remove duplicate glyphs
        glyphs = removeDuplicates(glyphs);
        // Stores the first vertex index for each glyph
        glyphIndexes = new TCharIntHashMap(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, Character.MIN_VALUE, -1);
        // Stores the offset (width) of each glyph
        glyphOffsets = new TCharFloatHashMap();
        // Size of a pixel in screen coordinates
        pixelSize = 1f / windowWidth;
        // Create temporary graphics, font metrics and render context
        final Graphics graphics = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR).getGraphics();
        graphics.setFont(font);
        final FontMetrics fontMetrics = graphics.getFontMetrics();
        final FontRenderContext fontRenderContext = fontMetrics.getFontRenderContext();
        // Obtain the glyph string size
        final Rectangle2D size = font.getStringBounds(String.valueOf(glyphs), fontRenderContext);
        // Obtain the width of each glyph
        final TCharIntMap widths = new TCharIntHashMap();
        for (int i = 0; i < glyphs.length(); i++) {
            final char glyph = glyphs.charAt(i);
            widths.put(glyph, fontMetrics.charWidth(glyph));
        }
        // Set the glyph padding to half the mean width of the first 256 characters
        glyphPadding = GenericMath.mean(fontMetrics.getWidths()) / 2;
        // Dispose of the temporary resources
        graphics.dispose();
        // Create the texture
        final int width = (int) Math.ceil(size.getWidth()) + glyphs.length() * glyphPadding * 2;
        final int height = (int) Math.ceil(size.getHeight());
        final Texture texture = generateTexture(context, glyphs, widths, font, antiAliasing, width, height);
        // Set the line height, for new lines
        lineHeight = fontMetrics.getHeight();
        // Create the material
        final Material material = new Material(fontProgram);
        material.addTexture(0, texture);
        setMaterial(material);
        // Create the model mesh
        final VertexArray vertexArray = generateMesh(context, glyphs, widths, width, height);
        // Only render one glyph per render call
        vertexArray.setIndicesCount(GLYPH_INDEX_COUNT);
        // Set the vertex array
        setVertexArray(vertexArray);
    }

    @Override
    public void render() {
        final Program program = getMaterial().getProgram();
        program.setUniform("fontColor", CausticUtil.WHITE);
        program.setUniform("pixelSize", pixelSize);
        final VertexArray vertexArray = getVertexArray();
        // Remove the padding for the first glyph
        Vector2f offset = new Vector2f(-glyphPadding * pixelSize, 0);
        final char[] glyphs = string.toCharArray();
        for (int i = 0; i < glyphs.length; i++) {
            final char glyph = glyphs[i];
            // Move the glyph offset to the next line for the new line character
            if (glyph == '\n') {
                offset = new Vector2f(-glyphPadding * pixelSize, offset.getY() - lineHeight * pixelSize);
                continue;
            }
            // Look for a color code
            final Vector4f color = colorIndices.get(i);
            if (color != null) {
                // Upload the color
                program.setUniform("fontColor", color);
            }
            // Get the glyph start index
            final int glyphIndex = glyphIndexes.get(glyph);
            // Skip glyphs missing in the texture
            if (glyphIndex == -1) {
                continue;
            }
            // Set rendering indices offset for the glyph
            vertexArray.setIndicesOffset(glyphIndex);
            // Offset the glyph in the string
            program.setUniform("glyphOffset", offset);
            // Offset for the next glyph
            offset = offset.add(glyphOffsets.get(glyph) * pixelSize, 0);
            // Render the model
            vertexArray.draw();
        }
    }

    /**
     * Sets the string to render.
     *
     * @param string The string to render
     */
    public void setString(String string) {
        rawString = string;
        colorIndices.clear();
        // Search for color codes
        final StringBuilder stringBuilder = new StringBuilder(string);
        final Matcher matcher = COLOR_PATTERN.matcher(string);
        int removedCount = 0;
        while (matcher.find()) {
            final int index = matcher.start() - removedCount;
            // Ignore escaped color codes
            if (index > 0 && stringBuilder.charAt(index - 1) == '\\') {
                // Remove the escape character
                stringBuilder.deleteCharAt(index - 1);
                removedCount++;
                continue;
            }
            // Add the color for the index and delete it from the string
            final String colorCode = matcher.group();
            colorIndices.put(index, CausticUtil.fromPackedARGB(Long.decode(colorCode).intValue()));
            final int length = colorCode.length();
            stringBuilder.delete(index, index + length);
            removedCount += length;
        }
        // Color code free string
        this.string = stringBuilder.toString();
    }

    /**
     * Returns the model's string.
     *
     * @return The string
     */
    public String getString() {
        return rawString;
    }

    /**
     * Sets the width of the window, used to ensure that the font pixels match up with the display pixels.
     *
     * @param width The window width
     */
    public void setWindowWidth(int width) {
        if (width <= 0) {
            throw new IllegalStateException("The window width must be greater than zero");
        }
        pixelSize = 1f / width;
    }

    /**
     * Returns an instance of this string model. The model shares the same glyphs as the original one, but different position information and uniform holder.
     *
     * @return The instanced string model
     */
    @Override
    public StringModel getInstance() {
        return new StringModel(this);
    }

    private VertexArray generateMesh(Context context, CharSequence glyphs, TCharIntMap glyphWidths, int textureWidth, int textureHeight) {
        final VertexData data = new VertexData();
        // Add the positions and texture coordinates attributes
        final VertexAttribute positionAttribute = new VertexAttribute("positions", DataType.FLOAT, 2);
        data.addAttribute(0, positionAttribute);
        final TFloatList positions = new TFloatArrayList();
        final VertexAttribute textureCoordsAttribute = new VertexAttribute("textureCoords", DataType.FLOAT, 2);
        data.addAttribute(1, textureCoordsAttribute);
        final TFloatList textureCoords = new TFloatArrayList();
        // Get the indices
        final TIntList indices = data.getIndices();
        /*
         * Generate a pile of small rectangles, each having one glyph on it
         * Rendering a sequence of glyphs means rendering the sequence of rectangles with the correct glyphs
         * Offsetting them correctly
         * 1--3
         * |\ |
         * | \|
         * 0--2
         */
        float x = 0;
        int index = 0;
        int renderIndex = 0;
        for (int i = 0; i < glyphs.length(); i++) {
            final char glyph = glyphs.charAt(i);
            final int glyphWidth = glyphWidths.get(glyph);
            float paddedGlyphWidth = glyphWidth + glyphPadding * 2;
            add(positions, 0, 0, 0, textureHeight);
            add(textureCoords, x, 0, x, 1);
            x += paddedGlyphWidth / textureWidth;
            add(positions, paddedGlyphWidth, 0, paddedGlyphWidth, textureHeight);
            add(textureCoords, x, 0, x, 1);
            add(indices, index, index + 2, index + 1, index + 2, index + 3, index + 1);
            index += 4;
            glyphIndexes.put(glyph, renderIndex);
            glyphOffsets.put(glyph, glyphWidth);
            renderIndex += 6;
        }
        positionAttribute.setData(positions);
        textureCoordsAttribute.setData(textureCoords);
        // Set the vertex data in the model
        final VertexArray vertexArray = context.newVertexArray();
        vertexArray.create();
        vertexArray.setData(data);
        return vertexArray;
    }

    private Texture generateTexture(Context context, CharSequence glyphs, TCharIntMap glyphWidths, Font font, AntiAliasing antiAliasing, int width, int height) {
        final Texture texture = context.newTexture();
        // Create an image for the texture
        final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        final Graphics graphics = image.getGraphics();
        // Draw the glyphs in white on a transparent background
        graphics.setColor(java.awt.Color.WHITE);
        graphics.setFont(font);
        ((Graphics2D) graphics).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, antiAliasing.getConstant());
        final FontMetrics fontMetrics = graphics.getFontMetrics();
        int x = 0;
        final int y = fontMetrics.getAscent();
        for (int i = 0; i < glyphs.length(); i++) {
            final char glyph = glyphs.charAt(i);
            x += glyphPadding;
            graphics.drawString(String.valueOf(glyph), x, y);
            x += glyphWidths.get(glyph) + glyphPadding;
        }
        // Dispose of the image graphics
        graphics.dispose();
        // Generate the texture
        texture.create();
        texture.setFormat(Format.RED, InternalFormat.R8);
        texture.setFilters(FilterMode.NEAREST, FilterMode.NEAREST);
        texture.setImageData(CausticUtil.getImageData(image, Format.RED), width, height);
        return texture;
    }

    private static void add(TFloatList list, float... f) {
        list.add(f);
    }

    private static void add(TIntList list, int... f) {
        list.add(f);
    }

    private static CharSequence removeDuplicates(CharSequence chars) {
        String results = "";
        final int length = chars.length();
        outer:
        for (int i = 0; i < length; i++) {
            final char c = chars.charAt(i);
            for (int ii = i + 1; ii < length; ii++) {
                if (c == chars.charAt(ii)) {
                    continue outer;
                }
            }
            results += c;
        }
        return results;
    }

    /**
     * An enum of the various available anti-aliasing policies.
     */
    public static enum AntiAliasing {
        ON(RenderingHints.VALUE_TEXT_ANTIALIAS_ON),
        OFF(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF),
        AUTO(RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        private final Object constant;

        private AntiAliasing(Object constant) {
            this.constant = constant;
        }

        private Object getConstant() {
            return constant;
        }
    }
}


text:
package org.kie.workbench.common.stunner.cm.backend.converters.fromstunner;

import org.junit.Before;
import org.junit.Test;
import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.DefinitionsBuildingContext;
import org.kie.workbench.common.stunner.cm.backend.converters.fromstunner.activities.CaseManagementReusableSubprocessConverter;
import org.kie.workbench.common.stunner.cm.backend.converters.fromstunner.processes.CaseManagementSubProcessConverter;
import org.kie.workbench.common.stunner.cm.backend.converters.fromstunner.properties.CaseManagementPropertyWriterFactory;
import org.kie.workbench.common.stunner.cm.definition.CaseManagementDiagram;
import org.kie.workbench.common.stunner.core.graph.impl.GraphImpl;
import org.kie.workbench.common.stunner.core.graph.store.GraphNodeStoreImpl;

import static org.junit.Assert.assertTrue;

public class CaseManagementConverterFactoryTest {

    private CaseManagementConverterFactory tested;

    @Before
    public void setUp() throws Exception {
        CaseManagementPropertyWriterFactory factory = new CaseManagementPropertyWriterFactory();

        tested = new CaseManagementConverterFactory(new DefinitionsBuildingContext(new GraphImpl("x", new GraphNodeStoreImpl()),
                                                                                CaseManagementDiagram.class),
                                                    factory);
    }

    @Test
    public void testReusableSubprocessConverter() throws Exception {
        assertTrue(CaseManagementReusableSubprocessConverter.class.isInstance(tested.reusableSubprocessConverter()));
    }

    @Test
    public void testSubProcessConverter() throws Exception {
        assertTrue(CaseManagementSubProcessConverter.class.isInstance(tested.subProcessConverter()));
    }
}