text:
package com.github.rjeschke.txtmark;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Emitter class responsible for generating HTML output.
 *
 * @author René Jeschke <rene_jeschke@yahoo.de>
 */
public class DefaultEmitter implements Emitter
{
    /** Link references. */
    private final HashMap<String, LinkRef> linkRefs      = new HashMap<String, LinkRef>();
    /** The configuration. */
    private final Configuration            config;
    /** Extension flag. */
    public boolean                         useExtensions = false;

    /** Constructor. */
    public DefaultEmitter(final Configuration config)
    {
        this.config = config;
        this.useExtensions = config.forceExtendedProfile;
    }

    @Override
    public void setUseExtensions(boolean useExtensions) {
       this.useExtensions = useExtensions;
    }

    @Override
    public void addLinkRef(final String key, final LinkRef linkRef)
    {
        this.linkRefs.put(key.toLowerCase(), linkRef);
    }

    @Override
    public void emit(final StringBuilder out, final Block root)
    {
        root.removeSurroundingEmptyLines();

        switch (root.type)
        {
        case RULER:
            this.config.decorator.horizontalRuler(out);
            return;
        case NONE:
        case XML:
            break;
        case HEADLINE:
            this.config.decorator.openHeadline(out, root.hlDepth);
            if (this.useExtensions && root.id != null)
            {
                out.append(" id=\"");
                Utils.appendCode(out, root.id, 0, root.id.length());
                out.append('"');
            }
            out.append('>');
            break;
        case PARAGRAPH:
            this.config.decorator.openParagraph(out);
            break;
        case CODE:
        case FENCED_CODE:
            if (this.config.codeBlockEmitter == null)
            {
                this.config.decorator.openCodeBlock(out);
            }
            break;
        case BLOCKQUOTE:
            this.config.decorator.openBlockquote(out);
            break;
        case UNORDERED_LIST:
            this.config.decorator.openUnorderedList(out);
            break;
        case ORDERED_LIST:
            this.config.decorator.openOrderedList(out);
            break;
        case LIST_ITEM:
            this.config.decorator.openListItem(out);
            if (this.useExtensions && root.id != null)
            {
                out.append(" id=\"");
                Utils.appendCode(out, root.id, 0, root.id.length());
                out.append('"');
            }
            out.append('>');
            break;
        }

        if (root.hasLines())
        {
            this.emitLines(out, root);
        }
        else
        {
            Block block = root.blocks;
            while (block != null)
            {
                this.emit(out, block);
                block = block.next;
            }
        }

        switch (root.type)
        {
        case RULER:
        case NONE:
        case XML:
            break;
        case HEADLINE:
            this.config.decorator.closeHeadline(out, root.hlDepth);
            break;
        case PARAGRAPH:
            this.config.decorator.closeParagraph(out);
            break;
        case CODE:
        case FENCED_CODE:
            if (this.config.codeBlockEmitter == null)
            {
                this.config.decorator.closeCodeBlock(out);
            }
            break;
        case BLOCKQUOTE:
            this.config.decorator.closeBlockquote(out);
            break;
        case UNORDERED_LIST:
            this.config.decorator.closeUnorderedList(out);
            break;
        case ORDERED_LIST:
            this.config.decorator.closeOrderedList(out);
            break;
        case LIST_ITEM:
            this.config.decorator.closeListItem(out);
            break;
        }
    }

    /**
     * Transforms lines into HTML.
     *
     * @param out
     *            The StringBuilder to write to.
     * @param block
     *            The Block to process.
     */
    private void emitLines(final StringBuilder out, final Block block)
    {
        switch (block.type)
        {
        case CODE:
            this.emitCodeLines(out, block.lines, block.meta, true);
            break;
        case FENCED_CODE:
            this.emitCodeLines(out, block.lines, block.meta, false);
            break;
        case XML:
            this.emitRawLines(out, block.lines);
            break;
        default:
            this.emitMarkedLines(out, block.lines);
            break;
        }
    }

    /**
     * Finds the position of the given Token in the given String.
     *
     * @param in
     *            The String to search on.
     * @param start
     *            The starting character position.
     * @param token
     *            The token to find.
     * @return The position of the token or -1 if none could be found.
     */
    private int findToken(final String in, final int start, final MarkToken token)
    {
        int pos = start;
        while (pos < in.length())
        {
            if (this.getToken(in, pos) == token)
            {
                return pos;
            }
            pos++;
        }
        return -1;
    }

    /**
     * Checks if there is a valid markdown link definition.
     *
     * @param out
     *            The StringBuilder containing the generated output.
     * @param in
     *            Input String.
     * @param start
     *            Starting position.
     * @param token
     *            Either LINK or IMAGE.
     * @return The new position or -1 if there is no valid markdown link.
     */
    private int checkLink(final StringBuilder out, final String in, final int start, final MarkToken token)
    {
        boolean isAbbrev = false;
        int pos = start + (token == MarkToken.LINK ? 1 : 2);
        final StringBuilder temp = new StringBuilder();

        temp.setLength(0);
        pos = Utils.readMdLinkId(temp, in, pos);
        if (pos < start)
        {
            return -1;
        }

        final String name = temp.toString();
        String link = null, comment = null;
        final int oldPos = pos++;
        pos = Utils.skipSpaces(in, pos);
        if (pos < start)
        {
            final LinkRef lr = this.linkRefs.get(name.toLowerCase());
            if (lr != null)
            {
                isAbbrev = lr.isAbbrev;
                link = lr.link;
                comment = lr.title;
                pos = oldPos;
            }
            else
            {
                return -1;
            }
        }
        else if (in.charAt(pos) == '(')
        {
            pos++;
            pos = Utils.skipSpaces(in, pos);
            if (pos < start)
            {
                return -1;
            }
            temp.setLength(0);
            final boolean useLt = in.charAt(pos) == '<';
            pos = useLt ? Utils.readUntil(temp, in, pos + 1, '>') : Utils.readMdLink(temp, in, pos);
            if (pos < start)
            {
                return -1;
            }
            if (useLt)
            {
                pos++;
            }
            link = temp.toString();

            if (in.charAt(pos) == ' ')
            {
                pos = Utils.skipSpaces(in, pos);
                if (pos > start && in.charAt(pos) == '"')
                {
                    pos++;
                    temp.setLength(0);
                    pos = Utils.readUntil(temp, in, pos, '"');
                    if (pos < start)
                    {
                        return -1;
                    }
                    comment = temp.toString();
                    pos++;
                    pos = Utils.skipSpaces(in, pos);
                    if (pos == -1)
                    {
                        return -1;
                    }
                }
            }
            if (in.charAt(pos) != ')')
            {
                return -1;
            }
        }
        else if (in.charAt(pos) == '[')
        {
            pos++;
            temp.setLength(0);
            pos = Utils.readRawUntil(temp, in, pos, ']');
            if (pos < start)
            {
                return -1;
            }
            final String id = temp.length() > 0 ? temp.toString() : name;
            final LinkRef lr = this.linkRefs.get(id.toLowerCase());
            if (lr != null)
            {
                link = lr.link;
                comment = lr.title;
            }
        }
        else
        {
            final LinkRef lr = this.linkRefs.get(name.toLowerCase());
            if (lr != null)
            {
                isAbbrev = lr.isAbbrev;
                link = lr.link;
                comment = lr.title;
                pos = oldPos;
            }
            else
            {
                return -1;
            }
        }

        if (link == null)
        {
            return -1;
        }

        if (token == MarkToken.LINK)
        {
            if (isAbbrev && comment != null)
            {
                if (!this.useExtensions)
                {
                    return -1;
                }
                out.append("<abbr title=\"");
                Utils.appendValue(out, comment, 0, comment.length());
                out.append("\">");
                this.recursiveEmitLine(out, name, 0, MarkToken.NONE);
                out.append("</abbr>");
            }
            else
            {
                this.config.decorator.openLink(out);
                out.append(" href=\"");
                Utils.appendValue(out, link, 0, link.length());
                out.append('"');
                if (comment != null)
                {
                    out.append(" title=\"");
                    Utils.appendValue(out, comment, 0, comment.length());
                    out.append('"');
                }
                out.append('>');
                this.recursiveEmitLine(out, name, 0, MarkToken.NONE);
                this.config.decorator.closeLink(out);
            }
        }
        else
        {
            this.config.decorator.openImage(out);
            out.append(" src=\"");
            Utils.appendValue(out, link, 0, link.length());
            out.append("\" alt=\"");
            Utils.appendValue(out, name, 0, name.length());
            out.append('"');
            if (comment != null)
            {
                out.append(" title=\"");
                Utils.appendValue(out, comment, 0, comment.length());
                out.append('"');
            }
            this.config.decorator.closeImage(out);
        }

        return pos;
    }

    /**
     * Check if there is a valid HTML tag here. This method also transforms auto
     * links and mailto auto links.
     *
     * @param out
     *            The StringBuilder to write to.
     * @param in
     *            Input String.
     * @param start
     *            Starting position.
     * @return The new position or -1 if nothing valid has been found.
     */
    private int checkHtml(final StringBuilder out, final String in, final int start)
    {
        final StringBuilder temp = new StringBuilder();
        int pos;

        // Check for auto links
        temp.setLength(0);
        pos = Utils.readUntil(temp, in, start + 1, ':', ' ', '>', '\n');
        if (pos != -1 && in.charAt(pos) == ':' && HTML.isLinkPrefix(temp.toString()))
        {
            pos = Utils.readUntil(temp, in, pos, '>');
            if (pos != -1)
            {
                final String link = temp.toString();
                this.config.decorator.openLink(out);
                out.append(" href=\"");
                Utils.appendValue(out, link, 0, link.length());
                out.append("\">");
                Utils.appendValue(out, link, 0, link.length());
                this.config.decorator.closeLink(out);
                return pos;
            }
        }

        // Check for mailto auto link
        temp.setLength(0);
        pos = Utils.readUntil(temp, in, start + 1, '@', ' ', '>', '\n');
        if (pos != -1 && in.charAt(pos) == '@')
        {
            pos = Utils.readUntil(temp, in, pos, '>');
            if (pos != -1)
            {
                final String link = temp.toString();
                this.config.decorator.openLink(out);
                out.append(" href=\"");
                Utils.appendMailto(out, "mailto:", 0, 7);
                Utils.appendMailto(out, link, 0, link.length());
                out.append("\">");
                Utils.appendMailto(out, link, 0, link.length());
                this.config.decorator.closeLink(out);
                return pos;
            }
        }

        // Check for inline html
        if (start + 2 < in.length())
        {
            temp.setLength(0);
            return Utils.readXML(out, in, start, this.config.safeMode);
        }

        return -1;
    }

    /**
     * Check if this is a valid XML/HTML entity.
     *
     * @param out
     *            The StringBuilder to write to.
     * @param in
     *            Input String.
     * @param start
     *            Starting position
     * @return The new position or -1 if this entity in invalid.
     */
    private static int checkEntity(final StringBuilder out, final String in, final int start)
    {
        final int pos = Utils.readUntil(out, in, start, ';');
        if (pos < 0 || out.length() < 3)
        {
            return -1;
        }
        if (out.charAt(1) == '#')
        {
            if (out.charAt(2) == 'x' || out.charAt(2) == 'X')
            {
                if (out.length() < 4)
                {
                    return -1;
                }
                for (int i = 3; i < out.length(); i++)
                {
                    final char c = out.charAt(i);
                    if ((c < '0' || c > '9') && ((c < 'a' || c > 'f') && (c < 'A' || c > 'F')))
                    {
                        return -1;
                    }
                }
            }
            else
            {
                for (int i = 2; i < out.length(); i++)
                {
                    final char c = out.charAt(i);
                    if (c < '0' || c > '9')
                    {
                        return -1;
                    }
                }
            }
            out.append(';');
        }
        else
        {
            for (int i = 1; i < out.length(); i++)
            {
                final char c = out.charAt(i);
                if (!Character.isLetterOrDigit(c))
                {
                    return -1;
                }
            }
            out.append(';');
            return HTML.isEntity(out.toString()) ? pos : -1;
        }

        return pos;
    }

    /**
     * Recursively scans through the given line, taking care of any markdown
     * stuff.
     *
     * @param out
     *            The StringBuilder to write to.
     * @param in
     *            Input String.
     * @param start
     *            Start position.
     * @param token
     *            The matching Token (for e.g. '*')
     * @return The position of the matching Token or -1 if token was NONE or no
     *         Token could be found.
     */
    private int recursiveEmitLine(final StringBuilder out, final String in, final int start, final MarkToken token)
    {
        int pos = start, a, b;
        final StringBuilder temp = new StringBuilder();
        while (pos < in.length())
        {
            final MarkToken mt = this.getToken(in, pos);
            if (token != MarkToken.NONE
                    && (mt == token || token == MarkToken.EM_STAR && mt == MarkToken.STRONG_STAR || token == MarkToken.EM_UNDERSCORE
                            && mt == MarkToken.STRONG_UNDERSCORE))
            {
                return pos;
            }

            switch (mt)
            {
            case IMAGE:
            case LINK:
                temp.setLength(0);
                b = this.checkLink(temp, in, pos, mt);
                if (b > 0)
                {
                    out.append(temp);
                    pos = b;
                }
                else
                {
                    out.append(in.charAt(pos));
                }
                break;
            case EM_STAR:
            case EM_UNDERSCORE:
                temp.setLength(0);
                b = this.recursiveEmitLine(temp, in, pos + 1, mt);
                if (b > 0)
                {
                    this.config.decorator.openEmphasis(out);
                    out.append(temp);
                    this.config.decorator.closeEmphasis(out);
                    pos = b;
                }
                else
                {
                    out.append(in.charAt(pos));
                }
                break;
            case STRONG_STAR:
            case STRONG_UNDERSCORE:
                temp.setLength(0);
                b = this.recursiveEmitLine(temp, in, pos + 2, mt);
                if (b > 0)
                {
                    this.config.decorator.openStrong(out);
                    out.append(temp);
                    this.config.decorator.closeStrong(out);
                    pos = b + 1;
                }
                else
                {
                    out.append(in.charAt(pos));
                }
                break;
            case SUPER:
                temp.setLength(0);
                b = this.recursiveEmitLine(temp, in, pos + 1, mt);
                if (b > 0)
                {
                    this.config.decorator.openSuper(out);
                    out.append(temp);
                    this.config.decorator.closeSuper(out);
                    pos = b;
                }
                else
                {
                    out.append(in.charAt(pos));
                }
                break;
            case CODE_SINGLE:
            case CODE_DOUBLE:
                a = pos + (mt == MarkToken.CODE_DOUBLE ? 2 : 1);
                b = this.findToken(in, a, mt);
                if (b > 0)
                {
                    pos = b + (mt == MarkToken.CODE_DOUBLE ? 1 : 0);
                    while (a < b && in.charAt(a) == ' ')
                    {
                        a++;
                    }
                    if (a < b)
                    {
                        while (in.charAt(b - 1) == ' ')
                        {
                            b--;
                        }
                        this.config.decorator.openCodeSpan(out);
                        Utils.appendCode(out, in, a, b);
                        this.config.decorator.closeCodeSpan(out);
                    }
                }
                else
                {
                    out.append(in.charAt(pos));
                }
                break;
            case HTML:
                temp.setLength(0);
                b = this.checkHtml(temp, in, pos);
                if (b > 0)
                {
                    out.append(temp);
                    pos = b;
                }
                else
                {
                    out.append("<");
                }
                break;
            case ENTITY:
                temp.setLength(0);
                b = checkEntity(temp, in, pos);
                if (b > 0)
                {
                    out.append(temp);
                    pos = b;
                }
                else
                {
                    out.append("&");
                }
                break;
            case X_LINK_OPEN:
                temp.setLength(0);
                b = this.recursiveEmitLine(temp, in, pos + 2, MarkToken.X_LINK_CLOSE);
                if (b > 0 && this.config.specialLinkEmitter != null)
                {
                    this.config.specialLinkEmitter.emitSpan(out, temp.toString());
                    pos = b + 1;
                }
                else
                {
                    out.append(in.charAt(pos));
                }
                break;
            case X_COPY:
                out.append("©");
                pos += 2;
                break;
            case X_REG:
                out.append("®");
                pos += 2;
                break;
            case X_TRADE:
                out.append("™");
                pos += 3;
                break;
            case X_NDASH:
                out.append("–");
                pos++;
                break;
            case X_MDASH:
                out.append("—");
                pos += 2;
                break;
            case X_HELLIP:
                out.append("…");
                pos += 2;
                break;
            case X_LAQUO:
                out.append("«");
                pos++;
                break;
            case X_RAQUO:
                out.append("»");
                pos++;
                break;
            case X_RDQUO:
                out.append("”");
                break;
            case X_LDQUO:
                out.append("“");
                break;
            case ESCAPE:
                pos++;
                //$FALL-THROUGH$
            default:
                out.append(in.charAt(pos));
                break;
            }
            pos++;
        }
        return -1;
    }

    /**
     * Turns every whitespace character into a space character.
     *
     * @param c
     *            Character to check
     * @return 32 is c was a whitespace, c otherwise
     */
    private static char whitespaceToSpace(final char c)
    {
        return Character.isWhitespace(c) ? ' ' : c;
    }

    /**
     * Check if there is any markdown Token.
     *
     * @param in
     *            Input String.
     * @param pos
     *            Starting position.
     * @return The Token.
     */
    private MarkToken getToken(final String in, final int pos)
    {
        final char c0 = pos > 0 ? whitespaceToSpace(in.charAt(pos - 1)) : ' ';
        final char c = whitespaceToSpace(in.charAt(pos));
        final char c1 = pos + 1 < in.length() ? whitespaceToSpace(in.charAt(pos + 1)) : ' ';
        final char c2 = pos + 2 < in.length() ? whitespaceToSpace(in.charAt(pos + 2)) : ' ';
        final char c3 = pos + 3 < in.length() ? whitespaceToSpace(in.charAt(pos + 3)) : ' ';

        switch (c)
        {
        case '*':
            if (c1 == '*')
            {
                return c0 != ' ' || c2 != ' ' ? MarkToken.STRONG_STAR : MarkToken.EM_STAR;
            }
            return c0 != ' ' || c1 != ' ' ? MarkToken.EM_STAR : MarkToken.NONE;
        case '_':
            if (c1 == '_')
            {
                return c0 != ' ' || c2 != ' ' ? MarkToken.STRONG_UNDERSCORE : MarkToken.EM_UNDERSCORE;
            }
            if (this.useExtensions)
            {
                return Character.isLetterOrDigit(c0) && c0 != '_' && Character.isLetterOrDigit(c1) ? MarkToken.NONE
                        : MarkToken.EM_UNDERSCORE;
            }
            return c0 != ' ' || c1 != ' ' ? MarkToken.EM_UNDERSCORE : MarkToken.NONE;
        case '!':
            if (c1 == '[')
            {
                return MarkToken.IMAGE;
            }
            return MarkToken.NONE;
        case '[':
            if (this.useExtensions && c1 == '[')
            {
                return MarkToken.X_LINK_OPEN;
            }
            return MarkToken.LINK;
        case ']':
            if (this.useExtensions && c1 == ']')
            {
                return MarkToken.X_LINK_CLOSE;
            }
            return MarkToken.NONE;
        case '`':
            return c1 == '`' ? MarkToken.CODE_DOUBLE : MarkToken.CODE_SINGLE;
        case '\\':
            switch (c1)
            {
            case '\\':
            case '[':
            case ']':
            case '(':
            case ')':
            case '{':
            case '}':
            case '#':
            case '"':
            case '\'':
            case '.':
            case '>':
            case '<':
            case '*':
            case '+':
            case '-':
            case '_':
            case '!':
            case '`':
            case '~':
            case '^':
                return MarkToken.ESCAPE;
            default:
                return MarkToken.NONE;
            }
        case '<':
            if (this.useExtensions && c1 == '<')
            {
                return MarkToken.X_LAQUO;
            }
            return MarkToken.HTML;
        case '&':
            return MarkToken.ENTITY;
        default:
            if (this.useExtensions)
            {
                switch (c)
                {
                case '-':
                    if (c1 == '-')
                    {
                        return c2 == '-' ? MarkToken.X_MDASH : MarkToken.X_NDASH;
                    }
                    break;
                case '^':
                    return c0 == '^' || c1 == '^' ? MarkToken.NONE : MarkToken.SUPER;
                case '>':
                    if (c1 == '>')
                    {
                        return MarkToken.X_RAQUO;
                    }
                    break;
                case '.':
                    if (c1 == '.' && c2 == '.')
                    {
                        return MarkToken.X_HELLIP;
                    }
                    break;
                case '(':
                    if (c1 == 'C' && c2 == ')')
                    {
                        return MarkToken.X_COPY;
                    }
                    if (c1 == 'R' && c2 == ')')
                    {
                        return MarkToken.X_REG;
                    }
                    if (c1 == 'T' & c2 == 'M' & c3 == ')')
                    {
                        return MarkToken.X_TRADE;
                    }
                    break;
                case '"':
                    if (!Character.isLetterOrDigit(c0) && c1 != ' ')
                    {
                        return MarkToken.X_LDQUO;
                    }
                    if (c0 != ' ' && !Character.isLetterOrDigit(c1))
                    {
                        return MarkToken.X_RDQUO;
                    }
                    break;
                }
            }
            return MarkToken.NONE;
        }
    }

    /**
     * Writes a set of markdown lines into the StringBuilder.
     *
     * @param out
     *            The StringBuilder to write to.
     * @param lines
     *            The lines to write.
     */
    private void emitMarkedLines(final StringBuilder out, final Line lines)
    {
        final StringBuilder in = new StringBuilder();
        Line line = lines;
        while (line != null)
        {
            if (!line.isEmpty)
            {
                in.append(line.value.substring(line.leading, line.value.length() - line.trailing));
                if (line.trailing >= 2)
                {
                    in.append("<br />");
                }
            }
            if (line.next != null)
            {
                in.append('\n');
            }
            line = line.next;
        }

        this.recursiveEmitLine(out, in.toString(), 0, MarkToken.NONE);
    }

    /**
     * Writes a set of raw lines into the StringBuilder.
     *
     * @param out
     *            The StringBuilder to write to.
     * @param lines
     *            The lines to write.
     */
    private void emitRawLines(final StringBuilder out, final Line lines)
    {
        Line line = lines;
        if (this.config.safeMode)
        {
            final StringBuilder temp = new StringBuilder();
            while (line != null)
            {
                if (!line.isEmpty)
                {
                    temp.append(line.value);
                }
                temp.append('\n');
                line = line.next;
            }
            final String in = temp.toString();
            for (int pos = 0; pos < in.length(); pos++)
            {
                if (in.charAt(pos) == '<')
                {
                    temp.setLength(0);
                    final int t = Utils.readXML(temp, in, pos, this.config.safeMode);
                    if (t != -1)
                    {
                        out.append(temp);
                        pos = t;
                    }
                    else
                    {
                        out.append(in.charAt(pos));
                    }
                }
                else
                {
                    out.append(in.charAt(pos));
                }
            }
        }
        else
        {
            while (line != null)
            {
                if (!line.isEmpty)
                {
                    out.append(line.value);
                }
                out.append('\n');
                line = line.next;
            }
        }
    }

    /**
     * Writes a code block into the StringBuilder.
     *
     * @param out
     *            The StringBuilder to write to.
     * @param lines
     *            The lines to write.
     * @param meta
     *            Meta information.
     */
    private void emitCodeLines(final StringBuilder out, final Line lines, final String meta, final boolean removeIndent)
    {
        Line line = lines;
        if (this.config.codeBlockEmitter != null)
        {
            final ArrayList<String> list = new ArrayList<String>();
            while (line != null)
            {
                if (line.isEmpty)
                {
                    list.add("");
                }
                else
                {
                    list.add(removeIndent ? line.value.substring(4) : line.value);
                }
                line = line.next;
            }
            this.config.codeBlockEmitter.emitBlock(out, list, meta);
        }
        else
        {
            while (line != null)
            {
                if (!line.isEmpty)
                {
                    for (int i = removeIndent ? 4 : 0; i < line.value.length(); i++)
                    {
                        final char c;
                        switch (c = line.value.charAt(i))
                        {
                        case '&':
                            out.append("&");
                            break;
                        case '<':
                            out.append("<");
                            break;
                        case '>':
                            out.append(">");
                            break;
                        default:
                            out.append(c);
                            break;
                        }
                    }
                }
                out.append('\n');
                line = line.next;
            }
        }
    }
}


text:
from ..schemas import Schema, fields

from ..model.application import ApplicationSchema
from ..model.credentials import CredentialsSchema
from ..model.report import ReportSchema
from ..model.transaction import TransactionSchema
from ..model.address import AddressSchema

class CreditSchema (Schema):
    Application = fields.Nested(ApplicationSchema)
    Credentials = fields.Nested(CredentialsSchema)
    CustomBilling = None
    Reports = fields.Nested(ReportSchema)
    Transaction = fields.Nested(TransactionSchema)

class RedepositSchema (Schema):
    Application = fields.Nested(ApplicationSchema)
    Credentials = fields.Nested(CredentialsSchema)
    DemandDepositAccount = None
    PaymentAccount = None
    Reports = fields.Nested(ReportSchema)
    Transaction = fields.Nested(TransactionSchema)

class ReturnSchema (Schema):
    Address = fields.Nested(AddressSchema)
    Application = fields.Nested(ApplicationSchema)
    Credentials = fields.Nested(CredentialsSchema)
    CustomBilling = None
    DemandDepositAccount = None
    PaymentAccount = None
    Reports = fields.Nested(ReportSchema)
    Transaction = fields.Nested(TransactionSchema)

class SaleSchema (Schema):
    Address = fields.Nested(AddressSchema)
    Application = fields.Nested(ApplicationSchema)
    Credentials = fields.Nested(CredentialsSchema)
    CustomBilling = None
    DemandDepositAccount = None
    PaymentAccount = None
    Reports = fields.Nested(ReportSchema)
    Transaction = fields.Nested(TransactionSchema)

class VerificationSchema (Schema):
    Address = fields.Nested(AddressSchema)
    Application = fields.Nested(ApplicationSchema)
    Credentials = fields.Nested(CredentialsSchema)
    DemandDepositAccount = None
    PaymentAccount = None
    Reports = fields.Nested(ReportSchema)
    Transaction = fields.Nested(TransactionSchema)

class VoidSchema (Schema):
    Application = fields.Nested(ApplicationSchema)
    Credentials = fields.Nested(CredentialsSchema)
    Reports = fields.Nested(ReportSchema)
    Transaction = fields.Nested(TransactionSchema)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Web.Models;

namespace Web
{
    public class BasePage : Page
    {
        protected ApplicationDbContext DbContext { get; private set; }

        public BasePage()
        {
            this.DbContext = new ApplicationDbContext();
        }
    }
}


text:
#pragma strict

var particleNumber		: int				= 0;		// The current selected particle from particles[]
var particles			: GameObject[];					// The particles Availalbe for the demo
var targets				: GameObject[];					// Targets for shooting particles
var targetNumber		: int				= 0;		// The current target
var currentParticle		: GameObject;					// Holds the current in-game object
var currentParticleName : String;

function Start () {
	currentParticleName = "Current: " + particles[particleNumber].name + " (" + (particleNumber + 1) + " of " + particles.Length + ")";
}

function Update () {
	if (Input.GetKeyDown ("space"))
		ShowNewParticle();
	if (Input.GetKeyDown ("left"))
		SwitchParticle(-1);
	if (Input.GetKeyDown ("right"))
		SwitchParticle(1);
}

function ShowNewParticle(){
	if (currentParticle)
		Destroy(currentParticle);
	currentParticle = Instantiate(particles[particleNumber], Vector3(0, 0, 0), Quaternion.identity);
	currentParticle.transform.position 		= currentParticle.GetComponent(demoParticleControl).startPosition;
	currentParticle.transform.eulerAngles 	= currentParticle.GetComponent(demoParticleControl).startRotation;
	if (currentParticle.GetComponent(demoParticleControl).shootsTarget)
	{
		currentParticle.transform.LookAt(targets[targetNumber].transform);
		targetNumber += 1;
		if (targetNumber < 0)
			targetNumber = targets.Length - 1;
		else if (targetNumber == targets.Length)
			targetNumber = 0;
	}
}

function SwitchParticle(value : int){
	particleNumber += value;
	if (particleNumber < 0)
		particleNumber = particles.Length - 1;
	else if (particleNumber == particles.Length)
		particleNumber = 0;
	currentParticleName = "Current: " + particles[particleNumber].name + " (" + (particleNumber + 1) + " of " + particles.Length + ")";
}


text:
module Azure::CDN::Mgmt::V2020_04_15
  module Models
    #
    # Defines values for UrlPathOperator
    #
    module UrlPathOperator
      Any = "Any"
      Equal = "Equal"
      Contains = "Contains"
      BeginsWith = "BeginsWith"
      EndsWith = "EndsWith"
      LessThan = "LessThan"
      LessThanOrEqual = "LessThanOrEqual"
      GreaterThan = "GreaterThan"
      GreaterThanOrEqual = "GreaterThanOrEqual"
      Wildcard = "Wildcard"
    end
  end
end


text:
import * as Cookies from "js-cookie";

export function normalizeBaseURL(url: string): string {
  return url.replace(/\/+$/, "");
}

export function createAJAXSettings(
  serverConfig: Object,
  uri: string = "/",
  opts: Object = {}
): Object {
  const baseURL = normalizeBaseURL(serverConfig.endpoint || serverConfig.url);
  const url = `${baseURL}${uri}`;
  const xsrfToken = Cookies.get("_xsrf");
  const headers = {
    "X-XSRFToken": xsrfToken,
    Authorization: `token ${serverConfig.token ? serverConfig.token : ""}`
  };
  // Merge in our typical settings for responseType, allow setting additional options
  // like the method
  const settings = Object.assign(
    {
      url,
      responseType: "json",
      createXHR: function() {
        return new XMLHttpRequest();
      }
    },
    serverConfig,
    opts,
    {
      // Make sure we merge in the auth headers with user given headers
      headers: Object.assign({}, headers, opts.headers)
    }
  );

  delete settings.endpoint;
  return settings;
}


text:
from __future__ import unicode_literals

import os
import shutil

from markment.core import Project
from markment.fs import Generator
from markment.ui import Theme
from lxml import html as lhtml
from sure import scenario
from os.path import relpath
from .base import LOCAL_FILE

def prepare(context):
    context.project_path = LOCAL_FILE('sandbox_mixed')
    context.theme_path = LOCAL_FILE('sandbox_mixed/simpletheme')
    context.output_path = LOCAL_FILE('sandbox_mixed/output')

def cleanup(context):
    if os.path.exists(context.output_path):
        shutil.rmtree(context.output_path)

fs_test = scenario([prepare], [cleanup])
sort_files = lambda x: "{0}{1}".format(len(relpath(x).split(os.sep)), x)
filter_html = lambda files: [i for i in files if i.endswith('.html')]

@fs_test
def test_first_level_file(context):
    "The first level file should have the assets pointing to the right path"

    project = Project.discover(context.project_path)
    theme = Theme.load_from_path(context.theme_path)
    destination = Generator(project, theme)
    generated = sorted(filter_html(destination.persist(context.output_path)), key=lambda x: len(x.split(os.sep)))
    generated.should.have.length_of(2)

    first_level = generated[0]
    first_level.should.contain('index.html')

    html = open(first_level).read()
    dom = lhtml.fromstring(html)

    links = dom.cssselect('link.theme-asset')

    links.should.have.length_of(1)

    style = links[0]

    style.attrib.should.have.key("href").being.equal("./assets/stylesheets/stylesheet.css")

@fs_test
def test_second_level_file(context):
    "The second_level file should have the assets pointing to the right path"

    project = Project.discover(context.project_path)
    theme = Theme.load_from_path(context.theme_path)
    destination = Generator(project, theme)
    generated = sorted(filter_html(destination.persist(context.output_path)), key=sort_files)
    generated.should.have.length_of(2)

    second_level = generated[1]
    second_level.should.contain('docs/index.html')

    html = open(second_level).read()
    dom = lhtml.fromstring(html)

    links = dom.cssselect('link.theme-asset')

    links.should.have.length_of(1)

    style = links[0]

    style.attrib.should.have.key("href").being.equal("../assets/stylesheets/stylesheet.css")


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />
	<meta name="robots" content="noindex" />

	<title>File src/Signals/Data/Definitions/ExportMessage.php | PEG Api</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />

		Overview

Namespaces

None

Peg

Cli

Commands

Config

Custom

Command

Action

Generate

Parse

CommandLine

Config

Localization

Utilities

Lib

Definitions

Element

Generator

Lexers

Plugins

Signals

Data

Definitions

Lexers

Type

PHP

Classes

ExportMessage

ImportMessage

	<form id="search">
		<input type="hidden" name="cx" value="" />
		<input type="hidden" name="ie" value="UTF-8" />
		<input type="text" name="q" class="text" />
		<input type="submit" value="Search" />
	</form>

				Overview

				Namespace

				Class

				Tree

				Todo

 1: <?php
 2: /**
 3:  * @author Jefferson González
 4:  * @license MIT
 5:  * @link http://github.com/peg-org/peg-src Source code.
 6:  */
 7:
 8: namespace Peg\Lib\Signals\Data\Definitions;
 9:
10: /**
11:  * Object sent by the EXPORT_MESSAGE signal.
12:  */
13: class ExportMessage extends \Peg\Lib\Signals\SignalData
14: {
15:     /**
16:      * A message representing current task been performed by the exporter.
17:      * @var string
18:      */
19:     public $message;
20:
21:     public function __construct()
22:     {
23:         parent::__construct();
24:     }
25: }

		PEG Api API documentation generated by ApiGen 2.8.0


text:
import cloudCommonConfig from './config.cloud.common'

const replicaConfig = {
  ...cloudCommonConfig,
  distDir: 'dist',
}

export default replicaConfig


text:
import logging
import uuid

from collections import defaultdict
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse, urlsplit, urlunparse, urlunsplit
from urllib.request import Request, urlopen

import requests

from django.core.exceptions import ImproperlyConfigured

from wagtail import __version__

logger = logging.getLogger('wagtail.frontendcache')

class PurgeRequest(Request):
    def get_method(self):
        return 'PURGE'

class BaseBackend:
    def purge(self, url):
        raise NotImplementedError

    def purge_batch(self, urls):
        # Fallback for backends that do not support batch purging
        for url in urls:
            self.purge(url)

class HTTPBackend(BaseBackend):
    def __init__(self, params):
        location_url_parsed = urlparse(params.pop('LOCATION'))
        self.cache_scheme = location_url_parsed.scheme
        self.cache_netloc = location_url_parsed.netloc

    def purge(self, url):
        url_parsed = urlparse(url)
        host = url_parsed.hostname

        # Append port to host if it is set in the original URL
        if url_parsed.port:
            host += (':' + str(url_parsed.port))

        request = PurgeRequest(
            url=urlunparse([
                self.cache_scheme,
                self.cache_netloc,
                url_parsed.path,
                url_parsed.params,
                url_parsed.query,
                url_parsed.fragment
            ]),
            headers={
                'Host': host,
                'User-Agent': 'Wagtail-frontendcache/' + __version__
            }
        )

        try:
            urlopen(request)
        except HTTPError as e:
            logger.error("Couldn't purge '%s' from HTTP cache. HTTPError: %d %s", url, e.code, e.reason)
        except URLError as e:
            logger.error("Couldn't purge '%s' from HTTP cache. URLError: %s", url, e.reason)

class CloudflareBackend(BaseBackend):
    CHUNK_SIZE = 30

    def __init__(self, params):
        self.cloudflare_email = params.pop("EMAIL", None)
        self.cloudflare_api_key = (
            params.pop("TOKEN", None)
            or params.pop("API_KEY", None)
        )
        self.cloudflare_token = params.pop("BEARER_TOKEN", None)
        self.cloudflare_zoneid = params.pop("ZONEID")

        if (
            (not self.cloudflare_email and self.cloudflare_api_key)
            or (self.cloudflare_email and not self.cloudflare_api_key)
            or (not any([self.cloudflare_email, self.cloudflare_api_key, self.cloudflare_token]))
        ):
            raise ImproperlyConfigured(
                "The setting 'WAGTAILFRONTENDCACHE' requires both 'EMAIL' and 'API_KEY', or 'BEARER_TOKEN' to be specified."
            )

    def _purge_urls(self, urls):
        try:
            purge_url = 'https://api.cloudflare.com/client/v4/zones/{0}/purge_cache'.format(self.cloudflare_zoneid)

            headers = {"Content-Type": "application/json"}

            if self.cloudflare_token:
                headers["Authorization"] = "Bearer {}".format(self.cloudflare_token)
            else:
                headers["X-Auth-Email"] = self.cloudflare_email
                headers["X-Auth-Key"] = self.cloudflare_api_key

            data = {"files": urls}

            response = requests.delete(
                purge_url,
                json=data,
                headers=headers,
            )

            try:
                response_json = response.json()
            except ValueError:
                if response.status_code != 200:
                    response.raise_for_status()
                else:
                    for url in urls:
                        logger.error("Couldn't purge '%s' from Cloudflare. Unexpected JSON parse error.", url)

        except requests.exceptions.HTTPError as e:
            for url in urls:
                logging.exception("Couldn't purge '%s' from Cloudflare. HTTPError: %d", url, e.response.status_code)
            return

        if response_json['success'] is False:
            error_messages = ', '.join([str(err['message']) for err in response_json['errors']])
            for url in urls:
                logger.error("Couldn't purge '%s' from Cloudflare. Cloudflare errors '%s'", url, error_messages)
            return

    def purge_batch(self, urls):
        # Break the batched URLs in to chunks to fit within Cloudflare's maximum size for
        # the purge_cache call (https://api.cloudflare.com/#zone-purge-files-by-url)
        for i in range(0, len(urls), self.CHUNK_SIZE):
            chunk = urls[i:i + self.CHUNK_SIZE]
            self._purge_urls(chunk)

    def purge(self, url):
        self.purge_batch([url])

class CloudfrontBackend(BaseBackend):
    def __init__(self, params):
        import boto3

        self.client = boto3.client('cloudfront')
        try:
            self.cloudfront_distribution_id = params.pop('DISTRIBUTION_ID')
        except KeyError:
            raise ImproperlyConfigured(
                "The setting 'WAGTAILFRONTENDCACHE' requires the object 'DISTRIBUTION_ID'."
            )

    def purge_batch(self, urls):
        paths_by_distribution_id = defaultdict(list)

        for url in urls:
            url_parsed = urlparse(url)
            distribution_id = None

            if isinstance(self.cloudfront_distribution_id, dict):
                host = url_parsed.hostname
                if host in self.cloudfront_distribution_id:
                    distribution_id = self.cloudfront_distribution_id.get(host)
                else:
                    logger.info(
                        "Couldn't purge '%s' from CloudFront. Hostname '%s' not found in the DISTRIBUTION_ID mapping",
                        url, host)
            else:
                distribution_id = self.cloudfront_distribution_id

            if distribution_id:
                paths_by_distribution_id[distribution_id].append(url_parsed.path)

        for distribution_id, paths in paths_by_distribution_id.items():
            self._create_invalidation(distribution_id, paths)

    def purge(self, url):
        self.purge_batch([url])

    def _create_invalidation(self, distribution_id, paths):
        import botocore

        try:
            self.client.create_invalidation(
                DistributionId=distribution_id,
                InvalidationBatch={
                    'Paths': {
                        'Quantity': len(paths),
                        'Items': paths
                    },
                    'CallerReference': str(uuid.uuid4())
                }
            )
        except botocore.exceptions.ClientError as e:
            for path in paths:
                logger.error(
                    "Couldn't purge path '%s' from CloudFront (DistributionId=%s). ClientError: %s %s",
                    path,
                    distribution_id,
                    e.response['Error']['Code'],
                    e.response['Error']['Message']
                )

class AzureBaseBackend(BaseBackend):
    def __init__(self, params):
        self._credentials = params.pop("CREDENTIALS", None)
        self._subscription_id = params.pop("SUBSCRIPTION_ID", None)
        try:
            self._resource_group_name = params.pop("RESOURCE_GROUP_NAME")
        except KeyError:
            raise ImproperlyConfigured(
                "The setting 'WAGTAILFRONTENDCACHE' requires 'RESOURCE_GROUP_NAME' to be specified."
            )
        self._custom_headers = params.pop("CUSTOM_HEADERS", None)

    def purge_batch(self, urls):
        self._purge_content([self._get_path(url) for url in urls])

    def purge(self, url):
        self.purge_batch([url])

    def _get_default_credentials(self):
        try:
            from azure.identity import DefaultAzureCredential
        except ImportError:
            return
        return DefaultAzureCredential()

    def _get_credentials(self):
        """
        Use credentials object set by user. If not set, use the one configured
        in the current environment.
        """
        user_credentials = self._credentials
        if user_credentials:
            return user_credentials
        return self._get_default_credentials()

    def _get_default_subscription_id(self):
        """
        Obtain subscription ID directly from Azure.
        """
        try:
            from azure.mgmt.resource import SubscriptionClient
        except ImportError:
            return ""
        credential = self._get_credentials()
        subscription_client = SubscriptionClient(credential)
        subscription = next(subscription_client.subscriptions.list())
        return subscription.subscription_id

    def _get_subscription_id(self):
        """
        Use subscription ID set in the user configuration. If not set, try to
        retrieve one from Azure directly.
        """
        user_subscription_id = self._subscription_id
        if user_subscription_id:
            return user_subscription_id
        return self._get_default_subscription_id()

    def _get_client_kwargs(self):
        return {
            "credentials": self._get_credentials(),
            "subscription_id": self._get_subscription_id(),
        }

    def _get_path(self, url):
        """
        Split netloc from the URL and return path only.
        """
        # Delete scheme and netloc from the URL, that will result in only path being
        # left.
        url_parts = ("",) * 2 + urlsplit(url)[2:]
        return urlunsplit(url_parts)

    def _get_client(self):
        """
        Get Azure client instance.
        """
        klass = self._get_client_class()
        kwargs = self._get_client_kwargs()
        return klass(**kwargs)

    def _get_purge_kwargs(self, paths):
        """
        Get keyword arguments passes to Azure purge content calls.
        """
        return {
            "resource_group_name": self._resource_group_name,
            "custom_headers": self._custom_headers,
            "content_paths": paths,
        }

    def _purge_content(self, paths):
        from msrest.exceptions import HttpOperationError

        client = self._get_client()
        try:
            self._make_purge_call(client, paths)
        except HttpOperationError as exception:
            for path in paths:
                logger.exception(
                    "Couldn't purge '%s' from %s cache. HttpOperationError: %r",
                    path,
                    type(self).__name__,
                    exception.response,
                )

class AzureFrontDoorBackend(AzureBaseBackend):
    def __init__(self, params):
        super().__init__(params)
        try:
            self._front_door_name = params.pop("FRONT_DOOR_NAME")
        except KeyError:
            raise ImproperlyConfigured(
                "The setting 'WAGTAILFRONTENDCACHE' requires 'FRONT_DOOR_NAME' to be specified."
            )
        self._front_door_service_url = params.pop("FRONT_DOOR_SERVICE_URL", None)

    def _get_client_class(self):
        from azure.mgmt.frontdoor import FrontDoorManagementClient

        return FrontDoorManagementClient

    def _get_client_kwargs(self):
        kwargs = super()._get_client_kwargs()
        kwargs.setdefault("base_url", self._front_door_service_url)
        return kwargs

    def _make_purge_call(self, client, paths):
        return client.endpoints.purge_content(
            **self._get_purge_kwargs(paths),
            front_door_name=self._front_door_name,
        )

class AzureCdnBackend(AzureBaseBackend):
    def __init__(self, params):
        super().__init__(params)
        try:
            self._cdn_profile_name = params.pop("CDN_PROFILE_NAME")
            self._cdn_endpoint_name = params.pop("CDN_ENDPOINT_NAME")
        except KeyError:
            raise ImproperlyConfigured(
                "The setting 'WAGTAILFRONTENDCACHE' requires 'CDN_PROFILE_NAME' and 'CDN_ENDPOINT_NAME' to be specified."
            )
        self._cdn_service_url = params.pop("CDN_SERVICE_URL", None)

    def _get_client_class(self):
        from azure.mgmt.cdn import CdnManagementClient

        return CdnManagementClient

    def _get_client_kwargs(self):
        kwargs = super()._get_client_kwargs()
        kwargs.setdefault("base_url", self._cdn_service_url)
        return kwargs

    def _make_purge_call(self, client, paths):
        return client.endpoints.purge_content(
            **self._get_purge_kwargs(paths),
            profile_name=self._cdn_profile_name,
            endpoint_name=self._cdn_endpoint_name,
        )


text:
QuickSpecBegin(SDLDeleteFileOperationSpec)

describe(@"Delete File Operation", ^{
    __block TestConnectionManager *testConnectionManager = nil;
    __block SDLDeleteFileOperation *testOperation = nil;

    __block NSString *deleteFileName = nil;
    __block BOOL successResult = NO;
    __block NSUInteger bytesAvailableResult = NO;
    __block NSError *errorResult = nil;

    beforeEach(^{
        deleteFileName = @"Some File";
        testConnectionManager = [[TestConnectionManager alloc] init];

        testOperation = [[SDLDeleteFileOperation alloc] initWithFileName:deleteFileName connectionManager:testConnectionManager completionHandler:^(BOOL success, NSUInteger bytesAvailable, NSError * _Nullable error) {
            successResult = success;
            bytesAvailableResult = bytesAvailable;
            errorResult = error;
        }];
    });

    it(@"should have a priority of 'very high'", ^{
        expect(@(testOperation.queuePriority)).to(equal(@(NSOperationQueuePriorityVeryHigh)));
    });

    describe(@"running the operation", ^{
        beforeEach(^{
            [testOperation start];
        });

        it(@"should send a list files request", ^{
            expect(testConnectionManager.receivedRequests.lastObject).to(beAnInstanceOf([SDLDeleteFile class]));
        });

        context(@"when a good response comes back", ^{
            __block SDLDeleteFileResponse *goodResponse = nil;
            __block NSNumber *responseSpaceAvailable = nil;

            beforeEach(^{
                responseSpaceAvailable = @(11212512);

                goodResponse = [[SDLDeleteFileResponse alloc] init];
                goodResponse.success = @YES;
                goodResponse.spaceAvailable = responseSpaceAvailable;

                [testConnectionManager respondToLastRequestWithResponse:goodResponse];
            });

            it(@"should have called the completion handler with proper data", ^{
                expect(@(successResult)).to(equal(@YES));
                expect(@(bytesAvailableResult)).to(equal(responseSpaceAvailable));
                expect(errorResult).to(beNil());
            });

            it(@"should be set to finished", ^{
                expect(@(testOperation.finished)).to(equal(@YES));
                expect(@(testOperation.executing)).to(equal(@NO));
            });
        });

        context(@"when a bad response comes back", ^{
            __block SDLDeleteFileResponse *badResponse = nil;
            __block NSNumber *responseSpaceAvailable = nil;

            __block NSString *responseErrorDescription = nil;
            __block NSString *responseErrorReason = nil;

            beforeEach(^{
                responseSpaceAvailable = @(0);

                responseErrorDescription = @"some description";
                responseErrorReason = @"some reason";

                badResponse = [[SDLDeleteFileResponse alloc] init];
                badResponse.success = @NO;
                badResponse.spaceAvailable = responseSpaceAvailable;

                [testConnectionManager respondToLastRequestWithResponse:badResponse error:[NSError sdl_lifecycle_unknownRemoteErrorWithDescription:responseErrorDescription andReason:responseErrorReason]];
            });

            it(@"should have called completion handler with error", ^{
                expect(errorResult.localizedDescription).to(match(responseErrorDescription));
                expect(errorResult.localizedFailureReason).to(match(responseErrorReason));
                expect(@(successResult)).to(equal(@NO));
            });
        });
    });
});

QuickSpecEnd


text:
package com.orientechnologies.orient.client.remote;

import com.orientechnologies.orient.core.config.OStorageConfiguration;

public class OStorageRemoteConfiguration extends OStorageConfiguration {

  private static final long serialVersionUID = -3850696054909943272L;
  private String            networkRecordSerializer;

  public OStorageRemoteConfiguration(OStorageRemote oStorageRemote, String iRecordSerializer) {
    super(oStorageRemote);
    networkRecordSerializer = iRecordSerializer;
  }

  @Override
  public String getRecordSerializer() {
    return networkRecordSerializer;
  }

  @Override
  public int getRecordSerializerVersion() {
    return super.getRecordSerializerVersion();
  }

}


text:
function assertdir {
    if [ ! -d "$1" ]; then
        sudo mkdir $1
    fi
}

# make director in usr/local
INSTALLDIR=/usr/local/codewebsindexdaemon
echo "Installing CodewebsUnitTestServer to $INSTALLDIR"
assertdir $INSTALLDIR

echo " ... copying files to $INSTALLDIR"
assertdir $INSTALLDIR/log
assertdir $INSTALLDIR/log/UnitTestServer
assertdir $INSTALLDIR/UnitTestServer

sudo cp CodewebsUnitTestDaemon.py $INSTALLDIR/UnitTestServer
sudo cp localconfig $INSTALLDIR/UnitTestServer
sudo cp codewebsunittester.conf /etc/init

echo " ... setting permissions"
sudo chown -R root:root $INSTALLDIR/UnitTestServer
sudo chown -R root:root $INSTALLDIR/log
sudo chown root:root /etc/init/codewebsunittester.conf
echo "Finished with installation."


text:
package ti.modules.titanium.ui.widget.tableview;

import org.appcelerator.titanium.TiContext;
import org.appcelerator.titanium.util.TiUIHelper;
import org.appcelerator.titanium.view.TiBorderWrapperView;
import org.appcelerator.titanium.view.TiUIView;

import ti.modules.titanium.ui.widget.tableview.TableViewModel.Item;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.View.MeasureSpec;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class TiTableViewHeaderItem extends TiBaseTableViewItem
{
	private RowView rowView;
	private TiUIView headerView;
	private boolean isHeaderView = false;

	class RowView extends RelativeLayout
	{
		private TextView textView;
		private Item item;

		public RowView(Context context)
		{
			super(context);
			setGravity(Gravity.CENTER_VERTICAL);

			textView = new TextView(context);
			textView.setId(101);
			textView.setFocusable(false);
			textView.setFocusableInTouchMode(false);
			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
			params.addRule(CENTER_VERTICAL);
			params.alignWithParent = true;
			addView(textView, params);

			setPadding(0, 0, 0, 0);
			setMinimumHeight((int) TiUIHelper.getRawDIPSize(18, context));
			setVerticalFadingEdgeEnabled(false);
			TiUIHelper.styleText(textView, "", "10dp", "normal"); // TODO font
			textView.setBackgroundColor(Color.DKGRAY);
			textView.setTextColor(Color.LTGRAY);
			TiUIHelper.setTextViewDIPPadding(textView, 4, 2);
		}

		public void setRowData(Item item)
		{
			this.item = item;
			if (item.headerText != null) {
				textView.setText(item.headerText, TextView.BufferType.NORMAL);
			} else if (item.footerText != null) {
				textView.setText(item.footerText, TextView.BufferType.NORMAL);
			}
		}

		public Item getRowData()
		{
			return item;
		}
	}

	public TiTableViewHeaderItem(Activity activity)
	{
		super(activity);
		this.handler = new Handler(this);
		rowView = new RowView(activity);
		this.addView(rowView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		setMinimumHeight((int) TiUIHelper.getRawDIPSize(18, activity));
	}

	public TiTableViewHeaderItem(Activity activity, TiUIView headerView)
	{
		super(activity);

		this.handler = new Handler(this);
		this.addView(headerView.getOuterView(), headerView.getOuterView().getLayoutParams());
		this.setLayoutParams(headerView.getOuterView().getLayoutParams());
		setMinimumHeight((int) TiUIHelper.getRawDIPSize(18, activity));
		this.headerView = headerView;
		this.isHeaderView = true;
	}

	public TiTableViewHeaderItem(TiContext tiContext, Activity activity)
	{
		this(activity);
	}

	public void setRowData(Item item)
	{
		if (!isHeaderView) {
			rowView.setRowData(item);
		}
	}

	public Item getRowData()
	{
		return rowView.getRowData();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		measureChildren(widthMeasureSpec, heightMeasureSpec);
		int w = MeasureSpec.getSize(widthMeasureSpec);
		int h = 0;
		// If measure spec is not specified, height should behave as Ti.UI.SIZE
		if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) {
		    h = getSuggestedMinimumHeight();
		} else {
		    h = Math.max(MeasureSpec.getSize(heightMeasureSpec), getSuggestedMinimumHeight());
		}
		setMeasuredDimension(resolveSize(w, widthMeasureSpec), resolveSize(h, heightMeasureSpec));

	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom)
	{
		if (!isHeaderView) {
			rowView.layout(left, 0, right, bottom - top);
		} else {
			View view = headerView.getOuterView();
			view.layout(left, 0, right, bottom - top);
			// Also layout the inner native view when we have borders
			if (view instanceof TiBorderWrapperView) {
				headerView.getNativeView().layout(left, 0, right, bottom - top);
			}
		}
	}
}


text:
<?php

namespace EmailMarketing\Domain\Entity;

class User
{

    private $id;

    private $nome;

    private $email;

    private $password;

    private $plainPassword;

    public function getId()
    {
        return $this->id;
    }

    public function getNome()
    {
        return $this->nome;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    public function setNome(string $nome)
    {
        $this->nome = $nome;
        return $this;
    }

    public function setEmail(string $email)
    {
        $this->email = $email;
        return $this;
    }

    public function setPassword(string $password)
    {
        $this->password = $password;
        return $this;
    }

    public function getPlainPassword()
    {
        return $this->plainPassword;
    }

    public function setPlainPassword(string $plainPassword)
    {
        $this->plainPassword = $plainPassword;
        return $this;
    }

    public function generatePassword()
    {
        $password = $this->getPlainPassword() ?? uniqid();
        $this->setPassword(password_hash($password, PASSWORD_BCRYPT));
    }

}


text:
<?php

namespace api\tests\functional;

use api\tests\FunctionalTester;

class HomeCest
{
    public function checkOpen(FunctionalTester $I)
    {
        $I->amOnPage(\Yii::$app->homeUrl);
        $I->see('My Company');
        $I->seeLink('About');
        $I->click('About');
        $I->see('This is the About page.');
    }
}


text:
import { runSaga, stdChannel } from 'redux-saga'
import { getContext, takeEvery } from 'redux-saga/effects'
import { subspace } from 'redux-subspace'
import provideStore from './provideStore'

const subspaced = (mapState, namespace) => {
  const subspaceDecorator = subspace(mapState, namespace)

  return saga => {
    return function*(...args) {
      const parentStore = yield getContext('store')
      const sagaMiddlewareOptions = yield getContext('sagaMiddlewareOptions')

      const channel = stdChannel()

      const store = {
        ...sagaMiddlewareOptions,
        ...subspaceDecorator(parentStore),
        channel
      }

      runSaga(store, provideStore(store, sagaMiddlewareOptions)(saga), ...args)

      yield takeEvery('*', function*(action) {
        store.processAction(action, channel.put)
        yield
      })
    }
  }
}

export default subspaced


text:
#ifndef JPCOMMON_H
#define JPCOMMON_H

#ifdef __cplusplus
#define JPCOMMON_H_START extern "C" {
#define JPCOMMON_H_END   }
#else
#define JPCOMMON_H_START
#define JPCOMMON_H_END
#endif                          /* __CPLUSPLUS */

JPCOMMON_H_START;

/* JPCommonLabel */

struct _JPCommonLabelPhoneme;
struct _JPCommonLabelMora;
struct _JPCommonLabelWord;
struct _JPCommonLabelAccentPhrase;
struct _JPCommonLabelBreathGroup;

typedef struct _JPCommonLabelPhoneme {
   char *phoneme;
   struct _JPCommonLabelPhoneme *prev;
   struct _JPCommonLabelPhoneme *next;
   struct _JPCommonLabelMora *up;
} JPCommonLabelPhoneme;

typedef struct _JPCommonLabelMora {
   char *mora;
   struct _JPCommonLabelPhoneme *head;
   struct _JPCommonLabelPhoneme *tail;
   struct _JPCommonLabelMora *prev;
   struct _JPCommonLabelMora *next;
   struct _JPCommonLabelWord *up;
} JPCommonLabelMora;

typedef struct _JPCommonLabelWord {
   char *pron;
   char *pos;
   char *ctype;
   char *cform;
   struct _JPCommonLabelMora *head;
   struct _JPCommonLabelMora *tail;
   struct _JPCommonLabelWord *prev;
   struct _JPCommonLabelWord *next;
   struct _JPCommonLabelAccentPhrase *up;
} JPCommonLabelWord;

typedef struct _JPCommonLabelAccentPhrase {
   int accent;
   char *emotion;
   struct _JPCommonLabelWord *head;
   struct _JPCommonLabelWord *tail;
   struct _JPCommonLabelAccentPhrase *prev;
   struct _JPCommonLabelAccentPhrase *next;
   struct _JPCommonLabelBreathGroup *up;
} JPCommonLabelAccentPhrase;

typedef struct _JPCommonLabelBreathGroup {
   struct _JPCommonLabelAccentPhrase *head;
   struct _JPCommonLabelAccentPhrase *tail;
   struct _JPCommonLabelBreathGroup *prev;
   struct _JPCommonLabelBreathGroup *next;
} JPCommonLabelBreathGroup;

typedef struct _JPCommonLabel {
   int size;
   char **feature;
   JPCommonLabelBreathGroup *breath_head;
   JPCommonLabelBreathGroup *breath_tail;
   JPCommonLabelAccentPhrase *accent_head;
   JPCommonLabelAccentPhrase *accent_tail;
   JPCommonLabelWord *word_head;
   JPCommonLabelWord *word_tail;
   JPCommonLabelMora *mora_head;
   JPCommonLabelMora *mora_tail;
   JPCommonLabelPhoneme *phoneme_head;
   JPCommonLabelPhoneme *phoneme_tail;
   int short_pause_flag;
} JPCommonLabel;

void JPCommonLabel_initialize(JPCommonLabel * label);
void JPCommonLabel_push_word(JPCommonLabel * label, const char *pron, const char *pos,
                             const char *ctype, const char *cform, int acc, int chain_flag);
void JPCommonLabel_make(JPCommonLabel * label);
int JPCommonLabel_get_size(JPCommonLabel * label);
char **JPCommonLabel_get_feature(JPCommonLabel * label);
void JPCommonLabel_print(JPCommonLabel * label);
void JPCommonLabel_fprint(JPCommonLabel * label, FILE * fp);
void JPCommonLabel_clear(JPCommonLabel * label);

/* JPCommonNode */

typedef struct _JPCommonNode {
   char *pron;                  /* pronunciation */
   char *pos;                   /* part of speech */
   char *ctype;                 /* conjugation type */
   char *cform;                 /* conjugation form */
   int acc;                     /* accent type */
   int chain_flag;              /* chain flag */
   struct _JPCommonNode *prev;
   struct _JPCommonNode *next;
} JPCommonNode;

void JPCommonNode_initialize(JPCommonNode * node);
void JPCommonNode_set_pron(JPCommonNode * node, const char *str);
void JPCommonNode_set_pos(JPCommonNode * node, const char *str);
void JPCommonNode_set_ctype(JPCommonNode * node, const char *str);
void JPCommonNode_set_cform(JPCommonNode * node, const char *str);
void JPCommonNode_set_acc(JPCommonNode * node, int acc);
void JPCommonNode_set_chain_flag(JPCommonNode * node, int flag);
const char *JPCommonNode_get_pron(JPCommonNode * node);
const char *JPCommonNode_get_pos(JPCommonNode * node);
const char *JPCommonNode_get_ctype(JPCommonNode * node);
const char *JPCommonNode_get_cform(JPCommonNode * node);
int JPCommonNode_get_acc(JPCommonNode * node);
int JPCommonNode_get_chain_flag(JPCommonNode * node);
void JPCommonNode_print(JPCommonNode * node);
void JPCommonNode_fprint(JPCommonNode * node, FILE * fp);
void JPCommonNode_clear(JPCommonNode * node);

/* JPCommon */

typedef struct _JPCommon {
   JPCommonNode *head;
   JPCommonNode *tail;
   JPCommonLabel *label;
} JPCommon;

void JPCommon_initialize(JPCommon * jpcommon);
void JPCommon_push(JPCommon * jpcommon, JPCommonNode * node);
void JPCommon_make_label(JPCommon * jpcommon);
int JPCommon_get_label_size(JPCommon * jpcommon);
char **JPCommon_get_label_feature(JPCommon * jpcommon);
void JPCommon_print(JPCommon * jpcommon);
void JPCommon_fprint(JPCommon * jpcommon, FILE * fp);
void JPCommon_refresh(JPCommon * jpcommon);
void JPCommon_clear(JPCommon * jpcommon);

JPCOMMON_H_END;

#endif                          /* !JPCOMMON_H */


text:
#ifndef __LINUX_KVM_PARA_H
#define __LINUX_KVM_PARA_H

/*
 * This header file provides a method for making a hypercall to the host
 * Architectures should define:
 * - kvm_hypercall0, kvm_hypercall1...
 * - kvm_arch_para_features
 * - kvm_para_available
 */

/* Return values for hypercalls */
#define KVM_ENOSYS		1000
#define KVM_EFAULT		EFAULT
#define KVM_E2BIG		E2BIG
#define KVM_EPERM		EPERM

#define KVM_HC_VAPIC_POLL_IRQ		1
#define KVM_HC_MMU_OP			2
#define KVM_HC_FEATURES			3
#define KVM_HC_PPC_MAP_MAGIC_PAGE	4
#define KVM_HC_KICK_CPU			5

/*
 * hypercalls use architecture specific
 */
#include <asm/kvm_para.h>

#endif /* __LINUX_KVM_PARA_H */


text:
package org.kuali.continuity.plan.action.dto;

public interface SubNavigation {

}


text:
from datetime import datetime
from typing import List

import numpy as np
import pytest

import pandas.util._test_decorators as td

from pandas.core.dtypes.cast import astype_nansafe
import pandas.core.dtypes.common as com
from pandas.core.dtypes.dtypes import (
    CategoricalDtype,
    CategoricalDtypeType,
    DatetimeTZDtype,
    IntervalDtype,
    PeriodDtype,
)
from pandas.core.dtypes.missing import isna

import pandas as pd
import pandas._testing as tm
from pandas.arrays import SparseArray

# EA & Actual Dtypes
def to_ea_dtypes(dtypes):
    """ convert list of string dtypes to EA dtype """
    return [getattr(pd, dt + "Dtype") for dt in dtypes]

def to_numpy_dtypes(dtypes):
    """ convert list of string dtypes to numpy dtype """
    return [getattr(np, dt) for dt in dtypes if isinstance(dt, str)]

class TestPandasDtype:

    # Passing invalid dtype, both as a string or object, must raise TypeError
    # Per issue GH15520
    @pytest.mark.parametrize("box", [pd.Timestamp, "pd.Timestamp", list])
    def test_invalid_dtype_error(self, box):
        with pytest.raises(TypeError, match="not understood"):
            com.pandas_dtype(box)

    @pytest.mark.parametrize(
        "dtype",
        [
            object,
            "float64",
            np.object_,
            np.dtype("object"),
            "O",
            np.float64,
            float,
            np.dtype("float64"),
        ],
    )
    def test_pandas_dtype_valid(self, dtype):
        assert com.pandas_dtype(dtype) == dtype

    @pytest.mark.parametrize(
        "dtype", ["M8[ns]", "m8[ns]", "object", "float64", "int64"]
    )
    def test_numpy_dtype(self, dtype):
        assert com.pandas_dtype(dtype) == np.dtype(dtype)

    def test_numpy_string_dtype(self):
        # do not parse freq-like string as period dtype
        assert com.pandas_dtype("U") == np.dtype("U")
        assert com.pandas_dtype("S") == np.dtype("S")

    @pytest.mark.parametrize(
        "dtype",
        [
            "datetime64[ns, US/Eastern]",
            "datetime64[ns, Asia/Tokyo]",
            "datetime64[ns, UTC]",
            # GH#33885 check that the M8 alias is understood
            "M8[ns, US/Eastern]",
            "M8[ns, Asia/Tokyo]",
            "M8[ns, UTC]",
        ],
    )
    def test_datetimetz_dtype(self, dtype):
        assert com.pandas_dtype(dtype) == DatetimeTZDtype.construct_from_string(dtype)
        assert com.pandas_dtype(dtype) == dtype

    def test_categorical_dtype(self):
        assert com.pandas_dtype("category") == CategoricalDtype()

    @pytest.mark.parametrize(
        "dtype",
        [
            "period[D]",
            "period[3M]",
            "period[U]",
            "Period[D]",
            "Period[3M]",
            "Period[U]",
        ],
    )
    def test_period_dtype(self, dtype):
        assert com.pandas_dtype(dtype) is PeriodDtype(dtype)
        assert com.pandas_dtype(dtype) == PeriodDtype(dtype)
        assert com.pandas_dtype(dtype) == dtype

dtypes = dict(
    datetime_tz=com.pandas_dtype("datetime64[ns, US/Eastern]"),
    datetime=com.pandas_dtype("datetime64[ns]"),
    timedelta=com.pandas_dtype("timedelta64[ns]"),
    period=PeriodDtype("D"),
    integer=np.dtype(np.int64),
    float=np.dtype(np.float64),
    object=np.dtype(np.object),
    category=com.pandas_dtype("category"),
)

@pytest.mark.parametrize("name1,dtype1", list(dtypes.items()), ids=lambda x: str(x))
@pytest.mark.parametrize("name2,dtype2", list(dtypes.items()), ids=lambda x: str(x))
def test_dtype_equal(name1, dtype1, name2, dtype2):

    # match equal to self, but not equal to other
    assert com.is_dtype_equal(dtype1, dtype1)
    if name1 != name2:
        assert not com.is_dtype_equal(dtype1, dtype2)

@pytest.mark.parametrize(
    "dtype1,dtype2",
    [
        (np.int8, np.int64),
        (np.int16, np.int64),
        (np.int32, np.int64),
        (np.float32, np.float64),
        (PeriodDtype("D"), PeriodDtype("2D")),  # PeriodType
        (
            com.pandas_dtype("datetime64[ns, US/Eastern]"),
            com.pandas_dtype("datetime64[ns, CET]"),
        ),  # Datetime
        (None, None),  # gh-15941: no exception should be raised.
    ],
)
def test_dtype_equal_strict(dtype1, dtype2):
    assert not com.is_dtype_equal(dtype1, dtype2)

def get_is_dtype_funcs():
    """
    Get all functions in pandas.core.dtypes.common that
    begin with 'is_' and end with 'dtype'

    """
    fnames = [f for f in dir(com) if (f.startswith("is_") and f.endswith("dtype"))]
    return [getattr(com, fname) for fname in fnames]

@pytest.mark.parametrize("func", get_is_dtype_funcs(), ids=lambda x: x.__name__)
def test_get_dtype_error_catch(func):
    # see gh-15941
    #
    # No exception should be raised.

    assert not func(None)

def test_is_object():
    assert com.is_object_dtype(object)
    assert com.is_object_dtype(np.array([], dtype=object))

    assert not com.is_object_dtype(int)
    assert not com.is_object_dtype(np.array([], dtype=int))
    assert not com.is_object_dtype([1, 2, 3])

@pytest.mark.parametrize(
    "check_scipy", [False, pytest.param(True, marks=td.skip_if_no_scipy)]
)
def test_is_sparse(check_scipy):
    assert com.is_sparse(SparseArray([1, 2, 3]))

    assert not com.is_sparse(np.array([1, 2, 3]))

    if check_scipy:
        import scipy.sparse

        assert not com.is_sparse(scipy.sparse.bsr_matrix([1, 2, 3]))

@td.skip_if_no_scipy
def test_is_scipy_sparse():
    from scipy.sparse import bsr_matrix

    assert com.is_scipy_sparse(bsr_matrix([1, 2, 3]))

    assert not com.is_scipy_sparse(SparseArray([1, 2, 3]))

def test_is_categorical():
    cat = pd.Categorical([1, 2, 3])
    with tm.assert_produces_warning(FutureWarning):
        assert com.is_categorical(cat)
        assert com.is_categorical(pd.Series(cat))
        assert com.is_categorical(pd.CategoricalIndex([1, 2, 3]))

        assert not com.is_categorical([1, 2, 3])

def test_is_categorical_deprecation():
    # GH#33385
    with tm.assert_produces_warning(FutureWarning):
        com.is_categorical([1, 2, 3])

def test_is_datetime64_dtype():
    assert not com.is_datetime64_dtype(object)
    assert not com.is_datetime64_dtype([1, 2, 3])
    assert not com.is_datetime64_dtype(np.array([], dtype=int))

    assert com.is_datetime64_dtype(np.datetime64)
    assert com.is_datetime64_dtype(np.array([], dtype=np.datetime64))

def test_is_datetime64tz_dtype():
    assert not com.is_datetime64tz_dtype(object)
    assert not com.is_datetime64tz_dtype([1, 2, 3])
    assert not com.is_datetime64tz_dtype(pd.DatetimeIndex([1, 2, 3]))
    assert com.is_datetime64tz_dtype(pd.DatetimeIndex(["2000"], tz="US/Eastern"))

def test_is_timedelta64_dtype():
    assert not com.is_timedelta64_dtype(object)
    assert not com.is_timedelta64_dtype(None)
    assert not com.is_timedelta64_dtype([1, 2, 3])
    assert not com.is_timedelta64_dtype(np.array([], dtype=np.datetime64))
    assert not com.is_timedelta64_dtype("0 days")
    assert not com.is_timedelta64_dtype("0 days 00:00:00")
    assert not com.is_timedelta64_dtype(["0 days 00:00:00"])
    assert not com.is_timedelta64_dtype("NO DATE")

    assert com.is_timedelta64_dtype(np.timedelta64)
    assert com.is_timedelta64_dtype(pd.Series([], dtype="timedelta64[ns]"))
    assert com.is_timedelta64_dtype(pd.to_timedelta(["0 days", "1 days"]))

def test_is_period_dtype():
    assert not com.is_period_dtype(object)
    assert not com.is_period_dtype([1, 2, 3])
    assert not com.is_period_dtype(pd.Period("2017-01-01"))

    assert com.is_period_dtype(PeriodDtype(freq="D"))
    assert com.is_period_dtype(pd.PeriodIndex([], freq="A"))

def test_is_interval_dtype():
    assert not com.is_interval_dtype(object)
    assert not com.is_interval_dtype([1, 2, 3])

    assert com.is_interval_dtype(IntervalDtype())

    interval = pd.Interval(1, 2, closed="right")
    assert not com.is_interval_dtype(interval)
    assert com.is_interval_dtype(pd.IntervalIndex([interval]))

def test_is_categorical_dtype():
    assert not com.is_categorical_dtype(object)
    assert not com.is_categorical_dtype([1, 2, 3])

    assert com.is_categorical_dtype(CategoricalDtype())
    assert com.is_categorical_dtype(pd.Categorical([1, 2, 3]))
    assert com.is_categorical_dtype(pd.CategoricalIndex([1, 2, 3]))

def test_is_string_dtype():
    assert not com.is_string_dtype(int)
    assert not com.is_string_dtype(pd.Series([1, 2]))

    assert com.is_string_dtype(str)
    assert com.is_string_dtype(object)
    assert com.is_string_dtype(np.array(["a", "b"]))
    assert com.is_string_dtype(pd.StringDtype())
    assert com.is_string_dtype(pd.array(["a", "b"], dtype="string"))

integer_dtypes: List = []

@pytest.mark.parametrize(
    "dtype",
    integer_dtypes
    + [pd.Series([1, 2])]
    + tm.ALL_INT_DTYPES
    + to_numpy_dtypes(tm.ALL_INT_DTYPES)
    + tm.ALL_EA_INT_DTYPES
    + to_ea_dtypes(tm.ALL_EA_INT_DTYPES),
)
def test_is_integer_dtype(dtype):
    assert com.is_integer_dtype(dtype)

@pytest.mark.parametrize(
    "dtype",
    [
        str,
        float,
        np.datetime64,
        np.timedelta64,
        pd.Index([1, 2.0]),
        np.array(["a", "b"]),
        np.array([], dtype=np.timedelta64),
    ],
)
def test_is_not_integer_dtype(dtype):
    assert not com.is_integer_dtype(dtype)

signed_integer_dtypes: List = []

@pytest.mark.parametrize(
    "dtype",
    signed_integer_dtypes
    + [pd.Series([1, 2])]
    + tm.SIGNED_INT_DTYPES
    + to_numpy_dtypes(tm.SIGNED_INT_DTYPES)
    + tm.SIGNED_EA_INT_DTYPES
    + to_ea_dtypes(tm.SIGNED_EA_INT_DTYPES),
)
def test_is_signed_integer_dtype(dtype):
    assert com.is_integer_dtype(dtype)

@pytest.mark.parametrize(
    "dtype",
    [
        str,
        float,
        np.datetime64,
        np.timedelta64,
        pd.Index([1, 2.0]),
        np.array(["a", "b"]),
        np.array([], dtype=np.timedelta64),
    ]
    + tm.UNSIGNED_INT_DTYPES
    + to_numpy_dtypes(tm.UNSIGNED_INT_DTYPES)
    + tm.UNSIGNED_EA_INT_DTYPES
    + to_ea_dtypes(tm.UNSIGNED_EA_INT_DTYPES),
)
def test_is_not_signed_integer_dtype(dtype):
    assert not com.is_signed_integer_dtype(dtype)

unsigned_integer_dtypes: List = []

@pytest.mark.parametrize(
    "dtype",
    unsigned_integer_dtypes
    + [pd.Series([1, 2], dtype=np.uint32)]
    + tm.UNSIGNED_INT_DTYPES
    + to_numpy_dtypes(tm.UNSIGNED_INT_DTYPES)
    + tm.UNSIGNED_EA_INT_DTYPES
    + to_ea_dtypes(tm.UNSIGNED_EA_INT_DTYPES),
)
def test_is_unsigned_integer_dtype(dtype):
    assert com.is_unsigned_integer_dtype(dtype)

@pytest.mark.parametrize(
    "dtype",
    [
        str,
        float,
        np.datetime64,
        np.timedelta64,
        pd.Index([1, 2.0]),
        np.array(["a", "b"]),
        np.array([], dtype=np.timedelta64),
    ]
    + tm.SIGNED_INT_DTYPES
    + to_numpy_dtypes(tm.SIGNED_INT_DTYPES)
    + tm.SIGNED_EA_INT_DTYPES
    + to_ea_dtypes(tm.SIGNED_EA_INT_DTYPES),
)
def test_is_not_unsigned_integer_dtype(dtype):
    assert not com.is_unsigned_integer_dtype(dtype)

@pytest.mark.parametrize(
    "dtype", [np.int64, np.array([1, 2], dtype=np.int64), "Int64", pd.Int64Dtype]
)
def test_is_int64_dtype(dtype):
    assert com.is_int64_dtype(dtype)

@pytest.mark.parametrize(
    "dtype",
    [
        str,
        float,
        np.int32,
        np.uint64,
        pd.Index([1, 2.0]),
        np.array(["a", "b"]),
        np.array([1, 2], dtype=np.uint32),
        "int8",
        "Int8",
        pd.Int8Dtype,
    ],
)
def test_is_not_int64_dtype(dtype):
    assert not com.is_int64_dtype(dtype)

def test_is_datetime64_any_dtype():
    assert not com.is_datetime64_any_dtype(int)
    assert not com.is_datetime64_any_dtype(str)
    assert not com.is_datetime64_any_dtype(np.array([1, 2]))
    assert not com.is_datetime64_any_dtype(np.array(["a", "b"]))

    assert com.is_datetime64_any_dtype(np.datetime64)
    assert com.is_datetime64_any_dtype(np.array([], dtype=np.datetime64))
    assert com.is_datetime64_any_dtype(DatetimeTZDtype("ns", "US/Eastern"))
    assert com.is_datetime64_any_dtype(
        pd.DatetimeIndex([1, 2, 3], dtype="datetime64[ns]")
    )

def test_is_datetime64_ns_dtype():
    assert not com.is_datetime64_ns_dtype(int)
    assert not com.is_datetime64_ns_dtype(str)
    assert not com.is_datetime64_ns_dtype(np.datetime64)
    assert not com.is_datetime64_ns_dtype(np.array([1, 2]))
    assert not com.is_datetime64_ns_dtype(np.array(["a", "b"]))
    assert not com.is_datetime64_ns_dtype(np.array([], dtype=np.datetime64))

    # This datetime array has the wrong unit (ps instead of ns)
    assert not com.is_datetime64_ns_dtype(np.array([], dtype="datetime64[ps]"))

    assert com.is_datetime64_ns_dtype(DatetimeTZDtype("ns", "US/Eastern"))
    assert com.is_datetime64_ns_dtype(
        pd.DatetimeIndex([1, 2, 3], dtype=np.dtype("datetime64[ns]"))
    )

def test_is_timedelta64_ns_dtype():
    assert not com.is_timedelta64_ns_dtype(np.dtype("m8[ps]"))
    assert not com.is_timedelta64_ns_dtype(np.array([1, 2], dtype=np.timedelta64))

    assert com.is_timedelta64_ns_dtype(np.dtype("m8[ns]"))
    assert com.is_timedelta64_ns_dtype(np.array([1, 2], dtype="m8[ns]"))

def test_is_datetime_or_timedelta_dtype():
    assert not com.is_datetime_or_timedelta_dtype(int)
    assert not com.is_datetime_or_timedelta_dtype(str)
    assert not com.is_datetime_or_timedelta_dtype(pd.Series([1, 2]))
    assert not com.is_datetime_or_timedelta_dtype(np.array(["a", "b"]))

    # TODO(jreback), this is slightly suspect
    assert not com.is_datetime_or_timedelta_dtype(DatetimeTZDtype("ns", "US/Eastern"))

    assert com.is_datetime_or_timedelta_dtype(np.datetime64)
    assert com.is_datetime_or_timedelta_dtype(np.timedelta64)
    assert com.is_datetime_or_timedelta_dtype(np.array([], dtype=np.timedelta64))
    assert com.is_datetime_or_timedelta_dtype(np.array([], dtype=np.datetime64))

def test_is_numeric_v_string_like():
    assert not com.is_numeric_v_string_like(1, 1)
    assert not com.is_numeric_v_string_like(1, "foo")
    assert not com.is_numeric_v_string_like("foo", "foo")
    assert not com.is_numeric_v_string_like(np.array([1]), np.array([2]))
    assert not com.is_numeric_v_string_like(np.array(["foo"]), np.array(["foo"]))

    assert com.is_numeric_v_string_like(np.array([1]), "foo")
    assert com.is_numeric_v_string_like("foo", np.array([1]))
    assert com.is_numeric_v_string_like(np.array([1, 2]), np.array(["foo"]))
    assert com.is_numeric_v_string_like(np.array(["foo"]), np.array([1, 2]))

def test_is_datetimelike_v_numeric():
    dt = np.datetime64(datetime(2017, 1, 1))

    assert not com.is_datetimelike_v_numeric(1, 1)
    assert not com.is_datetimelike_v_numeric(dt, dt)
    assert not com.is_datetimelike_v_numeric(np.array([1]), np.array([2]))
    assert not com.is_datetimelike_v_numeric(np.array([dt]), np.array([dt]))

    assert com.is_datetimelike_v_numeric(1, dt)
    assert com.is_datetimelike_v_numeric(1, dt)
    assert com.is_datetimelike_v_numeric(np.array([dt]), 1)
    assert com.is_datetimelike_v_numeric(np.array([1]), dt)
    assert com.is_datetimelike_v_numeric(np.array([dt]), np.array([1]))

def test_needs_i8_conversion():
    assert not com.needs_i8_conversion(str)
    assert not com.needs_i8_conversion(np.int64)
    assert not com.needs_i8_conversion(pd.Series([1, 2]))
    assert not com.needs_i8_conversion(np.array(["a", "b"]))

    assert com.needs_i8_conversion(np.datetime64)
    assert com.needs_i8_conversion(pd.Series([], dtype="timedelta64[ns]"))
    assert com.needs_i8_conversion(pd.DatetimeIndex(["2000"], tz="US/Eastern"))

def test_is_numeric_dtype():
    assert not com.is_numeric_dtype(str)
    assert not com.is_numeric_dtype(np.datetime64)
    assert not com.is_numeric_dtype(np.timedelta64)
    assert not com.is_numeric_dtype(np.array(["a", "b"]))
    assert not com.is_numeric_dtype(np.array([], dtype=np.timedelta64))

    assert com.is_numeric_dtype(int)
    assert com.is_numeric_dtype(float)
    assert com.is_numeric_dtype(np.uint64)
    assert com.is_numeric_dtype(pd.Series([1, 2]))
    assert com.is_numeric_dtype(pd.Index([1, 2.0]))

def test_is_string_like_dtype():
    assert not com.is_string_like_dtype(object)
    assert not com.is_string_like_dtype(pd.Series([1, 2]))

    assert com.is_string_like_dtype(str)
    assert com.is_string_like_dtype(np.array(["a", "b"]))

def test_is_float_dtype():
    assert not com.is_float_dtype(str)
    assert not com.is_float_dtype(int)
    assert not com.is_float_dtype(pd.Series([1, 2]))
    assert not com.is_float_dtype(np.array(["a", "b"]))

    assert com.is_float_dtype(float)
    assert com.is_float_dtype(pd.Index([1, 2.0]))

def test_is_bool_dtype():
    assert not com.is_bool_dtype(int)
    assert not com.is_bool_dtype(str)
    assert not com.is_bool_dtype(pd.Series([1, 2]))
    assert not com.is_bool_dtype(np.array(["a", "b"]))
    assert not com.is_bool_dtype(pd.Index(["a", "b"]))

    assert com.is_bool_dtype(bool)
    assert com.is_bool_dtype(np.bool)
    assert com.is_bool_dtype(np.array([True, False]))
    assert com.is_bool_dtype(pd.Index([True, False]))

    assert com.is_bool_dtype(pd.BooleanDtype())
    assert com.is_bool_dtype(pd.array([True, False, None], dtype="boolean"))

@pytest.mark.filterwarnings("ignore:'is_extension_type' is deprecated:FutureWarning")
@pytest.mark.parametrize(
    "check_scipy", [False, pytest.param(True, marks=td.skip_if_no_scipy)]
)
def test_is_extension_type(check_scipy):
    assert not com.is_extension_type([1, 2, 3])
    assert not com.is_extension_type(np.array([1, 2, 3]))
    assert not com.is_extension_type(pd.DatetimeIndex([1, 2, 3]))

    cat = pd.Categorical([1, 2, 3])
    assert com.is_extension_type(cat)
    assert com.is_extension_type(pd.Series(cat))
    assert com.is_extension_type(SparseArray([1, 2, 3]))
    assert com.is_extension_type(pd.DatetimeIndex(["2000"], tz="US/Eastern"))

    dtype = DatetimeTZDtype("ns", tz="US/Eastern")
    s = pd.Series([], dtype=dtype)
    assert com.is_extension_type(s)

    if check_scipy:
        import scipy.sparse

        assert not com.is_extension_type(scipy.sparse.bsr_matrix([1, 2, 3]))

def test_is_extension_type_deprecation():
    with tm.assert_produces_warning(FutureWarning):
        com.is_extension_type([1, 2, 3])

@pytest.mark.parametrize(
    "check_scipy", [False, pytest.param(True, marks=td.skip_if_no_scipy)]
)
def test_is_extension_array_dtype(check_scipy):
    assert not com.is_extension_array_dtype([1, 2, 3])
    assert not com.is_extension_array_dtype(np.array([1, 2, 3]))
    assert not com.is_extension_array_dtype(pd.DatetimeIndex([1, 2, 3]))

    cat = pd.Categorical([1, 2, 3])
    assert com.is_extension_array_dtype(cat)
    assert com.is_extension_array_dtype(pd.Series(cat))
    assert com.is_extension_array_dtype(SparseArray([1, 2, 3]))
    assert com.is_extension_array_dtype(pd.DatetimeIndex(["2000"], tz="US/Eastern"))

    dtype = DatetimeTZDtype("ns", tz="US/Eastern")
    s = pd.Series([], dtype=dtype)
    assert com.is_extension_array_dtype(s)

    if check_scipy:
        import scipy.sparse

        assert not com.is_extension_array_dtype(scipy.sparse.bsr_matrix([1, 2, 3]))

def test_is_complex_dtype():
    assert not com.is_complex_dtype(int)
    assert not com.is_complex_dtype(str)
    assert not com.is_complex_dtype(pd.Series([1, 2]))
    assert not com.is_complex_dtype(np.array(["a", "b"]))

    assert com.is_complex_dtype(np.complex)
    assert com.is_complex_dtype(np.array([1 + 1j, 5]))

@pytest.mark.parametrize(
    "input_param,result",
    [
        (int, np.dtype(int)),
        ("int32", np.dtype("int32")),
        (float, np.dtype(float)),
        ("float64", np.dtype("float64")),
        (np.dtype("float64"), np.dtype("float64")),
        (str, np.dtype(str)),
        (pd.Series([1, 2], dtype=np.dtype("int16")), np.dtype("int16")),
        (pd.Series(["a", "b"]), np.dtype(object)),
        (pd.Index([1, 2]), np.dtype("int64")),
        (pd.Index(["a", "b"]), np.dtype(object)),
        ("category", "category"),
        (pd.Categorical(["a", "b"]).dtype, CategoricalDtype(["a", "b"])),
        (pd.Categorical(["a", "b"]), CategoricalDtype(["a", "b"])),
        (pd.CategoricalIndex(["a", "b"]).dtype, CategoricalDtype(["a", "b"])),
        (pd.CategoricalIndex(["a", "b"]), CategoricalDtype(["a", "b"])),
        (CategoricalDtype(), CategoricalDtype()),
        (CategoricalDtype(["a", "b"]), CategoricalDtype()),
        (pd.DatetimeIndex([1, 2]), np.dtype("=M8[ns]")),
        (pd.DatetimeIndex([1, 2]).dtype, np.dtype("=M8[ns]")),
        ("<M8[ns]", np.dtype("<M8[ns]")),
        ("datetime64[ns, Europe/London]", DatetimeTZDtype("ns", "Europe/London")),
        (PeriodDtype(freq="D"), PeriodDtype(freq="D")),
        ("period[D]", PeriodDtype(freq="D")),
        (IntervalDtype(), IntervalDtype()),
    ],
)
def test__get_dtype(input_param, result):
    assert com._get_dtype(input_param) == result

@pytest.mark.parametrize(
    "input_param,expected_error_message",
    [
        (None, "Cannot deduce dtype from null object"),
        (1, "data type not understood"),
        (1.2, "data type not understood"),
        # numpy dev changed from double-quotes to single quotes
        ("random string", "data type [\"']random string[\"'] not understood"),
        (pd.DataFrame([1, 2]), "data type not understood"),
    ],
)
def test__get_dtype_fails(input_param, expected_error_message):
    # python objects
    # 2020-02-02 npdev changed error message
    expected_error_message += f"|Cannot interpret '{input_param}' as a data type"
    with pytest.raises(TypeError, match=expected_error_message):
        com._get_dtype(input_param)

@pytest.mark.parametrize(
    "input_param,result",
    [
        (int, np.dtype(int).type),
        ("int32", np.int32),
        (float, np.dtype(float).type),
        ("float64", np.float64),
        (np.dtype("float64"), np.float64),
        (str, np.dtype(str).type),
        (pd.Series([1, 2], dtype=np.dtype("int16")), np.int16),
        (pd.Series(["a", "b"]), np.object_),
        (pd.Index([1, 2], dtype="int64"), np.int64),
        (pd.Index(["a", "b"]), np.object_),
        ("category", CategoricalDtypeType),
        (pd.Categorical(["a", "b"]).dtype, CategoricalDtypeType),
        (pd.Categorical(["a", "b"]), CategoricalDtypeType),
        (pd.CategoricalIndex(["a", "b"]).dtype, CategoricalDtypeType),
        (pd.CategoricalIndex(["a", "b"]), CategoricalDtypeType),
        (pd.DatetimeIndex([1, 2]), np.datetime64),
        (pd.DatetimeIndex([1, 2]).dtype, np.datetime64),
        ("<M8[ns]", np.datetime64),
        (pd.DatetimeIndex(["2000"], tz="Europe/London"), pd.Timestamp),
        (pd.DatetimeIndex(["2000"], tz="Europe/London").dtype, pd.Timestamp),
        ("datetime64[ns, Europe/London]", pd.Timestamp),
        (PeriodDtype(freq="D"), pd.Period),
        ("period[D]", pd.Period),
        (IntervalDtype(), pd.Interval),
        (None, type(None)),
        (1, type(None)),
        (1.2, type(None)),
        (pd.DataFrame([1, 2]), type(None)),  # composite dtype
    ],
)
def test__is_dtype_type(input_param, result):
    assert com._is_dtype_type(input_param, lambda tipo: tipo == result)

@pytest.mark.parametrize("val", [np.datetime64("NaT"), np.timedelta64("NaT")])
@pytest.mark.parametrize("typ", [np.int64])
def test_astype_nansafe(val, typ):
    arr = np.array([val])

    msg = "Cannot convert NaT values to integer"
    with pytest.raises(ValueError, match=msg):
        astype_nansafe(arr, dtype=typ)

@pytest.mark.parametrize("from_type", [np.datetime64, np.timedelta64])
@pytest.mark.parametrize(
    "to_type",
    [
        np.uint8,
        np.uint16,
        np.uint32,
        np.int8,
        np.int16,
        np.int32,
        np.float16,
        np.float32,
    ],
)
def test_astype_datetime64_bad_dtype_raises(from_type, to_type):
    arr = np.array([from_type("2018")])

    with pytest.raises(TypeError, match="cannot astype"):
        astype_nansafe(arr, dtype=to_type)

@pytest.mark.parametrize("from_type", [np.datetime64, np.timedelta64])
def test_astype_object_preserves_datetime_na(from_type):
    arr = np.array([from_type("NaT")])
    result = astype_nansafe(arr, dtype="object")

    assert isna(result)[0]