text:
"""Parsed source code checkers for docstring violations."""

import ast
import string
import tokenize as tk
from collections import namedtuple
from itertools import chain, takewhile
from re import compile as re

from . import violations
from .config import IllegalConfiguration
from .parser import (
    AllError,
    Class,
    Definition,
    Function,
    Method,
    Module,
    NestedClass,
    NestedFunction,
    Package,
    ParseError,
    Parser,
    StringIO,
)
from .utils import (
    common_prefix_length,
    is_blank,
    log,
    pairwise,
    strip_non_alphanumeric,
)
from .wordlists import IMPERATIVE_BLACKLIST, IMPERATIVE_VERBS, stem

__all__ = ('check',)

def check_for(kind, terminal=False):
    def decorator(f):
        f._check_for = kind
        f._terminal = terminal
        return f

    return decorator

class ConventionChecker:
    """Checker for PEP 257, NumPy and Google conventions.

    D10x: Missing docstrings
    D20x: Whitespace issues
    D30x: Docstring formatting
    D40x: Docstring content issues

    """

    NUMPY_SECTION_NAMES = (
        'Short Summary',
        'Extended Summary',
        'Parameters',
        'Returns',
        'Yields',
        'Other Parameters',
        'Raises',
        'See Also',
        'Notes',
        'References',
        'Examples',
        'Attributes',
        'Methods',
    )

    GOOGLE_SECTION_NAMES = (
        'Args',
        'Arguments',
        'Attention',
        'Attributes',
        'Caution',
        'Danger',
        'Error',
        'Example',
        'Examples',
        'Hint',
        'Important',
        'Keyword Args',
        'Keyword Arguments',
        'Methods',
        'Note',
        'Notes',
        'Return',
        'Returns',
        'Raises',
        'References',
        'See Also',
        'Tip',
        'Todo',
        'Warning',
        'Warnings',
        'Warns',
        'Yield',
        'Yields',
    )

    # Examples that will be matched -
    # "     random: Test" where random will be captured as the param
    # " random         : test" where random will be captured as the param
    # "  random_t (Test) : test  " where random_t will be captured as the param
    # Matches anything that fulfills all the following conditions:
    GOOGLE_ARGS_REGEX = re(
        # Begins with 0 or more whitespace characters
        r"^\s*"
        # Followed by 1 or more unicode chars, numbers or underscores
        # The above is captured as the first group as this is the paramater name.
        r"(\w+)"
        # Followed by 0 or more whitespace characters
        r"\s*"
        # Matches patterns contained within round brackets.
        # The `.*?`matches any sequence of characters in a non-greedy
        # way (denoted by the `*?`)
        r"(\(.*?\))?"
        # Followed by 0 or more whitespace chars
        r"\s*"
        # Followed by a colon
        r":"
        # Followed by 1 or more characters - which is the docstring for the parameter
        ".+"
    )

    def check_source(
        self,
        source,
        filename,
        ignore_decorators=None,
        ignore_inline_noqa=False,
    ):
        module = parse(StringIO(source), filename)
        for definition in module:
            for this_check in self.checks:
                terminate = False
                if isinstance(definition, this_check._check_for):
                    skipping_all = definition.skipped_error_codes == 'all'
                    decorator_skip = ignore_decorators is not None and any(
                        len(ignore_decorators.findall(dec.name)) > 0
                        for dec in definition.decorators
                    )
                    if (
                        ignore_inline_noqa or not skipping_all
                    ) and not decorator_skip:
                        error = this_check(
                            self, definition, definition.docstring
                        )
                    else:
                        error = None
                    errors = error if hasattr(error, '__iter__') else [error]
                    for error in errors:
                        if error is not None and (
                            ignore_inline_noqa
                            or error.code not in definition.skipped_error_codes
                        ):
                            partition = this_check.__doc__.partition('.\n')
                            message, _, explanation = partition
                            error.set_context(
                                explanation=explanation, definition=definition
                            )
                            yield error
                            if this_check._terminal:
                                terminate = True
                                break
                if terminate:
                    break

    @property
    def checks(self):
        all = [
            this_check
            for this_check in vars(type(self)).values()
            if hasattr(this_check, '_check_for')
        ]
        return sorted(all, key=lambda this_check: not this_check._terminal)

    @check_for(Definition, terminal=True)
    def check_docstring_missing(self, definition, docstring):
        """D10{0,1,2,3}: Public definitions should have docstrings.

        All modules should normally have docstrings.  [...] all functions and
        classes exported by a module should also have docstrings. Public
        methods (including the __init__ constructor) should also have
        docstrings.

        Note: Public (exported) definitions are either those with names listed
              in __all__ variable (if present), or those that do not start
              with a single underscore.

        """
        if (
            not docstring
            and definition.is_public
            or docstring
            and is_blank(ast.literal_eval(docstring))
        ):
            codes = {
                Module: violations.D100,
                Class: violations.D101,
                NestedClass: violations.D106,
                Method: lambda: violations.D105()
                if definition.is_magic
                else (
                    violations.D107()
                    if definition.is_init
                    else (
                        violations.D102()
                        if not definition.is_overload
                        else None
                    )
                ),
                NestedFunction: violations.D103,
                Function: (
                    lambda: violations.D103()
                    if not definition.is_overload
                    else None
                ),
                Package: violations.D104,
            }
            return codes[type(definition)]()

    @check_for(Definition)
    def check_one_liners(self, definition, docstring):
        """D200: One-liner docstrings should fit on one line with quotes.

        The closing quotes are on the same line as the opening quotes.
        This looks better for one-liners.

        """
        if docstring:
            lines = ast.literal_eval(docstring).split('\n')
            if len(lines) > 1:
                non_empty_lines = sum(1 for l in lines if not is_blank(l))
                if non_empty_lines == 1:
                    return violations.D200(len(lines))

    @check_for(Function)
    def check_no_blank_before(self, function, docstring):  # def
        """D20{1,2}: No blank lines allowed around function/method docstring.

        There's no blank line either before or after the docstring unless directly
        followed by an inner function or class.
        """
        if docstring:
            before, _, after = function.source.partition(docstring)
            blanks_before = list(map(is_blank, before.split('\n')[:-1]))
            blanks_after = list(map(is_blank, after.split('\n')[1:]))
            blanks_before_count = sum(takewhile(bool, reversed(blanks_before)))
            blanks_after_count = sum(takewhile(bool, blanks_after))
            if blanks_before_count != 0:
                yield violations.D201(blanks_before_count)
            if not all(blanks_after) and blanks_after_count != 0:
                # Report a D202 violation if the docstring is followed by a blank line
                # and the blank line is not itself followed by an inner function or
                # class.
                if not (
                    blanks_after_count == 1
                    and re(r"\s+(?:(?:class|def|async def)\s|@)").match(after)
                ):
                    yield violations.D202(blanks_after_count)

    @check_for(Class)
    def check_blank_before_after_class(self, class_, docstring):
        """D20{3,4}: Class docstring should have 1 blank line around them.

        Insert a blank line before and after all docstrings (one-line or
        multi-line) that document a class -- generally speaking, the class's
        methods are separated from each other by a single blank line, and the
        docstring needs to be offset from the first method by a blank line;
        for symmetry, put a blank line between the class header and the
        docstring.

        """
        # NOTE: this gives false-positive in this case
        # class Foo:
        #
        #     """Docstring."""
        #
        #
        # # comment here
        # def foo(): pass
        if docstring:
            before, _, after = class_.source.partition(docstring)
            blanks_before = list(map(is_blank, before.split('\n')[:-1]))
            blanks_after = list(map(is_blank, after.split('\n')[1:]))
            blanks_before_count = sum(takewhile(bool, reversed(blanks_before)))
            blanks_after_count = sum(takewhile(bool, blanks_after))
            if blanks_before_count != 0:
                yield violations.D211(blanks_before_count)
            if blanks_before_count != 1:
                yield violations.D203(blanks_before_count)
            if not all(blanks_after) and blanks_after_count != 1:
                yield violations.D204(blanks_after_count)

    @check_for(Definition)
    def check_blank_after_summary(self, definition, docstring):
        """D205: Put one blank line between summary line and description.

        Multi-line docstrings consist of a summary line just like a one-line
        docstring, followed by a blank line, followed by a more elaborate
        description. The summary line may be used by automatic indexing tools;
        it is important that it fits on one line and is separated from the
        rest of the docstring by a blank line.

        """
        if docstring:
            lines = ast.literal_eval(docstring).strip().split('\n')
            if len(lines) > 1:
                post_summary_blanks = list(map(is_blank, lines[1:]))
                blanks_count = sum(takewhile(bool, post_summary_blanks))
                if blanks_count != 1:
                    return violations.D205(blanks_count)

    @staticmethod
    def _get_docstring_indent(definition, docstring):
        """Return the indentation of the docstring's opening quotes."""
        before_docstring, _, _ = definition.source.partition(docstring)
        _, _, indent = before_docstring.rpartition('\n')
        return indent

    @check_for(Definition)
    def check_indent(self, definition, docstring):
        """D20{6,7,8}: The entire docstring should be indented same as code.

        The entire docstring is indented the same as the quotes at its
        first line.

        """
        if docstring:
            indent = self._get_docstring_indent(definition, docstring)
            lines = docstring.split('\n')
            if len(lines) > 1:
                # First line and line continuations need no indent.
                lines = [
                    line
                    for i, line in enumerate(lines)
                    if i and not lines[i - 1].endswith('\\')
                ]
                indents = [leading_space(l) for l in lines if not is_blank(l)]
                if set(' \t') == set(''.join(indents) + indent):
                    yield violations.D206()
                if (len(indents) > 1 and min(indents[:-1]) > indent) or (
                    len(indents) > 0 and indents[-1] > indent
                ):
                    yield violations.D208()
                if len(indents) > 0 and min(indents) < indent:
                    yield violations.D207()

    @check_for(Definition)
    def check_newline_after_last_paragraph(self, definition, docstring):
        """D209: Put multi-line docstring closing quotes on separate line.

        Unless the entire docstring fits on a line, place the closing
        quotes on a line by themselves.

        """
        if docstring:
            lines = [
                l
                for l in ast.literal_eval(docstring).split('\n')
                if not is_blank(l)
            ]
            if len(lines) > 1:
                if docstring.split("\n")[-1].strip() not in ['"""', "'''"]:
                    return violations.D209()

    @check_for(Definition)
    def check_surrounding_whitespaces(self, definition, docstring):
        """D210: No whitespaces allowed surrounding docstring text."""
        if docstring:
            lines = ast.literal_eval(docstring).split('\n')
            if (
                lines[0].startswith(' ')
                or len(lines) == 1
                and lines[0].endswith(' ')
            ):
                return violations.D210()

    @check_for(Definition)
    def check_multi_line_summary_start(self, definition, docstring):
        """D21{2,3}: Multi-line docstring summary style check.

        A multi-line docstring summary should start either at the first,
        or separately at the second line of a docstring.

        """
        if docstring:
            start_triple = [
                '"""',
                "'''",
                'u"""',
                "u'''",
                'r"""',
                "r'''",
                'ur"""',
                "ur'''",
            ]

            lines = ast.literal_eval(docstring).split('\n')
            if len(lines) > 1:
                first = docstring.split("\n")[0].strip().lower()
                if first in start_triple:
                    return violations.D212()
                else:
                    return violations.D213()

    @check_for(Definition)
    def check_triple_double_quotes(self, definition, docstring):
        r'''D300: Use """triple double quotes""".

        For consistency, always use """triple double quotes""" around
        docstrings. Use r"""raw triple double quotes""" if you use any
        backslashes in your docstrings. For Unicode docstrings, use
        u"""Unicode triple-quoted strings""".

        Note: Exception to this is made if the docstring contains
              """ quotes in its body.

        '''
        if docstring:
            if '"""' in ast.literal_eval(docstring):
                # Allow ''' quotes if docstring contains """, because
                # otherwise """ quotes could not be expressed inside
                # docstring. Not in PEP 257.
                regex = re(r"[uU]?[rR]?'''[^'].*")
            else:
                regex = re(r'[uU]?[rR]?"""[^"].*')

            if not regex.match(docstring):
                illegal_matcher = re(r"""[uU]?[rR]?("+|'+).*""")
                illegal_quotes = illegal_matcher.match(docstring).group(1)
                return violations.D300(illegal_quotes)

    @check_for(Definition)
    def check_backslashes(self, definition, docstring):
        r'''D301: Use r""" if any backslashes in a docstring.

        Use r"""raw triple double quotes""" if you use any backslashes
        (\) in your docstrings.

        Exceptions are backslashes for line-continuation and unicode escape
        sequences \N... and \u... These are considered intended unescaped
        content in docstrings.
        '''
        # Just check that docstring is raw, check_triple_double_quotes
        # ensures the correct quotes.

        if (
            docstring
            and re(r'\\[^\nuN]').search(docstring)
            and not docstring.startswith(('r', 'ur'))
        ):
            return violations.D301()

    @staticmethod
    def _check_ends_with(docstring, chars, violation):
        """First line ends with one of `chars`.

        First line of the docstring should end with one of the characters in `chars`.
        `chars` supports either a `str` or an `Iterable[str]`. If the condition is
        evaluated to be false, it raises `violation`.

        """
        if docstring:
            summary_line = ast.literal_eval(docstring).strip().split('\n')[0]
            if not summary_line.endswith(chars):
                return violation(summary_line[-1])

    @check_for(Definition)
    def check_ends_with_period(self, definition, docstring):
        """D400: First line should end with a period.

        The [first line of a] docstring is a phrase ending in a period.

        """
        return self._check_ends_with(docstring, '.', violations.D400)

    @check_for(Definition)
    def check_ends_with_punctuation(self, definition, docstring):
        """D415: should end with proper punctuation.

        The [first line of a] docstring is a phrase ending in a period,
        question mark, or exclamation point

        """
        return self._check_ends_with(
            docstring, ('.', '!', '?'), violations.D415
        )

    @check_for(Function)
    def check_imperative_mood(self, function, docstring):  # def context
        """D401: First line should be in imperative mood: 'Do', not 'Does'.

        [Docstring] prescribes the function or method's effect as a command:
        ("Do this", "Return that"), not as a description; e.g. don't write
        "Returns the pathname ...".

        """
        if docstring and not function.is_test:
            stripped = ast.literal_eval(docstring).strip()
            if stripped:
                first_word = strip_non_alphanumeric(stripped.split()[0])
                check_word = first_word.lower()

                if check_word in IMPERATIVE_BLACKLIST:
                    return violations.D401b(first_word)

                correct_forms = IMPERATIVE_VERBS.get(stem(check_word))

                if correct_forms and check_word not in correct_forms:
                    best = max(
                        correct_forms,
                        key=lambda f: common_prefix_length(check_word, f),
                    )
                    return violations.D401(best.capitalize(), first_word)

    @check_for(Function)
    def check_no_signature(self, function, docstring):  # def context
        """D402: First line should not be function's or method's "signature".

        The one-line docstring should NOT be a "signature" reiterating the
        function/method parameters (which can be obtained by introspection).

        """
        if docstring:
            first_line = ast.literal_eval(docstring).strip().split('\n')[0]
            if function.name + '(' in first_line.replace(' ', ''):
                return violations.D402()

    @check_for(Function)
    def check_capitalized(self, function, docstring):
        """D403: First word of the first line should be properly capitalized.

        The [first line of a] docstring is a phrase ending in a period.

        """
        if docstring:
            first_word = ast.literal_eval(docstring).split()[0]
            if first_word == first_word.upper():
                return
            for char in first_word:
                if char not in string.ascii_letters and char != "'":
                    return
            if first_word != first_word.capitalize():
                return violations.D403(first_word.capitalize(), first_word)

    @check_for(Function)
    def check_if_needed(self, function, docstring):
        """D418: Function decorated with @overload shouldn't contain a docstring.

        Functions that are decorated with @overload are definitions,
        and are for the benefit of the type checker only,
        since they will be overwritten by the non-@overload-decorated definition.

        """
        if docstring and function.is_overload:
            return violations.D418()

    @check_for(Definition)
    def check_starts_with_this(self, function, docstring):
        """D404: First word of the docstring should not be `This`.

        Docstrings should use short, simple language. They should not begin
        with "This class is [..]" or "This module contains [..]".

        """
        if not docstring:
            return

        stripped = ast.literal_eval(docstring).strip()
        if not stripped:
            return

        first_word = strip_non_alphanumeric(stripped.split()[0])
        if first_word.lower() == 'this':
            return violations.D404()

    @staticmethod
    def _is_docstring_section(context):
        """Check if the suspected context is really a section header.

        Lets have a look at the following example docstring:
            '''Title.

            Some part of the docstring that specifies what the function
            returns. <----- Not a real section name. It has a suffix and the
                            previous line is not empty and does not end with
                            a punctuation sign.

            This is another line in the docstring. It describes stuff,
            but we forgot to add a blank line between it and the section name.
            Parameters  <-- A real section name. The previous line ends with
            ----------      a period, therefore it is in a new
                            grammatical context.
            param : int
            examples : list  <------- Not a section - previous line doesn't end
                A list of examples.   with punctuation.
            notes : list  <---------- Not a section - there's text after the
                A list of notes.      colon.

            Notes:  <--- Suspected as a context because there's a suffix to the
            -----        section, but it's a colon so it's probably a mistake.
            Bla.

            '''

        To make sure this is really a section we check these conditions:
            * There's no suffix to the section name or it's just a colon AND
            * The previous line is empty OR it ends with punctuation.

        If one of the conditions is true, we will consider the line as
        a section name.
        """
        section_name_suffix = (
            context.line.strip().lstrip(context.section_name.strip()).strip()
        )

        section_suffix_is_only_colon = section_name_suffix == ':'

        punctuation = [',', ';', '.', '-', '\\', '/', ']', '}', ')']
        prev_line_ends_with_punctuation = any(
            context.previous_line.strip().endswith(x) for x in punctuation
        )

        this_line_looks_like_a_section_name = (
            is_blank(section_name_suffix) or section_suffix_is_only_colon
        )

        prev_line_looks_like_end_of_paragraph = (
            prev_line_ends_with_punctuation or is_blank(context.previous_line)
        )

        return (
            this_line_looks_like_a_section_name
            and prev_line_looks_like_end_of_paragraph
        )

    @classmethod
    def _check_blanks_and_section_underline(
        cls, section_name, context, indentation
    ):
        """D4{07,08,09,12,14}, D215: Section underline checks.

        Check for correct formatting for docstring sections. Checks that:
            * The line that follows the section name contains
              dashes (D40{7,8}).
            * The amount of dashes is equal to the length of the section
              name (D409).
            * The section's content does not begin in the line that follows
              the section header (D412).
            * The section has no content (D414).
            * The indentation of the dashed line is equal to the docstring's
              indentation (D215).
        """
        blank_lines_after_header = 0

        for line in context.following_lines:
            if not is_blank(line):
                break
            blank_lines_after_header += 1
        else:
            # There are only blank lines after the header.
            yield violations.D407(section_name)
            yield violations.D414(section_name)
            return

        non_empty_line = context.following_lines[blank_lines_after_header]
        dash_line_found = ''.join(set(non_empty_line.strip())) == '-'

        if not dash_line_found:
            yield violations.D407(section_name)
            if blank_lines_after_header > 0:
                yield violations.D412(section_name)
        else:
            if blank_lines_after_header > 0:
                yield violations.D408(section_name)

            if non_empty_line.strip() != "-" * len(section_name):
                yield violations.D409(
                    len(section_name),
                    section_name,
                    len(non_empty_line.strip()),
                )

            if leading_space(non_empty_line) > indentation:
                yield violations.D215(section_name)

            line_after_dashes_index = blank_lines_after_header + 1
            # If the line index after the dashes is in range (perhaps we have
            # a header + underline followed by another section header).
            if line_after_dashes_index < len(context.following_lines):
                line_after_dashes = context.following_lines[
                    line_after_dashes_index
                ]
                if is_blank(line_after_dashes):
                    rest_of_lines = context.following_lines[
                        line_after_dashes_index:
                    ]
                    if not is_blank(''.join(rest_of_lines)):
                        yield violations.D412(section_name)
                    else:
                        yield violations.D414(section_name)
            else:
                yield violations.D414(section_name)

    @classmethod
    def _check_common_section(
        cls, docstring, definition, context, valid_section_names
    ):
        """D4{05,10,11,13}, D214: Section name checks.

        Check for valid section names. Checks that:
            * The section name is properly capitalized (D405).
            * The section is not over-indented (D214).
            * There's a blank line after the section (D410, D413).
            * There's a blank line before the section (D411).

        Also yields all the errors from `_check_blanks_and_section_underline`.
        """
        indentation = cls._get_docstring_indent(definition, docstring)
        capitalized_section = context.section_name.title()

        if (
            context.section_name not in valid_section_names
            and capitalized_section in valid_section_names
        ):
            yield violations.D405(capitalized_section, context.section_name)

        if leading_space(context.line) > indentation:
            yield violations.D214(capitalized_section)

        if not context.following_lines or not is_blank(
            context.following_lines[-1]
        ):
            if context.is_last_section:
                yield violations.D413(capitalized_section)
            else:
                yield violations.D410(capitalized_section)

        if not is_blank(context.previous_line):
            yield violations.D411(capitalized_section)

        yield from cls._check_blanks_and_section_underline(
            capitalized_section, context, indentation
        )

    @classmethod
    def _check_numpy_section(cls, docstring, definition, context):
        """D406: NumPy-style section name checks.

        Check for valid section names. Checks that:
            * The section name has no superfluous suffix to it (D406).

        Additionally, also yield all violations from `_check_common_section`
        which are style-agnostic section checks.
        """
        indentation = cls._get_docstring_indent(definition, docstring)
        capitalized_section = context.section_name.title()
        yield from cls._check_common_section(
            docstring, definition, context, cls.NUMPY_SECTION_NAMES
        )
        suffix = context.line.strip().lstrip(context.section_name)
        if suffix:
            yield violations.D406(capitalized_section, context.line.strip())

        if capitalized_section == "Parameters":
            yield from cls._check_parameters_section(
                docstring, definition, context
            )

    @staticmethod
    def _check_parameters_section(docstring, definition, context):
        """D417: `Parameters` section check for numpy style.

        Check for a valid `Parameters` section. Checks that:
            * The section documents all function arguments (D417)
                except `self` or `cls` if it is a method.

        """
        docstring_args = set()
        section_level_indent = leading_space(context.line)
        # Join line continuations, then resplit by line.
        content = (
            '\n'.join(context.following_lines).replace('\\\n', '').split('\n')
        )
        for current_line, next_line in zip(content, content[1:]):
            # All parameter definitions in the Numpy parameters
            # section must be at the same indent level as the section
            # name.
            # Also, we ensure that the following line is indented,
            # and has some string, to ensure that the parameter actually
            # has a description.
            # This means, this is a parameter doc with some description
            if (
                (leading_space(current_line) == section_level_indent)
                and (
                    len(leading_space(next_line))
                    > len(leading_space(current_line))
                )
                and next_line.strip()
            ):
                # In case the parameter has type definitions, it
                # will have a colon
                if ":" in current_line:
                    parameters, parameter_type = current_line.split(":", 1)
                # Else, we simply have the list of parameters defined
                # on the current line.
                else:
                    parameters = current_line.strip()
                # Numpy allows grouping of multiple parameters of same
                # type in the same line. They are comma separated.
                parameter_list = parameters.split(",")
                for parameter in parameter_list:
                    docstring_args.add(parameter.strip())
        yield from ConventionChecker._check_missing_args(
            docstring_args, definition
        )

    @staticmethod
    def _check_args_section(docstring, definition, context):
        """D417: `Args` section checks.

        Check for a valid `Args` or `Argument` section. Checks that:
            * The section documents all function arguments (D417)
                except `self` or `cls` if it is a method.

        """
        docstring_args = set()
        for line in context.following_lines:
            match = ConventionChecker.GOOGLE_ARGS_REGEX.match(line)
            if match:
                docstring_args.add(match.group(1))
        yield from ConventionChecker._check_missing_args(
            docstring_args, definition
        )

    @staticmethod
    def _check_missing_args(docstring_args, definition):
        """D417: Yield error for missing arguments in docstring.

        Given a list of arguments found in the docstring and the
        callable definition, it checks if all the arguments of the
        callable are present in the docstring, else it yields a
        D417 with a list of missing arguments.

        """
        if isinstance(definition, Function):
            function_args = get_function_args(definition.source)
            # If the method isn't static, then we skip the first
            # positional argument as it is `cls` or `self`
            if definition.kind == 'method' and not definition.is_static:
                function_args = function_args[1:]
            # Filtering out any arguments prefixed with `_` marking them
            # as private.
            function_args = [
                arg_name
                for arg_name in function_args
                if not is_def_arg_private(arg_name)
            ]
            missing_args = set(function_args) - docstring_args
            if missing_args:
                yield violations.D417(
                    ", ".join(sorted(missing_args)), definition.name
                )

    @classmethod
    def _check_google_section(cls, docstring, definition, context):
        """D416: Google-style section name checks.

        Check for valid section names. Checks that:
            * The section does not contain any blank line between its name
              and content (D412).
            * The section is not empty (D414).
            * The section name has colon as a suffix (D416).

        Additionally, also yield all violations from `_check_common_section`
        which are style-agnostic section checks.
        """
        capitalized_section = context.section_name.title()
        yield from cls._check_common_section(
            docstring, definition, context, cls.GOOGLE_SECTION_NAMES
        )
        suffix = context.line.strip().lstrip(context.section_name)
        if suffix != ":":
            yield violations.D416(
                capitalized_section + ":", context.line.strip()
            )

        if capitalized_section in ("Args", "Arguments"):
            yield from cls._check_args_section(docstring, definition, context)

    @staticmethod
    def _get_section_contexts(lines, valid_section_names):
        """Generate `SectionContext` objects for valid sections.

        Given a list of `valid_section_names`, generate an
        `Iterable[SectionContext]` which provides:
            * Section Name
            * String value of the previous line
            * The section line
            * Following lines till the next section
            * Line index of the beginning of the section in the docstring
            * Boolean indicating whether the section is the last section.
        for each valid section.

        """
        lower_section_names = [s.lower() for s in valid_section_names]

        def _suspected_as_section(_line):
            result = get_leading_words(_line.lower())
            return result in lower_section_names

        # Finding our suspects.
        suspected_section_indices = [
            i for i, line in enumerate(lines) if _suspected_as_section(line)
        ]

        SectionContext = namedtuple(
            'SectionContext',
            (
                'section_name',
                'previous_line',
                'line',
                'following_lines',
                'original_index',
                'is_last_section',
            ),
        )

        # First - create a list of possible contexts. Note that the
        # `following_lines` member is until the end of the docstring.
        contexts = (
            SectionContext(
                get_leading_words(lines[i].strip()),
                lines[i - 1],
                lines[i],
                lines[i + 1 :],
                i,
                False,
            )
            for i in suspected_section_indices
        )

        # Now that we have manageable objects - rule out false positives.
        contexts = (
            c for c in contexts if ConventionChecker._is_docstring_section(c)
        )

        # Now we shall trim the `following lines` field to only reach the
        # next section name.
        for a, b in pairwise(contexts, None):
            end = -1 if b is None else b.original_index
            yield SectionContext(
                a.section_name,
                a.previous_line,
                a.line,
                lines[a.original_index + 1 : end],
                a.original_index,
                b is None,
            )

    def _check_numpy_sections(self, lines, definition, docstring):
        """NumPy-style docstring sections checks.

        Check the general format of a sectioned docstring:
            '''This is my one-liner.

            Short Summary
            -------------
            This is my summary.

            Returns
            -------
            None.

            '''

        Section names appear in `NUMPY_SECTION_NAMES`.
        Yields all violation from `_check_numpy_section` for each valid
        Numpy-style section.
        """
        found_any_numpy_section = False
        for ctx in self._get_section_contexts(lines, self.NUMPY_SECTION_NAMES):
            found_any_numpy_section = True
            yield from self._check_numpy_section(docstring, definition, ctx)

        return found_any_numpy_section

    def _check_google_sections(self, lines, definition, docstring):
        """Google-style docstring section checks.

        Check the general format of a sectioned docstring:
            '''This is my one-liner.

            Note:
                This is my summary.

            Returns:
                None.

            '''

        Section names appear in `GOOGLE_SECTION_NAMES`.
        Yields all violation from `_check_google_section` for each valid
        Google-style section.
        """
        for ctx in self._get_section_contexts(
            lines, self.GOOGLE_SECTION_NAMES
        ):
            yield from self._check_google_section(docstring, definition, ctx)

    @check_for(Definition)
    def check_docstring_sections(self, definition, docstring):
        """Check for docstring sections."""
        if not docstring:
            return

        lines = docstring.split("\n")
        if len(lines) < 2:
            return

        found_numpy = yield from self._check_numpy_sections(
            lines, definition, docstring
        )
        if not found_numpy:
            yield from self._check_google_sections(
                lines, definition, docstring
            )

parse = Parser()

def check(
    filenames,
    select=None,
    ignore=None,
    ignore_decorators=None,
    ignore_inline_noqa=False,
):
    """Generate docstring errors that exist in `filenames` iterable.

    By default, the PEP-257 convention is checked. To specifically define the
    set of error codes to check for, supply either `select` or `ignore` (but
    not both). In either case, the parameter should be a collection of error
    code strings, e.g., {'D100', 'D404'}.

    When supplying `select`, only specified error codes will be reported.
    When supplying `ignore`, all error codes which were not specified will be
    reported.

    Note that ignored error code refer to the entire set of possible
    error codes, which is larger than just the PEP-257 convention. To your
    convenience, you may use `pydocstyle.violations.conventions.pep257` as
    a base set to add or remove errors from.

    `ignore_inline_noqa` controls if `# noqa` comments are respected or not.

    Examples
    ---------
    >>> check(['pydocstyle.py'])
    <generator object check at 0x...>

    >>> check(['pydocstyle.py'], select=['D100'])
    <generator object check at 0x...>

    >>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
    <generator object check at 0x...>

    """
    if select is not None and ignore is not None:
        raise IllegalConfiguration(
            'Cannot pass both select and ignore. '
            'They are mutually exclusive.'
        )
    elif select is not None:
        checked_codes = select
    elif ignore is not None:
        checked_codes = list(
            set(violations.ErrorRegistry.get_error_codes()) - set(ignore)
        )
    else:
        checked_codes = violations.conventions.pep257

    for filename in filenames:
        log.info('Checking file %s.', filename)
        try:
            with tk.open(filename) as file:
                source = file.read()
            for error in ConventionChecker().check_source(
                source, filename, ignore_decorators, ignore_inline_noqa
            ):
                code = getattr(error, 'code', None)
                if code in checked_codes:
                    yield error
        except (OSError, AllError, ParseError) as error:
            log.warning('Error in file %s: %s', filename, error)
            yield error
        except tk.TokenError:
            yield SyntaxError('invalid syntax in file %s' % filename)

def is_ascii(string):
    """Return a boolean indicating if `string` only has ascii characters."""
    return all(ord(char) < 128 for char in string)

def leading_space(string):
    """Return any leading space from `string`."""
    return re(r'\s*').match(string).group()

def get_leading_words(line):
    """Return any leading set of words from `line`.

    For example, if `line` is "  Hello world!!!", returns "Hello world".
    """
    result = re(r"[\w ]+").match(line.strip())
    if result is not None:
        return result.group()

def is_def_arg_private(arg_name):
    """Return a boolean indicating if the argument name is private."""
    return arg_name.startswith("_")

def get_function_args(function_source):
    """Return the function arguments given the source-code string."""
    # We are stripping the whitespace from the left of the
    # function source.
    # This is so that if the docstring has incorrectly
    # indented lines, which are at a lower indent than the
    # function source, we still dedent the source correctly
    # and the AST parser doesn't throw an error.
    try:
        function_arg_node = ast.parse(function_source.lstrip()).body[0].args
    except SyntaxError:
        # If we still get a syntax error, we don't want the
        # the checker to crash. Instead we just return a blank list.
        return []
    arg_nodes = function_arg_node.args
    kwonly_arg_nodes = function_arg_node.kwonlyargs
    return [arg_node.arg for arg_node in chain(arg_nodes, kwonly_arg_nodes)]


text:
package android.os.cts;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;

public class CountDownTimerTestStub extends Activity {
    public boolean onFinished;
    public ArrayList<Long> tickTimes;

    public final long MILLISINFUTURE = 4500;
    public final long INTERVAL = 1000;
    public CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tickTimes = new ArrayList<Long>();
        countDownTimer = new CountDownTimer(MILLISINFUTURE, INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                tickTimes.add(System.currentTimeMillis());
            }

            @Override
            public void onFinish() {
                onFinished = true;
            }
        };
    }

}

redpajama_set_name: RedPajamaGithub


text:
layout: author
authorid: preetum
---

I am a first-year PhD student at Harvard, and did my undergrad at UC Berkeley.
I'm generally interested in many theory things (complexity / cryptography /
etc).
[Website](http://preetum.nakkiran.org/).


text:
"""Test the VF2Layout pass"""

import retworkx

from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import ControlFlowOp
from qiskit.transpiler import CouplingMap, Layout, TranspilerError
from qiskit.transpiler.passes.layout import vf2_utils
from qiskit.transpiler.passes.layout.vf2_post_layout import VF2PostLayout, VF2PostLayoutStopReason
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeLima, FakeYorktown, FakeLimaV2, FakeYorktownV2
from qiskit.circuit import Qubit
from qiskit.compiler.transpiler import transpile

class TestVF2PostLayout(QiskitTestCase):
    """Tests the VF2Layout pass"""

    seed = 42

    def assertLayout(self, dag, coupling_map, property_set):
        """Checks if the circuit in dag was a perfect layout in property_set for the given
        coupling_map"""
        self.assertEqual(
            property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
        )

        layout = property_set["post_layout"]
        edges = coupling_map.graph.edge_list()

        def run(dag, wire_map):
            for gate in dag.two_qubit_ops():
                if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
                    continue
                physical_q0 = wire_map[gate.qargs[0]]
                physical_q1 = wire_map[gate.qargs[1]]
                self.assertTrue((physical_q0, physical_q1) in edges)
            for node in dag.op_nodes(ControlFlowOp):
                for block in node.op.blocks:
                    inner_wire_map = {
                        inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
                    }
                    run(circuit_to_dag(block), inner_wire_map)

        run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout})

    def assertLayoutV2(self, dag, target, property_set):
        """Checks if the circuit in dag was a perfect layout in property_set for the given
        coupling_map"""
        self.assertEqual(
            property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
        )

        layout = property_set["post_layout"]

        def run(dag, wire_map):
            for gate in dag.two_qubit_ops():
                if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
                    continue
                physical_q0 = wire_map[gate.qargs[0]]
                physical_q1 = wire_map[gate.qargs[1]]
                qargs = (physical_q0, physical_q1)
                self.assertTrue(target.instruction_supported(gate.name, qargs))
            for node in dag.op_nodes(ControlFlowOp):
                for block in node.op.blocks:
                    inner_wire_map = {
                        inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
                    }
                    run(circuit_to_dag(block), inner_wire_map)

        run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout})

    def test_no_constraints(self):
        """Test we raise at runtime if no target or coupling graph specified."""
        qc = QuantumCircuit(2)
        empty_pass = VF2PostLayout()
        with self.assertRaises(TranspilerError):
            empty_pass.run(circuit_to_dag(qc))

    def test_no_backend_properties(self):
        """Test we raise at runtime if no properties are provided with a coupling graph."""
        qc = QuantumCircuit(2)
        empty_pass = VF2PostLayout(coupling_map=CouplingMap([(0, 1), (1, 2)]))
        with self.assertRaises(TranspilerError):
            empty_pass.run(circuit_to_dag(qc))

    def test_empty_circuit(self):
        """Test no solution found for empty circuit"""
        qc = QuantumCircuit(2, 2)
        backend = FakeLima()
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"],
            VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
        )

    def test_empty_circuit_v2(self):
        """Test no solution found for empty circuit with v2 backend"""
        qc = QuantumCircuit(2, 2)
        backend = FakeLimaV2()
        vf2_pass = VF2PostLayout(target=backend.target)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"],
            VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
        )

    def test_skip_3q_circuit(self):
        """Test that the pass is a no-op on circuits with >2q gates."""
        qc = QuantumCircuit(3)
        qc.ccx(0, 1, 2)
        backend = FakeLima()
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
        )

    def test_skip_3q_circuit_control_flow(self):
        """Test that the pass is a no-op on circuits with >2q gates."""
        qc = QuantumCircuit(3)
        with qc.for_loop((1,)):
            qc.ccx(0, 1, 2)
        backend = FakeLima()
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
        )

    def test_skip_3q_circuit_v2(self):
        """Test that the pass is a no-op on circuits with >2q gates with a target."""
        qc = QuantumCircuit(3)
        qc.ccx(0, 1, 2)
        backend = FakeLimaV2()
        vf2_pass = VF2PostLayout(target=backend.target)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
        )

    def test_skip_3q_circuit_control_flow_v2(self):
        """Test that the pass is a no-op on circuits with >2q gates with a target."""
        qc = QuantumCircuit(3)
        with qc.for_loop((1,)):
            qc.ccx(0, 1, 2)
        backend = FakeLimaV2()
        vf2_pass = VF2PostLayout(target=backend.target)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
        )

    def test_best_mapping_ghz_state_full_device_multiple_qregs(self):
        """Test best mappings with multiple registers"""
        backend = FakeLima()
        qr_a = QuantumRegister(2)
        qr_b = QuantumRegister(3)
        qc = QuantumCircuit(qr_a, qr_b)
        qc.h(qr_a[0])
        qc.cx(qr_a[0], qr_a[1])
        qc.cx(qr_a[0], qr_b[0])
        qc.cx(qr_a[0], qr_b[1])
        qc.cx(qr_a[0], qr_b[2])
        qc.measure_all()
        tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial")
        initial_layout = tqc._layout
        dag = circuit_to_dag(tqc)
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed)
        pass_.run(dag)
        self.assertLayout(dag, cmap, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)

    def test_2q_circuit_5q_backend(self):
        """A simple example, without considering the direction
          0 - 1
        qr1 - qr0
        """
        backend = FakeYorktown()

        qr = QuantumRegister(2, "qr")
        circuit = QuantumCircuit(qr)
        circuit.cx(qr[1], qr[0])  # qr1 -> qr0
        tqc = transpile(circuit, backend, layout_method="dense")
        initial_layout = tqc._layout
        dag = circuit_to_dag(tqc)
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed)
        pass_.run(dag)
        self.assertLayout(dag, cmap, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)

    def test_2q_circuit_5q_backend_controlflow(self):
        """A simple example, without considering the direction
          0 - 1
        qr1 - qr0
        """
        backend = FakeYorktown()

        circuit = QuantumCircuit(2, 1)
        with circuit.for_loop((1,)):
            circuit.cx(1, 0)  # qr1 -> qr0
        with circuit.if_test((circuit.clbits[0], True)) as else_:
            pass
        with else_:
            with circuit.while_loop((circuit.clbits[0], True)):
                circuit.cx(1, 0)  # qr1 -> qr0
        initial_layout = Layout(dict(enumerate(circuit.qubits)))
        circuit._layout = initial_layout
        dag = circuit_to_dag(circuit)
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed)
        pass_.run(dag)
        self.assertLayout(dag, cmap, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)

    def test_best_mapping_ghz_state_full_device_multiple_qregs_v2(self):
        """Test best mappings with multiple registers"""
        backend = FakeLimaV2()
        qr_a = QuantumRegister(2)
        qr_b = QuantumRegister(3)
        qc = QuantumCircuit(qr_a, qr_b)
        qc.h(qr_a[0])
        qc.cx(qr_a[0], qr_a[1])
        qc.cx(qr_a[0], qr_b[0])
        qc.cx(qr_a[0], qr_b[1])
        qc.cx(qr_a[0], qr_b[2])
        qc.measure_all()
        tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial")
        initial_layout = tqc._layout
        dag = circuit_to_dag(tqc)
        pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
        pass_.run(dag)
        self.assertLayoutV2(dag, backend.target, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)

    def test_2q_circuit_5q_backend_v2(self):
        """A simple example, without considering the direction
          0 - 1
        qr1 - qr0
        """
        backend = FakeYorktownV2()

        qr = QuantumRegister(2, "qr")
        circuit = QuantumCircuit(qr)
        circuit.cx(qr[1], qr[0])  # qr1 -> qr0
        tqc = transpile(circuit, backend, layout_method="dense")
        initial_layout = tqc._layout
        dag = circuit_to_dag(tqc)
        pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
        pass_.run(dag)
        self.assertLayoutV2(dag, backend.target, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)

    def test_2q_circuit_5q_backend_v2_control_flow(self):
        """A simple example, without considering the direction
          0 - 1
        qr1 - qr0
        """
        backend = FakeYorktownV2()

        circuit = QuantumCircuit(2, 1)
        with circuit.for_loop((1,)):
            circuit.cx(1, 0)  # qr1 -> qr0
        with circuit.if_test((circuit.clbits[0], True)) as else_:
            pass
        with else_:
            with circuit.while_loop((circuit.clbits[0], True)):
                circuit.cx(1, 0)  # qr1 -> qr0
        initial_layout = Layout(dict(enumerate(circuit.qubits)))
        circuit._layout = initial_layout
        dag = circuit_to_dag(circuit)
        pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
        pass_.run(dag)
        self.assertLayoutV2(dag, backend.target, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)

    def test_target_invalid_2q_gate(self):
        """Test that we don't find a solution with a gate outside target."""
        backend = FakeYorktownV2()
        qc = QuantumCircuit(2)
        qc.ecr(0, 1)
        dag = circuit_to_dag(qc)
        pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
        pass_.run(dag)
        self.assertEqual(
            pass_.property_set["VF2PostLayout_stop_reason"],
            VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
        )

    def test_target_invalid_2q_gate_control_flow(self):
        """Test that we don't find a solution with a gate outside target."""
        backend = FakeYorktownV2()
        qc = QuantumCircuit(2)
        with qc.for_loop((1,)):
            qc.ecr(0, 1)
        dag = circuit_to_dag(qc)
        pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
        pass_.run(dag)
        self.assertEqual(
            pass_.property_set["VF2PostLayout_stop_reason"],
            VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
        )

class TestVF2PostLayoutScoring(QiskitTestCase):
    """Test scoring heuristic function for VF2PostLayout."""

    def test_empty_score(self):
        """Test error rate is 0 for empty circuit."""
        bit_map = {}
        reverse_bit_map = {}
        im_graph = retworkx.PyDiGraph()
        backend = FakeYorktownV2()
        vf2_pass = VF2PostLayout(target=backend.target)
        layout = Layout()
        score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph)
        self.assertEqual(0, score)

    def test_all_1q_score(self):
        """Test error rate for all 1q input."""
        bit_map = {Qubit(): 0, Qubit(): 1}
        reverse_bit_map = {v: k for k, v in bit_map.items()}
        im_graph = retworkx.PyDiGraph()
        im_graph.add_node({"sx": 1})
        im_graph.add_node({"sx": 1})
        backend = FakeYorktownV2()
        vf2_pass = VF2PostLayout(target=backend.target)
        layout = Layout(bit_map)
        score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph)
        self.assertAlmostEqual(0.002925, score, places=5)

    def test_all_1q_avg_score(self):
        """Test average scoring for all 1q input."""
        bit_map = {Qubit(): 0, Qubit(): 1}
        reverse_bit_map = {v: k for k, v in bit_map.items()}
        im_graph = retworkx.PyDiGraph()
        im_graph.add_node({"sx": 1})
        im_graph.add_node({"sx": 1})
        backend = FakeYorktownV2()
        vf2_pass = VF2PostLayout(target=backend.target)
        vf2_pass.avg_error_map = vf2_utils.build_average_error_map(
            vf2_pass.target, vf2_pass.properties, vf2_pass.coupling_map
        )
        layout = Layout(bit_map)
        score = vf2_utils.score_layout(
            vf2_pass.avg_error_map, layout, bit_map, reverse_bit_map, im_graph
        )
        self.assertAlmostEqual(0.02054, score, places=5)

class TestVF2PostLayoutUndirected(QiskitTestCase):
    """Tests the VF2Layout pass"""

    seed = 42

    def assertLayout(self, dag, coupling_map, property_set):
        """Checks if the circuit in dag was a perfect layout in property_set for the given
        coupling_map"""
        self.assertEqual(
            property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
        )

        layout = property_set["post_layout"]
        for gate in dag.two_qubit_ops():
            if dag.has_calibration_for(gate):
                continue
            physical_q0 = layout[gate.qargs[0]]
            physical_q1 = layout[gate.qargs[1]]
            self.assertTrue(coupling_map.graph.has_edge(physical_q0, physical_q1))

    def assertLayoutV2(self, dag, target, property_set):
        """Checks if the circuit in dag was a perfect layout in property_set for the given
        coupling_map"""
        self.assertEqual(
            property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
        )

        layout = property_set["post_layout"]
        for gate in dag.two_qubit_ops():
            if dag.has_calibration_for(gate):
                continue
            physical_q0 = layout[gate.qargs[0]]
            physical_q1 = layout[gate.qargs[1]]
            qargs = (physical_q0, physical_q1)
            self.assertTrue(target.instruction_supported(gate.name, qargs))

    def test_no_constraints(self):
        """Test we raise at runtime if no target or coupling graph specified."""
        qc = QuantumCircuit(2)
        empty_pass = VF2PostLayout(strict_direction=False)
        with self.assertRaises(TranspilerError):
            empty_pass.run(circuit_to_dag(qc))

    def test_no_backend_properties(self):
        """Test we raise at runtime if no properties are provided with a coupling graph."""
        qc = QuantumCircuit(2)
        empty_pass = VF2PostLayout(
            coupling_map=CouplingMap([(0, 1), (1, 2)]), strict_direction=False
        )
        with self.assertRaises(TranspilerError):
            empty_pass.run(circuit_to_dag(qc))

    def test_empty_circuit(self):
        """Test no solution found for empty circuit"""
        qc = QuantumCircuit(2, 2)
        backend = FakeLima()
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"],
            VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
        )

    def test_empty_circuit_v2(self):
        """Test no solution found for empty circuit with v2 backend"""
        qc = QuantumCircuit(2, 2)
        backend = FakeLimaV2()
        vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"],
            VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
        )

    def test_skip_3q_circuit(self):
        """Test that the pass is a no-op on circuits with >2q gates."""
        qc = QuantumCircuit(3)
        qc.ccx(0, 1, 2)
        backend = FakeLima()
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
        )

    def test_skip_3q_circuit_v2(self):
        """Test that the pass is a no-op on circuits with >2q gates with a target."""
        qc = QuantumCircuit(3)
        qc.ccx(0, 1, 2)
        backend = FakeLimaV2()
        vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False)
        vf2_pass.run(circuit_to_dag(qc))
        self.assertEqual(
            vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
        )

    def test_best_mapping_ghz_state_full_device_multiple_qregs(self):
        """Test best mappings with multiple registers"""
        backend = FakeLima()
        qr_a = QuantumRegister(2)
        qr_b = QuantumRegister(3)
        qc = QuantumCircuit(qr_a, qr_b)
        qc.h(qr_a[0])
        qc.cx(qr_a[0], qr_a[1])
        qc.cx(qr_a[0], qr_b[0])
        qc.cx(qr_a[0], qr_b[1])
        qc.cx(qr_a[0], qr_b[2])
        qc.measure_all()
        tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial")
        initial_layout = tqc._layout
        dag = circuit_to_dag(tqc)
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        pass_ = VF2PostLayout(
            coupling_map=cmap, properties=props, seed=self.seed, strict_direction=False
        )
        pass_.run(dag)
        self.assertLayout(dag, cmap, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)

    def test_2q_circuit_5q_backend(self):
        """A simple example, without considering the direction
          0 - 1
        qr1 - qr0
        """
        backend = FakeYorktown()

        qr = QuantumRegister(2, "qr")
        circuit = QuantumCircuit(qr)
        circuit.cx(qr[1], qr[0])  # qr1 -> qr0
        tqc = transpile(circuit, backend, layout_method="dense")
        initial_layout = tqc._layout
        dag = circuit_to_dag(tqc)
        cmap = CouplingMap(backend.configuration().coupling_map)
        props = backend.properties()
        pass_ = VF2PostLayout(
            coupling_map=cmap, properties=props, seed=self.seed, strict_direction=False
        )
        pass_.run(dag)
        self.assertLayout(dag, cmap, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)

    def test_best_mapping_ghz_state_full_device_multiple_qregs_v2(self):
        """Test best mappings with multiple registers"""
        backend = FakeLimaV2()
        qr_a = QuantumRegister(2)
        qr_b = QuantumRegister(3)
        qc = QuantumCircuit(qr_a, qr_b)
        qc.h(qr_a[0])
        qc.cx(qr_a[0], qr_a[1])
        qc.cx(qr_a[0], qr_b[0])
        qc.cx(qr_a[0], qr_b[1])
        qc.cx(qr_a[0], qr_b[2])
        qc.measure_all()
        tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial")
        initial_layout = tqc._layout
        dag = circuit_to_dag(tqc)
        pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False)
        pass_.run(dag)
        self.assertLayoutV2(dag, backend.target, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)

    def test_2q_circuit_5q_backend_v2(self):
        """A simple example, without considering the direction
          0 - 1
        qr1 - qr0
        """
        backend = FakeYorktownV2()

        qr = QuantumRegister(2, "qr")
        circuit = QuantumCircuit(qr)
        circuit.cx(qr[1], qr[0])  # qr1 -> qr0
        tqc = transpile(circuit, backend, layout_method="dense")
        initial_layout = tqc._layout
        dag = circuit_to_dag(tqc)
        pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False)
        pass_.run(dag)
        self.assertLayoutV2(dag, backend.target, pass_.property_set)
        self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)


text:
<?xml version="1.0" ?>
<INPUT>

	<MEDALS>
		<MEDAL Id="1" MEDAL_THRESHOLD="52000" TYPE="Gold"/>
		<MEDAL Id="2" MEDAL_THRESHOLD="79000" TYPE="Silver"/>
		<MEDAL Id="3" MEDAL_THRESHOLD="102000" TYPE="Bronze"/>

	</MEDALS>

	<SpeedSettings Default="18" Max="150" Min="0"/>

	<PenaltySettings SpeedLost="0.1" TimeLost="15"/>

	<PROBLEM_SET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="String">
				<ContentSettings string="1.5"/>
			</TARGET>
			<QUESTION INDEX="1">
				<Content TYPE="Fraction">
					<ContentSettings denominator="5" numerator="1" whole="1"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="12" numerator="9" whole="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="2">
				<Content TYPE="Fraction">
					<ContentSettings denominator="3" numerator="1"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="5" numerator="2"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="3">
				<Content TYPE="Fraction">
					<ContentSettings denominator="100" numerator="82"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="5" numerator="4" whole="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="String">
				<ContentSettings string="0.75"/>
			</TARGET>
			<QUESTION INDEX="4">
				<Content TYPE="Fraction">
					<ContentSettings denominator="8" numerator="2"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="5" numerator="1" whole="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="5">
				<Content TYPE="Fraction">
					<ContentSettings denominator="100" numerator="11"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="5" numerator="1"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="6">
				<Content TYPE="Fraction">
					<ContentSettings denominator="3" numerator="0"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="8" numerator="5" whole="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="String">
				<ContentSettings string="1.5"/>
			</TARGET>
			<QUESTION INDEX="7">
				<Content TYPE="Fraction">
					<ContentSettings denominator="3" numerator="2" whole="1"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="8" numerator="7" whole="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="8">
				<Content TYPE="Fraction">
					<ContentSettings denominator="12" numerator="0"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="8" numerator="6" whole="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="9">
				<Content TYPE="Fraction">
					<ContentSettings denominator="1000" numerator="29"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="4" numerator="4"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="String">
				<ContentSettings string="0.9"/>
			</TARGET>
			<QUESTION INDEX="10">
				<Content TYPE="Fraction">
					<ContentSettings denominator="10" numerator="3" whole="1"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="2" numerator="1" whole="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="11">
				<Content TYPE="Fraction">
					<ContentSettings denominator="8" numerator="0"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="4" numerator="3" whole="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="12">
				<Content TYPE="Fraction">
					<ContentSettings denominator="1000" numerator="801" whole="1"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="12" numerator="10" whole="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="String">
				<ContentSettings string="1.2"/>
			</TARGET>
			<QUESTION INDEX="13">
				<Content TYPE="Fraction">
					<ContentSettings denominator="4" numerator="2"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="12" numerator="7" whole="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="14">
				<Content TYPE="Fraction">
					<ContentSettings denominator="1000" numerator="548"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="1000" numerator="647" whole="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="15">
				<Content TYPE="Fraction">
					<ContentSettings denominator="100" numerator="55"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="12" numerator="11"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="String">
				<ContentSettings string="0.5"/>
			</TARGET>
			<QUESTION INDEX="16">
				<Content TYPE="Fraction">
					<ContentSettings denominator="3" numerator="0"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="2" numerator="2"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="17">
				<Content TYPE="Fraction">
					<ContentSettings denominator="12" numerator="3" whole="1"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="3" numerator="1" whole="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="18">
				<Content TYPE="Fraction">
					<ContentSettings denominator="10" numerator="0"/>
				</Content>
				<Content TYPE="Fraction">
					<ContentSettings denominator="10" numerator="8" whole="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
		</PROBLEM_SUBSET>

	</PROBLEM_SET>

</INPUT>


text:
<?php

namespace Droid\Plugin\{{classname}}\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class {{classname}}ExampleCommand extends Command
{
    public function configure()
    {
        $this
            ->setName('{{name}}:example')
            ->setDescription('This is an example command')
            ->addArgument(
                'message',
                InputArgument::REQUIRED,
                'Message to output'
            )
            ->addOption(
                'color',
                'c',
                InputOption::VALUE_REQUIRED,
                'Set color of the output'
            )
        ;
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeLn("{{classname}} Example: " . $input->getArgument('message') . " @ " . $input->getOption('color'));
    }
}


text:
<?php
/**
 * pet.find test
 *
 * @package Petfinder
 * @subpackage Tests
 * @author Eric
 */
namespace SalernoLabs\Tests\Petfinder\Requests\Pet;

class FindTest extends \PHPUnit\Framework\TestCase
{
    use \SalernoLabs\Tests\Petfinder\Traits\TestHelper;

    /**
     * Test the query
     *
     * @throws \SalernoLabs\Petfinder\Exceptions\Exception
     * @dataProvider queryDataProvider
     */
    public function testQuery($age, $animal, $zip)
    {
        $query = new \SalernoLabs\Petfinder\Requests\Pet\Find($this->configuration);

        $data = $query
            ->setAge($age)
            ->setAnimal($animal)
            ->setLocation($zip)
            ->setCount(10)
            ->execute();

        $this->assertInstanceOf('\SalernoLabs\Petfinder\Responses\PetList', $data);
        $this->assertNotEmpty($data->pets);
        $this->assertLessThanOrEqual(10, $data->count);
    }

    /**
     * @return array
     */
    public function queryDataProvider()
    {
        return [
            ['Young', 'bird', '10014'],
            ['Adult', 'cat', '90210'],
            ['Senior', 'dog', '45255']
        ];
    }
}


text:
.class Landroid/widget/ListPopupWindow$PopupScrollListener;
.super Ljava/lang/Object;
.source "ListPopupWindow.java"

# interfaces
.implements Landroid/widget/AbsListView$OnScrollListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/ListPopupWindow;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "PopupScrollListener"
.end annotation

# instance fields
.field final synthetic this$0:Landroid/widget/ListPopupWindow;

# direct methods
.method private constructor <init>(Landroid/widget/ListPopupWindow;)V
    .locals 0
    .parameter

    .prologue
    .line 1341
    iput-object p1, p0, Landroid/widget/ListPopupWindow$PopupScrollListener;->this$0:Landroid/widget/ListPopupWindow;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/widget/ListPopupWindow;Landroid/widget/ListPopupWindow$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 1341
    invoke-direct {p0, p1}, Landroid/widget/ListPopupWindow$PopupScrollListener;-><init>(Landroid/widget/ListPopupWindow;)V

    return-void
.end method

# virtual methods
.method public onScroll(Landroid/widget/AbsListView;III)V
    .locals 0
    .parameter "view"
    .parameter "firstVisibleItem"
    .parameter "visibleItemCount"
    .parameter "totalItemCount"

    .prologue
    .line 1345
    return-void
.end method

.method public onScrollStateChanged(Landroid/widget/AbsListView;I)V
    .locals 2
    .parameter "view"
    .parameter "scrollState"

    .prologue
    .line 1348
    const/4 v0, 0x1

    if-ne p2, v0, :cond_0

    iget-object v0, p0, Landroid/widget/ListPopupWindow$PopupScrollListener;->this$0:Landroid/widget/ListPopupWindow;

    invoke-virtual {v0}, Landroid/widget/ListPopupWindow;->isInputMethodNotNeeded()Z

    move-result v0

    if-nez v0, :cond_0

    iget-object v0, p0, Landroid/widget/ListPopupWindow$PopupScrollListener;->this$0:Landroid/widget/ListPopupWindow;

    #getter for: Landroid/widget/ListPopupWindow;->mPopup:Landroid/widget/PopupWindow;
    invoke-static {v0}, Landroid/widget/ListPopupWindow;->access$800(Landroid/widget/ListPopupWindow;)Landroid/widget/PopupWindow;

    move-result-object v0

    invoke-virtual {v0}, Landroid/widget/PopupWindow;->getContentView()Landroid/view/View;

    move-result-object v0

    if-eqz v0, :cond_0

    .line 1350
    iget-object v0, p0, Landroid/widget/ListPopupWindow$PopupScrollListener;->this$0:Landroid/widget/ListPopupWindow;

    #getter for: Landroid/widget/ListPopupWindow;->mHandler:Landroid/os/Handler;
    invoke-static {v0}, Landroid/widget/ListPopupWindow;->access$1000(Landroid/widget/ListPopupWindow;)Landroid/os/Handler;

    move-result-object v0

    iget-object v1, p0, Landroid/widget/ListPopupWindow$PopupScrollListener;->this$0:Landroid/widget/ListPopupWindow;

    #getter for: Landroid/widget/ListPopupWindow;->mResizePopupRunnable:Landroid/widget/ListPopupWindow$ResizePopupRunnable;
    invoke-static {v1}, Landroid/widget/ListPopupWindow;->access$900(Landroid/widget/ListPopupWindow;)Landroid/widget/ListPopupWindow$ResizePopupRunnable;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/os/Handler;->removeCallbacks(Ljava/lang/Runnable;)V

    .line 1351
    iget-object v0, p0, Landroid/widget/ListPopupWindow$PopupScrollListener;->this$0:Landroid/widget/ListPopupWindow;

    #getter for: Landroid/widget/ListPopupWindow;->mResizePopupRunnable:Landroid/widget/ListPopupWindow$ResizePopupRunnable;
    invoke-static {v0}, Landroid/widget/ListPopupWindow;->access$900(Landroid/widget/ListPopupWindow;)Landroid/widget/ListPopupWindow$ResizePopupRunnable;

    move-result-object v0

    invoke-virtual {v0}, Landroid/widget/ListPopupWindow$ResizePopupRunnable;->run()V

    .line 1353
    :cond_0
    return-void
.end method


text:
package convert

import (
	"errors"

	"github.com/hashicorp/go-cty/cty"
)

// This file contains the public interface of this package, which is intended
// to be a small, convenient interface designed for easy integration into
// a hypothetical language type checker and interpreter.

// Conversion is a named function type representing a conversion from a
// value of one type to a value of another type.
//
// The source type for a conversion is always the source type given to
// the function that returned the Conversion, but there is no way to recover
// that from a Conversion value itself. If a Conversion is given a value
// that is not of its expected type (with the exception of DynamicPseudoType,
// which is always supported) then the function may panic or produce undefined
// results.
type Conversion func(in cty.Value) (out cty.Value, err error)

// GetConversion returns a Conversion between the given in and out Types if
// a safe one is available, or returns nil otherwise.
func GetConversion(in cty.Type, out cty.Type) Conversion {
	return retConversion(getConversion(in, out, false))
}

// GetConversionUnsafe returns a Conversion between the given in and out Types
// if either a safe or unsafe one is available, or returns nil otherwise.
func GetConversionUnsafe(in cty.Type, out cty.Type) Conversion {
	return retConversion(getConversion(in, out, true))
}

// Convert returns the result of converting the given value to the given type
// if an safe or unsafe conversion is available, or returns an error if such a
// conversion is impossible.
//
// This is a convenience wrapper around calling GetConversionUnsafe and then
// immediately passing the given value to the resulting function.
func Convert(in cty.Value, want cty.Type) (cty.Value, error) {
	if in.Type().Equals(want) {
		return in, nil
	}

	conv := GetConversionUnsafe(in.Type(), want)
	if conv == nil {
		return cty.NilVal, errors.New(MismatchMessage(in.Type(), want))
	}
	return conv(in)
}

// Unify attempts to find the most general type that can be converted from
// all of the given types. If this is possible, that type is returned along
// with a slice of necessary conversions for some of the given types.
//
// If no common supertype can be found, this function returns cty.NilType and
// a nil slice.
//
// If a common supertype *can* be found, the returned slice will always be
// non-nil and will contain a non-nil conversion for each given type that
// needs to be converted, with indices corresponding to the input slice.
// Any given type that does *not* need conversion (because it is already of
// the appropriate type) will have a nil Conversion.
//
// cty.DynamicPseudoType is, as usual, a special case. If the given type list
// contains a mixture of dynamic and non-dynamic types, the dynamic types are
// disregarded for type selection and a conversion is returned for them that
// will attempt a late conversion of the given value to the target type,
// failing with a conversion error if the eventual concrete type is not
// compatible. If *all* given types are DynamicPseudoType, or in the
// degenerate case of an empty slice of types, the returned type is itself
// cty.DynamicPseudoType and no conversions are attempted.
func Unify(types []cty.Type) (cty.Type, []Conversion) {
	return unify(types, false)
}

// UnifyUnsafe is the same as Unify except that it may return unsafe
// conversions in situations where a safe conversion isn't also available.
func UnifyUnsafe(types []cty.Type) (cty.Type, []Conversion) {
	return unify(types, true)
}


text:
package io.techcode.logbulk.io;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigRenderOptions;
import com.typesafe.config.ConfigValue;
import io.vertx.core.json.JsonObject;

import java.util.Map;
import java.util.Set;

/**
 * This class is a app configuration container.
 */
public class AppConfig {

    // Default application reference
    public static final Config REFERENCE = ConfigFactory.defaultReference();

    // All configuration keys
    public static final String INPUT = "input";
    public static final String OUTPUT = "output";
    public static final String TRANSFORM = "transform";
    public static final String HAS_MAILBOX = "hasMailbox";
    public static final String MAILBOX = "mailbox";
    public static final String ROUTE = "route";
    public static final String ENDPOINT = "endpoint";
    public static final String FIFO = "fifo";
    public static final String INSTANCE = "instance";
    public static final String WORKER = "worker";
    public static final String STATUS = "status";
    public static final String SETTING = "setting";
    public static final String COMPONENT = "component";
    public static final String IDLE = "idle";
    public static final String THRESHOLD = "threshold";
    public static final String FALLBACK = "fallback";
    public static final String TRACING = "tracing";

    // Configuration wrapped
    private final Config config;

    /**
     * Create a new app config.
     */
    public AppConfig() {
        this.config = ConfigFactory.load().withFallback(REFERENCE);
    }

    /**
     * Gets the component section.
     *
     * @return component section.
     */
    public Set<Map.Entry<String, ConfigValue>> components() {
        return section(COMPONENT);
    }

    /**
     * Gets the setting section.
     *
     * @return setting section.
     */
    public JsonObject settings() {
        return block(SETTING);
    }

    /**
     * Gets the input section.
     *
     * @return input section.
     */
    public Set<Map.Entry<String, ConfigValue>> inputs() {
        return section(INPUT);
    }

    /**
     * Gets the output section.
     *
     * @return output section.
     */
    public Set<Map.Entry<String, ConfigValue>> outputs() {
        return section(OUTPUT);
    }

    /**
     * Gets the transform section.
     *
     * @return transform section.
     */
    public Set<Map.Entry<String, ConfigValue>> transforms() {
        return section(TRANSFORM);
    }

    /**
     * Gets the route section.
     *
     * @return route section.
     */
    public JsonObject routes() {
        return block(ROUTE);
    }

    /**
     * Gets a section route.
     *
     * @param key section key.
     * @return section.
     */
    private Set<Map.Entry<String, ConfigValue>> section(String key) {
        return config.getObject(key).entrySet();
    }

    /**
     * Gets a block route.
     *
     * @param key block key.
     * @return block.
     */
    private JsonObject block(String key) {
        return new Configuration(config.getConfig(key).root().render(ConfigRenderOptions.concise().setOriginComments(false).setJson(true)));
    }

    @Override public String toString() {
        return config.root().render(ConfigRenderOptions.concise().setOriginComments(false).setJson(false));
    }

}


text:
<?php

namespace Grid\Embed\Model\Parser\Oembed\Provider;

use Grid\Embed\Model\Parser\Oembed;
use Grid\Embed\Model\Parser\Oembed\ProviderAbstract;

/**
 * Youtube Oembed provider adapter
 *
 * @author Kristof Matos <kristof.matos@megaweb.hu>
 */
class Youtube extends ProviderAbstract
{

    /**
     * API endpoint
     */
    const API_ENDPOINT = 'http://www.youtube.com/oembed';

    /**
     * @see \Embed\Model\Parser\Oembed\ProviderAbstract::getFeedUrl()
     *
     * @param string $contentUrl
     * @return string|false
     */
    public function getFeedUrl($contentUrl)
    {
        return
            preg_match('@http://([a-z\.-]*\.)?youtube\.com/watch@i',$contentUrl)
            ? self::API_ENDPOINT
               .'?format='.$this->getFeedFormat()
               .'&url='.urlencode($contentUrl)
            : false;
    }

    /**
     * @see \Embed\Model\Parser\Oembed\ProviderAbstract::getFeedFormat()
     *
     * @return string json|xml
     */
    public function getFeedFormat()
    {
        return Oembed::FEED_FORMAT_JSON;
    }

    /**
     * Fixes Youtube embed code
     *
     * @see \Embed\Model\Parser\Oembed\ProviderAbstract::parseResponse()
     *
     * @param object $response
     */
    public function parseResponse($response)
    {
        parent::parseResponse($response);

        $regexp = '#<iframe[^>]*src="([^"]+)[^>]*>#i';
        $m = array();
        if( preg_match($regexp,$this->_embedHtml,$m) )
        {
            $src = $m[1];
            $fix = $src.(strpos($src,'?')?'&':'?').'wmode=opaque';
            $this->_embedHtml = str_replace($src, $fix, $this->_embedHtml);
        }
    }

}


text:
const int kMinUpper = 65;   // First upper case letter 'A'
const int kMaxUpper = 90;   // Last upper case letter 'Z'
const int kMinLower = 97;   // First lower case letter 'a'
const int kMaxLower = 122;  // Last lower case letter 'z'
const int kMinDigit = 48;   // First digit '0'
const int kMaxDigit = 57;   // Last digit '9'
const int kMinPasswordLength = 4;
const int kMaxPasswordLength = 15;

namespace {

// A helper function to get the length of the generated password from
// |max_length| retrieved from input password field.
int GetLengthFromHint(int max_length, int default_length) {
  if (max_length >= kMinPasswordLength && max_length <= kMaxPasswordLength)
    return max_length;
  else
    return default_length;
}

// We want the password to have uppercase, lowercase, and at least one number.
bool VerifyPassword(const std::string& password) {
  int num_lower_case = 0;
  int num_upper_case = 0;
  int num_digits = 0;

  for (size_t i = 0; i < password.size(); ++i) {
    if (password[i] >= kMinUpper && password[i] <= kMaxUpper)
      ++num_upper_case;
    if (password[i] >= kMinLower && password[i] <= kMaxLower)
      ++num_lower_case;
    if (password[i] >= kMinDigit && password[i] <= kMaxDigit)
      ++num_digits;
  }

  return num_lower_case && num_upper_case && num_digits;
}

}  // namespace

namespace autofill {

const int PasswordGenerator::kDefaultPasswordLength = 15;

void ForceFixPassword(std::string* password) {
  for (char& it : *password) {
    if (islower(it)) {
      it = base::ToUpperASCII(it);
      break;
    }
  }
  for (std::string::reverse_iterator iter = password->rbegin();
       iter != password->rend(); ++iter) {
    if (islower(*iter)) {
      *iter = base::RandInt(kMinDigit, kMaxDigit);
      break;
    }
  }
}

PasswordGenerator::PasswordGenerator(int max_length)
    : password_length_(GetLengthFromHint(max_length, kDefaultPasswordLength)) {}
PasswordGenerator::~PasswordGenerator() {}

std::string PasswordGenerator::Generate() const {
  char password[255];
  char unused_hypenated_password[255];
  // Generate passwords that have numbers and upper and lower case letters.
  // No special characters included for now.
  unsigned int mode = S_NB | S_CL | S_SL;

  // Generate the password by gen_pron_pass(), if it is not conforming then
  // force fix it.
  gen_pron_pass(password, unused_hypenated_password, password_length_,
                password_length_, mode);

  std::string str_password(password);
  if (VerifyPassword(str_password))
    return str_password;

  ForceFixPassword(&str_password);
  return str_password;
}

}  // namespace autofill


text:
//
// 此檔案是由 JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 所產生
// 請參閱 http://java.sun.com/xml/jaxb
// 一旦重新編譯來源綱要, 對此檔案所做的任何修改都將會遺失.
// 產生時間: 2015.10.20 於 10:44:08 AM CST
//

package com.netsteadfast.greenstep.base.model.dynamichql;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
anonymous complex type 的 Java 類別.
 *
 *
下列綱要片段會指定此類別中包含的預期內容.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "content"
})
@XmlRootElement(name = "query")
public class Query {

    @XmlValue
    protected String content;
    @XmlAttribute(name = "name", required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NCName")
    protected String name;

    /**
     * 取得 content 特性的值.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getContent() {
        return content;
    }

    /**
     * 設定 content 特性的值.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setContent(String value) {
        this.content = value;
    }

    /**
     * 取得 name 特性的值.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * 設定 name 特性的值.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

}


text:
module Bumpspark

  class Railtie < Rails::Railtie
    initializer "bumpspark.helper" do |app|
      require "bumpspark/helper"
      ActionView::Base.send(:include, Bumpspark::Helper)
    end
  end

end


text:
#include "SiconosMemory.hpp"
#include "BlockVector.hpp"
#include "SiconosVector.hpp"

#include <iostream>

// --- CONSTRUCTORS ---

// from data: _size
SiconosMemory::SiconosMemory(const unsigned int size, const unsigned int vectorSize)
  : MemoryContainer(),
    _nbVectorsInMemory(0),
    _indx(size-1)
{
  for (unsigned int i = 0; i < size; i++)
  {
    push_back(SiconosVector(vectorSize));
  }
}

// copy of a std::vector of siconos vectors
SiconosMemory::SiconosMemory(const MemoryContainer& V)
  : MemoryContainer(),
    _nbVectorsInMemory(V.size()),
    _indx(V.size()-1)
{
  for (unsigned int i = 0; i < V.size(); i++)
  {
    push_back(V[i]);
  }
}

// copy of a std::vector of siconos vectors  + _size
SiconosMemory::SiconosMemory(const unsigned int newMemorySize,
                             const MemoryContainer& V)
  : MemoryContainer(),
    _nbVectorsInMemory(V.size()),
    _indx(newMemorySize-1)
{
  if (newMemorySize < V.size())
    SiconosMemoryException::selfThrow(
      "SiconosMemory(int _size, vector<SP::SiconosVector> V) : V.size > _size");
  else
  {
    unsigned int i;
    for (i = 0; i < V.size(); i++)
    {
      push_back(V[i]);
    }
    for (; i < newMemorySize; i++)
    {
      push_back(SiconosVector(V[0].size()));
    }
  }
}

//Copy constructor
SiconosMemory::SiconosMemory(const SiconosMemory& Mem)
  : MemoryContainer(),
    _nbVectorsInMemory(Mem.nbVectorsInMemory()),
    _indx(Mem.getMemorySize()-1)
{
  for (unsigned int i = 0; i < Mem.getMemorySize(); i++)
  {
    push_back(Mem[i]);
  }
}

// Destructor
SiconosMemory::~SiconosMemory()
{
}

// Assignment
void SiconosMemory::operator=(const SiconosMemory& V)
{
  if (size() != V.size()) {
    this->resize(V.size());
  }
  for (unsigned int i = 0; i < V.size(); i++) {
    (*this)[i].resize(V[i].size(), true);
    (*this)[i] = V[i];
  }
  _indx = V._indx;
  _nbVectorsInMemory = V._nbVectorsInMemory;
}

// Assignment from container
void SiconosMemory::operator=(const MemoryContainer& V)
{
  _nbVectorsInMemory = V.size();
  if (V.size() > size())
    this->resize(V.size());
  _indx = size()-1;
  for (unsigned int i = 0; i < V.size(); i++)
  {
    (*this)[i].resize(V[i].size(), true);
    (*this)[i] = V[i];
  }
}

// Copy from container
void SiconosMemory::setVectorMemory(const MemoryContainer& V,
                                    MemoryContainer::size_type _size)
{
  _nbVectorsInMemory = std::min(V.size(), _size);
  if (_size > size())
    resize(_size);
  _indx = size()-1;
  for (unsigned int i = 0; i < _nbVectorsInMemory; i++)
  {
    (*this)[i].resize(V[i].size(), true);
    (*this)[i] = V[i];
  }
}

// Set the size of an existing SiconosMemory
void SiconosMemory::setMemorySize(const unsigned int steps,
                                  const unsigned int vectorSize)
{
  _nbVectorsInMemory = 0;
  _indx = steps-1;
  for (unsigned int i = 0; i < size(); i++)
  {
    this->at(i).resize(vectorSize, true);
  }
  for (unsigned int i = size(); i < steps; i++)
  {
    this->push_back(SiconosVector(vectorSize));
  }
}

// --- GETTERS/SETTERS ---

const SiconosVector& SiconosMemory::getSiconosVector(const unsigned int index) const
{
  assert(index < _nbVectorsInMemory && "getSiconosVector(index) : inconsistent index value");
  return this->at( (_indx + 1 + index) % this->size() );
}

SiconosVector& SiconosMemory::getSiconosVectorMutable(const unsigned int index)
{
  assert(index < _nbVectorsInMemory && "getSiconosVector(index) : inconsistent index value");
  return *(SiconosVector*)(&this->at( (_indx + 1 + index) % this->size() ));
}

void SiconosMemory::swap(const SiconosVector& v)
{
  // Be robust to empty memory
  if (size()==0)
    return;

  // If _nbVectorsInMemory is this->size(), we remove the last element.
  (*this)[_indx] = v;
  _nbVectorsInMemory = std::min(_nbVectorsInMemory+1, this->size());
  if (_indx > 0)
    _indx--;
  else
    _indx = this->size()-1;
}

void SiconosMemory::swap(SP::SiconosVector v)
{
  // Be robust to empty memory
  // Be robust to null pointer
  if (size()==0 || !v)
    return;

  // If _nbVectorsInMemory is this->size(), we remove the last element.
  (*this)[_indx] = *v;
  _nbVectorsInMemory = std::min(_nbVectorsInMemory+1, this->size());
  if (_indx > 0)
    _indx--;
  else
    _indx = this->size()-1;
}

void SiconosMemory::display() const
{
  std::cout << " ====== Memory vector display ======= " <<std::endl;
  std::cout << "| size : " << this->size() <<std::endl;
  std::cout << "| _nbVectorsInMemory : " << _nbVectorsInMemory <<std::endl;
  for (unsigned int i = 0; i < _nbVectorsInMemory; i++)
  {
    std::cout << "vector number " << i << ": address = "
              << &this->at(i) << " | " << std::endl;
    this->at(i).display();
  }
  std::cout << " ===================================== " <<std::endl;
}