text:
/*
 * To change this template, choose Tools | Templates and open the template in the editor.
 */

package armyc2.c2sd.renderer.utilities;

import android.util.Log;

import java.util.HashMap;
import java.util.logging.Level;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author michael.spinelli
 */
public class UnitFontLookup
{

    private static boolean _initCalled = false;
    private static UnitFontLookup _instance;
    private boolean _ready = false;
    private static HashMap<String, UnitFontLookupInfo> hashMapB = new HashMap<String, UnitFontLookupInfo>();
    private static HashMap<String, UnitFontLookupInfo> hashMapC = new HashMap<String, UnitFontLookupInfo>();

    // UNKNOWN FILL Indexes
    private static final int FillIndexUZ = 800;// Unknown
    private static final int FillIndexUP = 849;// Space
    private static final int FillIndexUA = 825;// Air
    private static final int FillIndexUG = 800;// Ground
    private static final int FillIndexUGE = 800;// Ground Equipment
    private static final int FillIndexUS = 800;// Sea Surface
    private static final int FillIndexUU = 837;// Subsurface
    private static final int FillIndexUF = 800;// SOF
    // FRIENDLY FILL Indexes
    private static final int FillIndexFZ = 812;
    private static final int FillIndexFP = 843;
    private static final int FillIndexFA = 819;
    private static final int FillIndexFG = 803;
    private static final int FillIndexFGE = 812;
    private static final int FillIndexFS = 812;
    private static final int FillIndexFU = 831;
    private static final int FillIndexFF = 803;
    // NEUTRAL FILL Indexes
    private static final int FillIndexNZ = 809;
    private static final int FillIndexNP = 846;
    private static final int FillIndexNA = 822;
    private static final int FillIndexNG = 809;
    private static final int FillIndexNGE = 809;
    private static final int FillIndexNS = 809;
    private static final int FillIndexNU = 834;
    private static final int FillIndexNF = 809;
    // HOSTILE FILL Indexes
    private static final int FillIndexHZ = 806;
    private static final int FillIndexHP = 840;
    private static final int FillIndexHA = 816;
    private static final int FillIndexHG = 806;
    private static final int FillIndexHGE = 806;
    private static final int FillIndexHS = 806;
    private static final int FillIndexHU = 828;
    private static final int FillIndexHF = 806;

    // Font positions for new layout
    // 770-799: small fills, inside the frame
    // 800-900: regular fills with solid & dashed frame
    // 1000 - 3000?: Warfighting - A -
    // 3000 - 3200?: SigInt - D - 80 only need fill/frame/symbol
    // 3200? - 3400?: Stability Operations Symbology - E - 60 w/ 6 that need 4 symbols & 6 with secondary
    // symbol / fill
    // 4000+: Emergency Management Symbols - G -

    //
    public boolean getReady()
    {
        return this._ready;
    }

    private UnitFontLookup()
    {

    }

    public static synchronized UnitFontLookup getInstance()
    {
        if (_instance == null) {
            _instance = new UnitFontLookup();
        }
        return _instance;
    }

    public synchronized void init(String[] unitFontMappingsStream)
    {
        if (_initCalled == false) {
            _instance = new UnitFontLookup();
            String lookupXmlB = unitFontMappingsStream[0];// FileHandler.InputStreamToString(xmlStreamB);
            String lookupXmlC = unitFontMappingsStream[1];// FileHandler.InputStreamToString(xmlStreamC);

            populateLookup(lookupXmlB, RendererSettings.Symbology_2525B);
            populateLookup(lookupXmlC, RendererSettings.Symbology_2525C);

            _initCalled = true;
        }
    }

    private static void populateLookup(String xml, int SymbologyStandard)
    {
        Document document = XMLParser.getDomElement(xml);

        NodeList symbols = XMLUtil.getItemList(document, "SYMBOL");
        for (int i = 0; i < symbols.getLength(); i++) {
            Node node = symbols.item(i);

            String ID = XMLUtil.parseTagValue(node, "SYMBOLID");
            String description = XMLUtil.parseTagValue(node, "DESCRIPTION");
            String m1u = XMLUtil.parseTagValue(node, "MAPPING1U");
            String m1f = XMLUtil.parseTagValue(node, "MAPPING1F");
            String m1n = XMLUtil.parseTagValue(node, "MAPPING1N");
            String m1h = XMLUtil.parseTagValue(node, "MAPPING1H");
            String m2 = XMLUtil.parseTagValue(node, "MAPPING2");
            String c1 = XMLUtil.parseTagValue(node, "MAPPING1COLOR");
            String c2 = XMLUtil.parseTagValue(node, "MAPPING2COLOR");

            UnitFontLookupInfo uflTemp = null;

            // Check for bad font locations and remap
            m1u = checkMappingIndex(m1u);
            m1f = checkMappingIndex(m1f);
            m1n = checkMappingIndex(m1n);
            m1h = checkMappingIndex(m1h);
            m2 = checkMappingIndex(m2);
            ////////////////////////////////////////

            uflTemp = new UnitFontLookupInfo(ID, description, m1u, m1f, m1n, m1h, c1, m2, c2);

            if (uflTemp != null) {
                if (SymbologyStandard == RendererSettings.Symbology_2525B)
                    hashMapB.put(ID, uflTemp);
                else if (SymbologyStandard == RendererSettings.Symbology_2525C)
                    hashMapC.put(ID, uflTemp);
            }
        }
    }

    /**
     * Until XML files are updated, we need to shift the index
     *
     * @param index
     * @return
     */
    private static String checkMappingIndex(String index)
    {
        int i = -1;
        if (SymbolUtilities.isNumber(index)) {
            i = Integer.valueOf(index);

            if (i < 9000)
                return String.valueOf(i + 57000);
            else
                return String.valueOf(i + 54000);

        }

        return index;// */

    }

    /**
     * we only have font lookups for F,H,N,U. But the shapes match one of these four for the remaining
     * affiliations. So we convert the string to a base affiliation before we do the lookup.
     *
     * @param symbolID
     * @return
     */
    private String resolveAffiliation(String symbolID)
    {
        String code = symbolID.substring(0);
        String affiliation = symbolID.substring(1, 2);

        if (affiliation.equals("F") || // friendly
                affiliation.equals("H") || // hostile
                affiliation.equals("U") || // unknown
                affiliation.equals("N"))// neutral
            return code;
        else if (affiliation.equals("S"))// suspect
            code = code.substring(0, 1) + "H" + code.substring(2, 15);
        else if (affiliation.equals("L"))// exercise neutral
            code = code.substring(0, 1) + "N" + code.substring(2, 15);
        else if (affiliation.equals("A") || // assumed friend
                affiliation.equals("D") || // exercise friend
                affiliation.equals("M") || // exercise assumed friend
                affiliation.equals("K") || // faker
                affiliation.equals("J"))// joker
            code = code.substring(0, 1) + "F" + code.substring(2, 15);
        else if (affiliation.equals("P") || // pending
                affiliation.equals("G") || // exercise pending
                affiliation.equals("O") || // ? brought it over from mitch's code
                affiliation.equals("W"))// exercise unknown
            code = code.substring(0, 1) + "U" + code.substring(2, 15);
        else
            code = code.substring(0, 1) + "U" + code.substring(2, 15);

        return code;
    }

    public static UnitFontLookupInfo adjustSubSurfaceIfNot2525C(UnitFontLookupInfo original)
    {
        UnitFontLookupInfo result = null;

        return result;
    }

    /**
     * 2525C returns the character index for the fill frame based on the symbol code.
     *
     * @param SymbolID 15 character symbol ID
     * @param symStd 0 for 2525B, 1 for 2525C
     * @return fill character index
     */
    public static int getFillCode(String SymbolID, int symStd)
    {
        int returnVal = -1;

        char scheme = 0;
        char battleDimension = 0;
        char status = 0;
        char affiliation = 0;
        char grdtrkSubset = 0;
        // char foo = 'a';

        try {
            // to upper
            if (SymbolID != null && SymbolID.length() >= 10) {
                scheme = SymbolID.charAt(0);// S,O,E,I,etc...
                affiliation = SymbolID.charAt(1);// F,H,N,U,etc...
                battleDimension = SymbolID.charAt(2);// P,A,G,S,U,F,X,Z
                status = SymbolID.charAt(3);// A,P,C,D,X,F
                grdtrkSubset = SymbolID.charAt(4);

                if (scheme == 'S')// Warfighting symbols
                {
                    if (affiliation == 'F' || affiliation == 'A' || affiliation == 'D' || affiliation == 'M'
                            || affiliation == 'J' || affiliation == 'K') {
                        if (battleDimension == 'F' || battleDimension == 'G')// ground & SOF
                        {
                            if (battleDimension == 'F' || (battleDimension == 'G' && (grdtrkSubset == 'U'
                                    || grdtrkSubset == 'I' || grdtrkSubset == '0' || grdtrkSubset == '-'))) {
                                returnVal = 803;
                            } else if (battleDimension == 'G' && grdtrkSubset == 'E') {
                                returnVal = 812;
                            } else
                                returnVal = 803;
                        } else if (battleDimension == 'A')// Air
                        {
                            returnVal = 819;
                        } else if (battleDimension == 'S')// SeaSurface
                        {
                            returnVal = getSeaSurfaceFill(SymbolID);
                        } else if (battleDimension == 'U')// Subsurface
                        {
                            returnVal = getSubSurfaceFill(SymbolID);
                        } else if (battleDimension == 'P')// space
                        {
                            if (symStd == 0)
                                returnVal = 819;
                            else
                                returnVal = 843;
                        } else// if(battleDimension=='Z')//unknown
                        {
                            returnVal = 812;// index in font file
                        }

                    } else if (affiliation == 'H' || affiliation == 'S')// hostile,suspect
                    {
                        if (battleDimension == 'Z')// unknown
                        {
                            returnVal = 806;// index in font file
                        } else if (battleDimension == 'F' || battleDimension == 'G')// ground & SOF
                        {
                            returnVal = 806;
                        } else if (battleDimension == 'A')// Air
                        {
                            returnVal = 816;
                        } else if (battleDimension == 'S')// SeaSurface
                        {
                            returnVal = getSeaSurfaceFill(SymbolID);
                        } else if (battleDimension == 'U')// Subsurface
                        {
                            returnVal = getSubSurfaceFill(SymbolID);
                        } else if (battleDimension == 'P')// space
                        {
                            if (symStd == 0)
                                returnVal = 816;
                            else
                                returnVal = 840;
                        } else
                            returnVal = 806;
                    } else if (affiliation == 'N' || affiliation == 'L')// neutral,exercise neutral
                    {
                        if (battleDimension == 'Z')// unknown
                        {
                            returnVal = 809;// index in font file
                        } else if (battleDimension == 'F' || battleDimension == 'G')// ground & SOF
                        {
                            returnVal = 809;
                        } else if (battleDimension == 'A')// Air
                        {
                            returnVal = 822;
                        } else if (battleDimension == 'S')// SeaSurface
                        {
                            returnVal = getSeaSurfaceFill(SymbolID);
                        } else if (battleDimension == 'U')// Subsurface
                        {
                            returnVal = getSubSurfaceFill(SymbolID);
                        } else if (battleDimension == 'P')// space
                        {
                            if (symStd == 0)
                                returnVal = 822;
                            else
                                returnVal = 846;
                        } else
                            returnVal = 809;
                    } else /*
                            * if(affiliation == 'P' || affiliation == 'U' || affiliation == 'G' || affiliation
                            * == 'W')
                            */ // these or any bad values
                    {

                        if (battleDimension == 'Z' || // unknown
                                battleDimension == 'G' || // ground
                                battleDimension == 'F')// SOF
                        {
                            returnVal = 800;// index in font file
                        } else if (battleDimension == 'A')// Air
                        {
                            returnVal = 825;
                        } else if (battleDimension == 'S')// SeaSurface
                        {
                            returnVal = getSeaSurfaceFill(SymbolID);
                        } else if (battleDimension == 'U')// Subsurface
                        {
                            returnVal = getSubSurfaceFill(SymbolID);
                        } else if (battleDimension == 'P')// space
                        {
                            if (symStd == 0)
                                returnVal = 825;
                            else
                                returnVal = 849;
                        } else
                            returnVal = 800;
                    }
                } // end if scheme == 's'
                else if (scheme == 'E')// Emergency Management Symbols
                {
                    if (battleDimension != 'N')// if not EMS natural event
                    {
                        if (affiliation == 'F' || affiliation == 'A' || affiliation == 'D'
                                || affiliation == 'M' || affiliation == 'J' || affiliation == 'K') {

                            // EMS symbols break some rules about symbol codes
                            if (SymbolUtilities.isEMSEquipment(SymbolID))
                                returnVal = 812;
                            else
                                returnVal = 803;
                        } else if (affiliation == 'H' || affiliation == 'S')// hostile,suspect
                        {
                            returnVal = 806;// index in font file

                        } else if (affiliation == 'N' || affiliation == 'L')// neutral,exercise neutral
                        {
                            returnVal = 809;
                        } else /*
                                * if(affiliation == 'P' || affiliation == 'U' || affiliation == 'G' ||
                                * affiliation == 'W')
                                */
                        {
                            returnVal = 800;// index in font file
                        }
                    } else // natural events do not have a fill/frame
                    {
                        returnVal = -1;
                    }
                } // end if scheme == 'E'
                else if (scheme == 'I')// Also default behavior
                {
                    if (affiliation == 'F' || affiliation == 'A' || affiliation == 'D' || affiliation == 'M'
                            || affiliation == 'J' || affiliation == 'K') {
                        if (battleDimension == 'Z')// unknown
                        {
                            returnVal = 812;// index in font file
                        } else if (battleDimension == 'F' || battleDimension == 'G' || battleDimension == 'S')// ground
                                                                                // &
                                                                                // SOF
                                                                                // &
                                                                                // sea
                                                                                // surface
                        {
                            if (scheme == 'I')
                                returnVal = 812;
                            else
                                returnVal = 803;
                        } else if (battleDimension == 'A')// Air
                        {
                            returnVal = 819;
                        } else if (battleDimension == 'U')// Subsurface
                        {
                            returnVal = 831;
                        } else if (battleDimension == 'P')// space
                        {
                            if (symStd == 0)
                                returnVal = 819;
                            else
                                returnVal = 843;
                        } else {
                            if (scheme == 'I')
                                returnVal = 812;
                            else
                                returnVal = 803;
                        }
                    }
                    if (affiliation == 'H' || affiliation == 'S')// hostile,suspect
                    {
                        if (battleDimension == 'Z')// unknown
                        {
                            returnVal = 806;// index in font file
                        } else if (battleDimension == 'F' || battleDimension == 'G' || battleDimension == 'S')// ground
                                                                                // &
                                                                                // SOF
                                                                                // &
                                                                                // sea
                                                                                // surface
                        {
                            returnVal = 806;
                        } else if (battleDimension == 'A')// Air
                        {
                            returnVal = 816;
                        } else if (battleDimension == 'U')// Subsurface
                        {
                            returnVal = 828;
                        } else if (battleDimension == 'P')// space
                        {
                            if (symStd == 0)
                                returnVal = 816;
                            else
                                returnVal = 840;
                        } else {
                            returnVal = 806;
                        }
                    }
                    if (affiliation == 'N' || affiliation == 'L')// neutral,exercise neutral
                    {
                        if (battleDimension == 'Z')// unknown
                        {
                            returnVal = 809;// index in font file
                        } else if (battleDimension == 'F' || battleDimension == 'G' || battleDimension == 'S')// ground
                                                                                // &
                                                                                // SOF
                                                                                // &
                                                                                // sea
                                                                                // surface
                        {
                            returnVal = 809;
                        } else if (battleDimension == 'A')// Air
                        {
                            returnVal = 822;
                        } else if (battleDimension == 'U')// Subsurface
                        {
                            returnVal = 834;
                        } else if (battleDimension == 'P')// space
                        {
                            if (symStd == 0)
                                returnVal = 822;
                            else
                                returnVal = 846;
                        } else {
                            returnVal = 809;
                        }
                    } else if (affiliation == 'P' || affiliation == 'U' || affiliation == 'G'
                            || affiliation == 'W') {

                        if (battleDimension == 'Z' || // unknown
                                battleDimension == 'G' || // ground
                                battleDimension == 'S' || // sea surface
                                battleDimension == 'F')// SOF
                        {
                            returnVal = 800;// index in font file
                        } else if (battleDimension == 'A')// Air
                        {
                            returnVal = 825;
                        } else if (battleDimension == 'U')// Subsurface
                        {
                            returnVal = 837;
                        } else if (battleDimension == 'P')// Space
                        {
                            if (symStd == 0)
                                returnVal = 825;
                            else
                                returnVal = 849;
                        } else {
                            returnVal = 800;
                        }
                    }
                } // end if scheme == 'I'
                else// scheme = 'O' and anything else
                {
                    if (affiliation == 'F' || affiliation == 'A' || affiliation == 'D' || affiliation == 'M'
                            || affiliation == 'J' || affiliation == 'K') {
                        returnVal = 803;
                    } else if (affiliation == 'H' || affiliation == 'S')// hostile,suspect
                    {
                        returnVal = 806;// index in font file
                    } else if (affiliation == 'N' || affiliation == 'L')// neutral,exercise neutral
                    {
                        returnVal = 809;
                    } else /*
                            * if(affiliation == 'P' || affiliation == 'U' || affiliation == 'G' || affiliation
                            * == 'W')
                            */
                    {
                        returnVal = 800;// index in font file
                    }
                } // end default

            }

        } catch (Exception exc) {
            ErrorLogger.LogException("UnitFontLookup", "getFillCode", exc, Level.SEVERE);
        }

        return returnVal + 57000;
    }

    public static int getFrameCode(String SymbolID, int FillCode)
    {
        int returnVal = 0;
        char status = SymbolID.charAt(3);

        if (status == 'A')
            returnVal = FillCode + 2;
        else// P, C, D, X, F
            returnVal = FillCode + 1;

        if (returnVal == 847)
            returnVal = 852;

        if (SymbolUtilities.isSeaSurface(SymbolID)) {
            returnVal = getSeaSurfaceFrame(SymbolID, FillCode);
        }
        if (SymbolUtilities.isSubSurface(SymbolID)) {
            returnVal = getSubSurfaceFrame(SymbolID, FillCode);
        }

        return returnVal;

    }

    private static int getSeaSurfaceFill(String SymbolID)
    {
        char affiliation = 0;
        char status = 0;
        int returnVal = 0;

        try {
            affiliation = SymbolID.charAt(1);// F,H,N,U,etc...
            status = SymbolID.charAt(3);// A,P,C,D,X,F

            if (SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*S*O-----*****")) {
                return 2016;
            } else {
                if (affiliation == 'F' || affiliation == 'A' || affiliation == 'D' || affiliation == 'M'
                        || affiliation == 'J' || affiliation == 'K') {
                    return FillIndexFS;
                } else if (affiliation == 'H' || affiliation == 'S')// hostile,suspect
                {
                    return FillIndexHS;
                } else if (affiliation == 'N' || affiliation == 'L')// neutral,exercise neutral
                {
                    return FillIndexNS;
                } else if (affiliation == 'P' || affiliation == 'U' || affiliation == 'G'
                        || affiliation == 'W') {
                    return FillIndexUS;
                }
            }
        } catch (Exception exc) {
            ErrorLogger.LogException("UnitFontLookupC", "getSeaSurfaceFill", exc);
            return FillIndexUG;
        }
        return FillIndexUG;
    }

    private static int getSubSurfaceFill(String SymbolID)
    {
        char affiliation = 0;
        char status = 0;
        int returnVal = 0;

        returnVal = 831;

        try {
            affiliation = SymbolID.charAt(1);// F,H,N,U,etc...
            status = SymbolID.charAt(3);// A,P,C,D,X,F

            if (affiliation == 'F' || affiliation == 'A' || affiliation == 'D' || affiliation == 'M'
                    || affiliation == 'J' || affiliation == 'K') {
                returnVal = 831;//
            } else if (affiliation == 'H' || affiliation == 'S')// hostile,suspect
            {
                returnVal = 828;// index in font file

            } else if (affiliation == 'N' || affiliation == 'L')// neutral,exercise neutral
            {
                returnVal = 834;
            } else if (affiliation == 'P' || affiliation == 'U' || affiliation == 'G' || affiliation == 'W') {
                returnVal = 837;// index in font file
            }

            // appears in USAS so we check in both standards
            if (SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*X-----*****")) {
                if (status == 'A')
                    returnVal = returnVal + 2;
                else
                    returnVal++;
            }

            // Special check for sea mine graphics
            // 2525C///////////////////////////////////////////////////////////////
            if (RendererSettings.getInstance().getSymbologyStandard() == RendererSettings.Symbology_2525C) {
                if (SymbolID.indexOf("WM") == 4 || // Sea Mine
                        SymbolID.indexOf("WDM") == 4 || // Sea Mine Decoy
                        SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*E-----*****")
                        || SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*V-----*****")) {
                    returnVal++;

                    if (status == 'A')
                        returnVal++;

                } else if (SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*ND----*****")) {
                    returnVal = 2121;
                }
            } else// 2525Bch2////////////////////////////////////////////////////////
            {
                if (SymbolID.indexOf("WM") == 4)// Sea Mine
                {
                    if (SymbolID.indexOf("----", 6) == 6 || SymbolID.indexOf("D---", 6) == 6)
                        returnVal = 2059;//
                    else if (SymbolID.indexOf("G---", 6) == 6)
                        returnVal = 2062;
                    else if (SymbolID.indexOf("GD--", 6) == 6)
                        returnVal = 2064;
                    else if (SymbolID.indexOf("M---", 6) == 6)
                        returnVal = 2073;
                    else if (SymbolID.indexOf("MD--", 6) == 6)
                        returnVal = 2075;
                    else if (SymbolID.indexOf("F---", 6) == 6)
                        returnVal = 2084;
                    else if (SymbolID.indexOf("FD--", 6) == 6)
                        returnVal = 2086;
                    else if (SymbolID.indexOf("O---", 6) == 6 || SymbolID.indexOf("OD--", 6) == 6)
                        returnVal = 2094;

                } else if (SymbolID.indexOf("WDM") == 4)// Sea Mine Decoy
                {
                    returnVal = 2115;
                } else if (SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*ND----*****")) {
                    returnVal = 2121;
                } //
            }
        } catch (Exception exc) {
            ErrorLogger.LogException("UnitFontLookupC", "getSubSurfaceFill", exc);
            return FillIndexUU;
        }

        return returnVal;
    }

    private static int getSeaSurfaceFrame(String SymbolID, int fillCode)
    {
        int returnVal = fillCode + 1;

        if (SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*S*O-----*****"))
            returnVal = -1;
        else {
            if (SymbolID.charAt(3) == 'A' || SymbolID.charAt(3) == 'a')
                return fillCode + 2;
            else
                return fillCode + 1;
        }

        return returnVal;
    }

    private static int getSubSurfaceFrame(String SymbolID, int fillCode)
    {
        int returnVal = 0;

        returnVal = 831;

        try {
            // Special check for sea mine graphics
            // 2525C///////////////////////////////////////////////////////////////
            if (RendererSettings.getInstance().getSymbologyStandard() == RendererSettings.Symbology_2525C) {
                if (SymbolID.indexOf("WM") == 4 || // Sea Mine
                        SymbolID.indexOf("WDM") == 4 || // Sea Mine Decoy
                        SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*E-----*****")
                        || SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*V-----*****")
                        || SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*X-----*****")) {
                    returnVal = -1;
                } else if (SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*ND----*****")) {
                    returnVal = -1;
                } else {
                    if (SymbolID.charAt(3) == 'A' || SymbolID.charAt(3) == 'a')
                        return fillCode + 2;
                    else
                        return fillCode + 1;
                } //
            } else// 2525Bch2////////////////////////////////////////////////////////
            {
                if (SymbolID.indexOf("WM") == 4)// Sea Mine
                {
                    returnVal = -1;

                } else if (SymbolID.indexOf("WDM") == 4)// Sea Mine Decoy
                {
                    returnVal = -1;
                } else if (SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*ND----*****")) {
                    returnVal = -1;
                } //
                else if (SymbolUtilities.getBasicSymbolID(SymbolID).equalsIgnoreCase("S*U*X-----*****")) {
                    returnVal = -1;
                } else {
                    if (SymbolID.charAt(3) == 'A' || SymbolID.charAt(3) == 'a')
                        return fillCode + 2;
                    else
                        return fillCode + 1;
                }
            }
        } catch (Exception exc) {
            ErrorLogger.LogException("UnitFontLookupC", "getSubSurfaceFrame", exc);
            return fillCode;
        }

        return returnVal;
    }

    /**
     *
     * @param SymbolID
     * @return
     * @deprecated
     */
    public UnitFontLookupInfo getLookupInfo(String SymbolID)
    {
        return getLookupInfo(SymbolID, RendererSettings.getInstance().getSymbologyStandard());
    }

    /**
     *
     * @param SymbolID
     * @param symbologyStandard
     * @return
     */
    public UnitFontLookupInfo getLookupInfo(String SymbolID, int symbologyStandard)
    {
        UnitFontLookupInfo data = null;
        try {
            String code = SymbolUtilities.getBasicSymbolID(SymbolID);

            if (code.length() >= 10) {
                code = code.substring(0, 10) + "*****";
            }

            try {
                if (symbologyStandard == RendererSettings.Symbology_2525B) {
                    if (hashMapB.containsKey(code)) {
                        data = hashMapB.get(code);
                    }
                } else {
                    if (hashMapC.containsKey(code)) {
                        data = hashMapC.get(code);
                    }
                }
            } catch (Exception exc) {
                Log.e("UnitFontLookup", exc.getMessage(), exc);

            } catch (Throwable thrown) {
                Log.wtf("UnitFontLookup", thrown.getMessage(), thrown);
                Exception ex = new Exception(thrown.getMessage());
                ErrorLogger.LogException("UnitFontLookup", "getLookupInfo(" + String.valueOf(SymbolID) + ")",
                        ex, Level.WARNING);
            }
            return data;
        } catch (Exception exc) {
            ErrorLogger.LogException("UnitFontLookup", "getLookupInfo(" + String.valueOf(SymbolID) + ")", exc,
                    Level.WARNING);
            return null;
        }
    }

    /**
     *
     * @param charIndex - Fill Character Index
     * @return
     */
    public static float getUnitRatioHeight(int charIndex)
    {
        int characterIndex = charIndex - 57000;

        if (characterIndex == FillIndexHP || characterIndex == FillIndexHA || characterIndex == FillIndexHU
                || characterIndex == (FillIndexHU + 1) || characterIndex == (FillIndexHU + 2)
                || characterIndex == FillIndexUP || characterIndex == FillIndexUA
                || characterIndex == FillIndexUU || characterIndex == (FillIndexUU + 1)
                || characterIndex == (FillIndexUU + 2)) {
            return 1.3f;
        } else if (characterIndex == FillIndexHZ || characterIndex == FillIndexHG
                || characterIndex == FillIndexHGE || characterIndex == FillIndexHS
                || characterIndex == FillIndexHF || characterIndex == FillIndexUZ
                || characterIndex == FillIndexUG || characterIndex == FillIndexUGE
                || characterIndex == FillIndexUS || characterIndex == FillIndexUF) {
            return 1.44f;
        } else if (characterIndex == FillIndexFGE || characterIndex == FillIndexFP
                || characterIndex == FillIndexFA || characterIndex == FillIndexFU
                || characterIndex == (FillIndexFU + 1) || characterIndex == (FillIndexFU + 2)
                || characterIndex == FillIndexFZ || characterIndex == FillIndexFS
                || characterIndex == FillIndexNP || characterIndex == FillIndexNA
                || characterIndex == FillIndexNU || characterIndex == (FillIndexNU + 1)
                || characterIndex == (FillIndexNU + 2)) {
            return 1.2f;
        } else if (characterIndex == FillIndexNZ || characterIndex == FillIndexNG
                || characterIndex == FillIndexNGE || characterIndex == FillIndexNS
                || characterIndex == FillIndexNF) {
            return 1.1f;
        } else if (characterIndex == FillIndexFG || characterIndex == FillIndexFGE) {
            return 1.0f;
        } else {
            return 1.2f;
        }
    }

    /**
     *
     * @param charIndex - Fill Character Index
     * @return
     */
    public static float getUnitRatioWidth(int charIndex)
    {
        int characterIndex = charIndex - 57000;
        if (characterIndex == FillIndexUP || characterIndex == FillIndexUA || characterIndex == FillIndexUU
                || characterIndex == FillIndexUU + 1 || characterIndex == FillIndexUU + 2
                || characterIndex == FillIndexFG || characterIndex == FillIndexFF) {
            return 1.5f;
        } else if (characterIndex == FillIndexHZ || characterIndex == FillIndexHG
                || characterIndex == FillIndexHGE || characterIndex == FillIndexHS
                || characterIndex == FillIndexHF || characterIndex == FillIndexUZ
                || characterIndex == FillIndexUG || characterIndex == FillIndexUGE
                || characterIndex == FillIndexUS || characterIndex == FillIndexUF) {
            return 1.44f;
        } else if (characterIndex == FillIndexFZ || characterIndex == FillIndexFGE
                || characterIndex == FillIndexFS) {
            return 1.2f;
        } else {
            return 1.1f;
        }
    }

    /*
     * public static void main(String args[]) { int mapping =
     * UnitFontLookup.instance().getCharCodeFromSymbol("G*FPPTN---****X"); String junk = ""; }
     */
}


text:
package org.newdawn.pathexample;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import org.newdawn.slick.util.pathfinding.AStarPathFinder;
import org.newdawn.slick.util.pathfinding.Path;
import org.newdawn.slick.util.pathfinding.PathFinder;

/**
 * A simple test to show some path finding at unit
 * movement for a tutorial at http://www.cokeandcode.com
 *
 * @author Kevin Glass
 */
public class PathTest extends JFrame {
	/** The map on which the units will move */
	private GameMap map = new GameMap();
	/** The path finder we'll use to search our map */
	private PathFinder finder;
	/** The last path found for the current unit */
	private Path path;

	/** The list of tile images to render the map */
	private Image[] tiles = new Image[6];
	/** The offscreen buffer used for rendering in the wonder world of Java 2D */
	private Image buffer;

	/** The x coordinate of selected unit or -1 if none is selected */
	private int selectedx = -1;
	/** The y coordinate of selected unit or -1 if none is selected */
	private int selectedy = -1;

	/** The x coordinate of the target of the last path we searched for - used to cache and prevent constantly re-searching */
	private int lastFindX = -1;
	/** The y coordinate of the target of the last path we searched for - used to cache and prevent constantly re-searching */
	private int lastFindY = -1;

	/**
	 * Create a new test game for the path finding tutorial
	 */
	public PathTest() {
		super("Path Finding Example");

		try {
			tiles[GameMap.TREES] = ImageIO.read(getResource("res/trees.png"));
			tiles[GameMap.GRASS] = ImageIO.read(getResource("res/grass.png"));
			tiles[GameMap.WATER] = ImageIO.read(getResource("res/water.png"));
			tiles[GameMap.TANK] = ImageIO.read(getResource("res/tank.png"));
			tiles[GameMap.PLANE] = ImageIO.read(getResource("res/plane.png"));
			tiles[GameMap.BOAT] = ImageIO.read(getResource("res/boat.png"));
		} catch (IOException e) {
			System.err.println("Failed to load resources: "+e.getMessage());
			System.exit(0);
		}

		finder = new AStarPathFinder(map, 500, true);

		addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				handleMousePressed(e.getX(), e.getY());
			}
		});
		addMouseMotionListener(new MouseMotionListener() {
			public void mouseDragged(MouseEvent e) {
			}

			public void mouseMoved(MouseEvent e) {
				handleMouseMoved(e.getX(), e.getY());
			}
		});
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		setSize(600,600);
		setResizable(false);
		setVisible(true);
	}

	/**
	 * Load a resource based on a file reference
	 *
	 * @param ref The reference to the file to load
	 * @return The stream loaded from either the classpath or file system
	 * @throws IOException Indicates a failure to read the resource
	 */
	private InputStream getResource(String ref) throws IOException {
		InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(ref);
		if (in != null) {
			return in;
		}

		return new FileInputStream(ref);
	}

	/**
	 * Handle the mouse being moved. In this case we want to find a path from the
	 * selected unit to the position the mouse is at
	 *
	 * @param x The x coordinate of the mouse cursor on the screen
	 * @param y The y coordinate of the mouse cursor on the screen
	 */
	private void handleMouseMoved(int x, int y) {
		x -= 50;
		y -= 50;
		x /= 16;
		y /= 16;

		if ((x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles())) {
			return;
		}

		if (selectedx != -1) {
			if ((lastFindX != x) || (lastFindY != y)) {
				lastFindX = x;
				lastFindY = y;
				path = finder.findPath(new UnitMover(map.getUnit(selectedx, selectedy)),
									   selectedx, selectedy, x, y);
				repaint(0);
			}
		}
	}
	/**
	 * Handle the mouse being pressed. If the mouse is over a unit select it. Otherwise we move
	 * the selected unit to the new target (assuming there was a path found)
	 *
	 * @param x The x coordinate of the mouse cursor on the screen
	 * @param y The y coordinate of the mouse cursor on the screen
	 */
	private void handleMousePressed(int x, int y) {
		x -= 50;
		y -= 50;
		x /= 16;
		y /= 16;

		if ((x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles())) {
			return;
		}

		if (map.getUnit(x, y) != 0) {
			selectedx = x;
			selectedy = y;
			lastFindX = - 1;
		} else {
			if (selectedx != -1) {
				map.clearVisited();
				path = finder.findPath(new UnitMover(map.getUnit(selectedx, selectedy)),
						   			   selectedx, selectedy, x, y);

				if (path != null) {
					path = null;
					int unit = map.getUnit(selectedx, selectedy);
					map.setUnit(selectedx, selectedy, 0);
					map.setUnit(x,y,unit);
					selectedx = x;
					selectedy = y;
					lastFindX = - 1;
				}
			}
		}

		repaint(0);
	}

	/**
	 * @see java.awt.Container#paint(java.awt.Graphics)
	 */
	public void paint(Graphics graphics) {
		// create an offscreen buffer to render the map
		if (buffer == null) {
			buffer = new BufferedImage(600, 600, BufferedImage.TYPE_INT_ARGB);
		}
		Graphics g = buffer.getGraphics();

		g.clearRect(0,0,600,600);
		g.translate(50, 50);

		// cycle through the tiles in the map drawing the appropriate
		// image for the terrain and units where appropriate
		for (int x=0;x<map.getWidthInTiles();x++) {
			for (int y=0;y<map.getHeightInTiles();y++) {
				g.drawImage(tiles[map.getTerrain(x, y)],x*16,y*16,null);
				if (map.getUnit(x, y) != 0) {
					g.drawImage(tiles[map.getUnit(x, y)],x*16,y*16,null);
				} else {
					if (path != null) {
						if (path.contains(x, y)) {
							g.setColor(Color.blue);
							g.fillRect((x*16)+4, (y*16)+4,7,7);
						}
					}
				}
			}
		}

		// if a unit is selected then draw a box around it
		if (selectedx != -1) {
			g.setColor(Color.black);
			g.drawRect(selectedx*16, selectedy*16, 15, 15);
			g.drawRect((selectedx*16)-2, (selectedy*16)-2, 19, 19);
			g.setColor(Color.white);
			g.drawRect((selectedx*16)-1, (selectedy*16)-1, 17, 17);
		}

		// finally draw the buffer to the real graphics context in one
		// atomic action
		graphics.drawImage(buffer, 0, 0, null);
	}

	/**
	 * Entry point to our simple test game
	 *
	 * @param argv The arguments passed into the game
	 */
	public static void main(String[] argv) {
		PathTest test = new PathTest();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.meow.truc.bar; // obligatory

public class Hello
{
	int m_var = 0;
	public Hello()
	{
		this.m_var = 2;
	}

	class MyHelperClass
	{
		MyHelperClass() { }
		int someHelperMethod(int z, int q) { return 2; }
	}

	public Object makeObj(String name)
	{
		final String objName = "My name is " + name;

		return new Object() {
			public String toString()
			{
				return objName;
			}
		};
	}

	public static void main(String args[])
	{
		System.out.println("Hello, world");
	}
}


text:
include_recipe "apt" if ['debian', 'ubuntu'].member? node[:platform]

# Make sure we have all we need to compile ruby implementations:
include_recipe "networking_basic"
include_recipe "build-essential"
include_recipe "git"
include_recipe "libyaml"
include_recipe "libgdbm"
include_recipe "libreadline"
include_recipe "libxml"
include_recipe "libssl"
include_recipe "libncurses"
include_recipe "sqlite"
node[:rvm][:pkg_requirements].each do |r|
  package r
end

bash "install RVM" do
  user        node.travis_build_environment.user
  group       node.travis_build_environment.group
  cwd         node.travis_build_environment.home
  environment Hash['HOME' => node.travis_build_environment.home, 'rvm_user_install_flag' => '1']
  code        <<-SH
  gpg --keyserver hkp://ha.pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 || (
    curl -sSL https://rvm.io/mpapis.asc | gpg --import -
  )
  curl -s https://raw.githubusercontent.com/wayneeseguin/rvm/master/binscripts/rvm-installer -o /tmp/rvm-installer &&
  bash /tmp/rvm-installer #{node.rvm.version}
  rm   /tmp/rvm-installer
  ~/.rvm/bin/rvm version
  SH
  not_if      "test -f #{node.travis_build_environment.home}/.rvm/scripts/rvm"
end

cookbook_file "/etc/profile.d/rvm.sh" do
  owner node.travis_build_environment.user
  group node.travis_build_environment.group
  mode 0755
end

template "#{node.travis_build_environment.home}/.rvmrc" do
  owner node.travis_build_environment.user
  group node.travis_build_environment.group
  mode  0755

  source "dot_rvmrc.sh.erb"
end

bundler_settings = File.join(node.travis_build_environment.home, ".bundle", "config")
template bundler_settings do
  owner  node.travis_build_environment.user
  group  node.travis_build_environment.group

  mode   0644

  source "bundler_config.yml.erb"
  variables Hash[:suffix => node.travis_build_environment.installation_suffix]
  action :nothing
end

directory(File.join(node.travis_build_environment.home, ".bundle")) do
  owner  node.travis_build_environment.user
  group  node.travis_build_environment.group

  action :create
  notifies :create, resources(:template => bundler_settings)
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="A simple app to mass e-mail Newsletter.">
    <meta name="author" content="Jaimil Prajapati">

    <title>{{ $title }} | Newsletters</title>

    {{ HTML::style('//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css') }}

    {{ HTML::style('css/global.css') }}

                @if( Route::currentRouteName() == 'users.index' )

All Users

                @else

All Users

                @endif

                @if( Route::currentRouteName() == 'newsletters.create' )

Send Newsletter

                @else

Send Newsletter

                @endif

Newsletters

Newsletters

                Send your subscribers mass e-mail notification in a cinch!

                Current provider: {{ $provider }}

                @yield('content')

© Acme Company 2014

    {{ HTML::script('//code.jquery.com/jquery-2.1.0.min.js') }}

    {{ HTML::script('//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js') }}

    @yield('scripts')

    {{ HTML::script('js/global.js') }}


text:
@protocol BasicStringsDelegate <AJNBusInterface>

// properties
//

// methods
//
- (NSString *)concatenateString:(NSString *)str1 withString:(NSString *)str2;

// signals
//

@end

////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
//
//  AJNBasicObject Bus Object superclass
//
////////////////////////////////////////////////////////////////////////////////

@interface AJNBasicObject : AJNBusObject<BasicStringsDelegate>

// properties
//

// methods
//
- (NSString *)concatenateString:(NSString *)str1 withString:(NSString *)str2;

// signals
//

@end

////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
//
//  BasicObject Proxy
//
////////////////////////////////////////////////////////////////////////////////

@interface BasicObjectProxy : AJNProxyBusObject

// properties
//

// methods
//
- (NSString *)concatenateString:(NSString *)str1 withString:(NSString *)str2;

@end

////////////////////////////////////////////////////////////////////////////////


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="middle"
    android:gravity="center"
    android:maxLines="1"
    android:minHeight="@dimen/title_bar_icon_size"
    android:paddingLeft="0dp"
    android:textColor="@color/fg_title_bar_normal"
    android:textSize="18sp"
    tools:background="@color/colorPrimary"
    tools:maxWidth="60dp"
    tools:text="□□□□□□□□□□">

</TextView>


text:
module CamaleonCms
  module Widget
    class Sidebar < CamaleonCms::TermTaxonomy
      default_scope { where(taxonomy: :sidebar) }

      has_many :metas, ->{ where(object_class: 'Widget::Sidebar')}, class_name: 'CamaleonCms::Meta', foreign_key: :objectid, dependent: :destroy
      has_many :assigned, foreign_key: :post_parent, dependent: :destroy
      belongs_to :site, class_name: 'CamaleonCms::Site', foreign_key: :parent_id

      #scopes
      scope :default_sidebar, -> { where(slug: 'default-sidebar') }
      scope :all_sidebar, -> { where('slug != \'default-sidebar\'') }

      # assign the widget into this sidebar
      # widget: string(slug)/object
      # data: {title, content}
      def add_widget(widget, data = {})
        widget = site.widgets.where(slug: widget).first if widget.is_a?(String)
        data[:widget_id] = widget.id
        self.assigned.create(data)
      end
    end
  end
end


text:
package limelight.styles.attributes;

import limelight.styles.StyleAttribute;

public class MaxWidthAttribute extends StyleAttribute
{
  public MaxWidthAttribute()
  {
    super("Max Width", "noneable simple dimension", "none");
  }
}


text:
\documentclass{article}
\usepackage[fancyhdr,pdf]{latex2man}

\input{common.tex}

\begin{document}

\begin{Name}{3}{unw\_get\_proc\_info}{David Mosberger-Tang}{Programming Library}{unw\_get\_proc\_info}unw\_get\_proc\_info -- get info on current procedure
\end{Name}

\section{Synopsis}

\File{\#include $<$libunwind.h$>$}\\

\Type{int} \Func{unw\_get\_proc\_info}(\Type{unw\_cursor\_t~*}\Var{cp}, \Type{unw\_proc\_info\_t~*}\Var{pip});\\

\section{Description}

The \Func{unw\_get\_proc\_info}() routine returns auxiliary
information about the procedure that created the stack frame
identified by argument \Var{cp}.  The \Var{pip} argument is a pointer
to a structure of type \Type{unw\_proc\_info\_t} which is used to
return the information.  The \Type{unw\_proc\_info\_t} has the
following members:
\begin{description}
\item[\Type{unw\_word\_t} \Var{start\_ip}] The address of the first
  instruction of the procedure.  If this address cannot be determined
  (e.g., due to lack of unwind information), the \Var{start\_ip}
  member is cleared to 0.  \\
\item[\Type{unw\_word\_t} \Var{end\_ip}] The address of the first
  instruction \emph{beyond} the end of the procedure.  If this address
  cannot be determined (e.g., due to lack of unwind information),
  the \Var{end\_ip} member is cleared to 0.  \\
\item[\Type{unw\_word\_t} \Var{lsda}] The address of the
  language-specific data-area (LSDA).  This area normally contains
  language-specific information needed during exception handling.  If
  the procedure has no such area, this member is cleared to 0.  \\
\item[\Type{unw\_word\_t} \Var{handler}] The address of the exception
  handler routine.  This is sometimes called the \emph{personality}
  routine.  If the procedure does not define
  a personality routine, the \Var{handler} member is cleared to 0.  \\
\item[\Type{unw\_word\_t} \Var{gp}] The global-pointer of the
  procedure.  On platforms that do not use a global pointer, this
  member may contain an undefined value.  On all other platforms, it
  must be set either to the correct global-pointer value of the
  procedure or to 0 if the proper global-pointer cannot be
  obtained for some reason.  \\
\item[\Type{unw\_word\_t} \Var{flags}] A set of flags.  There are
  currently no target-independent flags.  For the IA-64 target, the
  flag \Const{UNW\_PI\_FLAG\_IA64\_RBS\_SWITCH} is set if the
  procedure may switch the register-backing store.\\
\item[\Type{int} \Var{format}] The format of the unwind-info for this
  procedure.  If the unwind-info consists of dynamic procedure info,
  \Var{format} is equal to \Const{UNW\_INFO\_FORMAT\_DYNAMIC}.  If the
  unwind-info consists of a (target-specific) unwind table, it is
  equal to \Const{UNW\_INFO\_FORMAT\_TABLE}.  All other values are
  reserved for future use by \Prog{libunwind}.  This member exists
  for use by the \Func{find\_proc\_info}() call-back (see
  \Func{unw\_create\_addr\_space}(3)).  The
  \Func{unw\_get\_proc\_info}() routine
  may return an undefined value in this member. \\
\item[\Type{int} \Var{unwind\_info\_size}] The size of the unwind-info
  in bytes.  This member exists for use by the
  \Func{find\_proc\_info}() call-back (see
  \Func{unw\_create\_addr\_space}(3)).  The
  \Func{unw\_get\_proc\_info}() routine
  may return an undefined value in this member.\\
\item[\Type{void~*}\Var{unwind\_info}] The pointer to the unwind-info.
  If no unwind info is available, this member must be set to
  \Const{NULL}.  This member exists for use by the
  \Func{find\_proc\_info}() call-back (see
  \Func{unw\_create\_addr\_space}(3)).  The
  \Func{unw\_get\_proc\_info}() routine
  may return an undefined value in this member.\\
\end{description}
Note that for the purposes of \Prog{libunwind}, the code of a
procedure is assumed to occupy a single, contiguous range of
addresses.  For this reason, it is always possible to describe the
extent of a procedure with the \Var{start\_ip} and \Var{end\_ip}
members.  If a single function/routine is split into multiple,
discontiguous pieces, \Prog{libunwind} will treat each piece as a
separate procedure.

\section{Return Value}

On successful completion, \Func{unw\_get\_proc\_info}() returns 0.
Otherwise the negative value of one of the error-codes below is
returned.

\section{Thread and Signal Safety}

\Func{unw\_get\_proc\_info}() is thread-safe.  If cursor \Var{cp} is
in the local address-space, this routine is also safe to use from a
signal handler.

\section{Errors}

\begin{Description}
\item[\Const{UNW\_EUNSPEC}] An unspecified error occurred.
\item[\Const{UNW\_ENOINFO}] \Prog{Libunwind} was unable to locate
  unwind-info for the procedure.
\item[\Const{UNW\_EBADVERSION}] The unwind-info for the procedure has
  version or format that is not understood by \Prog{libunwind}.
\end{Description}
In addition, \Func{unw\_get\_proc\_info}() may return any error
returned by the \Func{access\_mem}() call-back (see
\Func{unw\_create\_addr\_space}(3)).

\section{See Also}

\SeeAlso{libunwind(3)},
\SeeAlso{unw\_create\_addr\_space(3)},
\SeeAlso{unw\_get\_proc\_name(3)}

\section{Author}

\noindent
David Mosberger-Tang\\
Email: \Email{dmosberger@gmail.com}\\
WWW: \URL{http://www.nongnu.org/libunwind/}.
\LatexManEnd

\end{document}


text:
package io.imgn.module;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

public class ModuleTest {
  @Test
  void testEquals() {
    Metadata metadata = Metadata.builder(Name.valueOf("abc"), Version.of(1, 2, 3)).build();
    Module mod1 = Module.builder(metadata).build();
    Module mod2 = Module.builder(metadata).build();
    assertThat(mod1).isEqualTo(mod2);
    assertThat(mod2).isEqualTo(mod1);
  }

  @Test
  void testHashcode() {
    Name abc = Name.valueOf("abc");
    Name xyz = Name.valueOf("xyz");

    Version v1_2_3 = Version.of(1, 2, 3);
    Version v2_3_4 = Version.of(2, 3, 4);

    Module mod1 = Module.builder(Metadata.builder(abc, v1_2_3).build()).build();
    Module mod2 = Module.builder(Metadata.builder(abc, v1_2_3).build()).build();

    assertThat(mod1.hashCode()).isEqualTo(mod2.hashCode());
  }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PredicateExtensions.cs" company="CODE Insiders LTD">
//
// Copyright 2013-2015 CODE Insiders LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CodeInsiders.SharpQL
{
    using System;

    using CodeInsiders.SharpQL.Helpers.Internal;

    public static class PredicateExtensions
    {
        public static Predicate AndIf(this Predicate predicate, Func<bool> condition, Predicate rightPart) {
            if (condition()) {
                return predicate & rightPart;
            }

            return predicate;
        }

        public static Predicate AndIfNotNull<T>(this Predicate predicate, T value, Func<T, Predicate> handler) {
            if (value != null) {
                return predicate & handler(value);
            }

            return predicate;
        }

        public static Predicate AndIfNotNullOrWhitespace<T>(
            this Predicate predicate,
            T value,
            Func<T, Predicate> handler) {
            if (value != null) {
                if (!StringHelper.IsNullOrWhiteSpace(value.ToString())) {
                    return predicate & handler(value);
                }
            }

            return predicate;
        }

        public static Predicate OrIfNotNull<T>(this Predicate predicate, T value, Func<T, Predicate> handler) {
            if (value != null) {
                return predicate & handler(value);
            }

            return predicate;
        }

        public static Predicate OrIfNotNullOrWhitespace<T>(
            this Predicate predicate,
            T value,
            Func<T, Predicate> handler) {
            if (value != null) {
                if (!StringHelper.IsNullOrWhiteSpace(value.ToString())) {
                    return predicate & handler(value);
                }
            }

            return predicate;
        }
    }
}


text:
<?php
/**
 * JPMEna Gallery links manipulation
 * Module to manipulate Gallery Links
 */

// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;

if ( !class_exists('wprsm_links', false) ) {
	class wprsm_links {
		//the array of wp links found in the POST!!!
		private $wp_links_array;
		private $wprsmimg_link_count;
		private $type;

		public function __construct($type) {
			$this->wp_links_array = array();
			$this->wprsmimg_link_count = 0;
			$this->type = $type; //the gallery.js type to apply
		}

		public function remove_wp_link($found_image_link){
			if (sizeof($found_image_link) > 11){
				$img_url = $found_image_link[3];
				$thumb_url = $found_image_link[9];
				$format = "<a%shref='%s' %s><img%ssrc='%s' data-imagelightbox='%s' %s /></a>";
				$new_img_wp_code = sprintf($format,$found_image_link[1],$img_url,$found_image_link[5],$found_image_link[7],$thumb_url,$this->type,$found_image_link[11]);
				$this->wp_links_array[] = array('img_url'=>$img_url,
						'thumb_url'=>$thumb_url,
						'new_img_wp_code'=>$new_img_wp_code);
				return '__rsmwp_link_' . $this->wprsmimg_link_count++ . '__';
			}else{
				return $found_image_link[0]; //we do nothing in that case
			}

		}

		public function restore_wp_link($replacment_text_matches){
			$wp_rsm_image = $this->wp_links_array[$replacment_text_matches[1]];
			$new_link = array_key_exists('new_img_wp_code', $wp_rsm_image)? $wp_rsm_image['new_img_wp_code'] : $replacment_text_matches[0];
			return $new_link;
		}
	}
}


text:
package org.springframework.boot.origin;

import java.util.HashMap;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;

/**
 * Tests for {@link PropertySourceOrigin}.
 *
 * @author Phillip Webb
 */
public class PropertySourceOriginTests {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Test
	public void createWhenPropertySourceIsNullShouldThrowException() {
		this.thrown.expect(IllegalArgumentException.class);
		this.thrown.expectMessage("PropertySource must not be null");
		new PropertySourceOrigin(null, "name");
	}

	@Test
	public void createWhenPropertyNameIsNullShouldThrowException() {
		this.thrown.expect(IllegalArgumentException.class);
		this.thrown.expectMessage("PropertyName must not be empty");
		new PropertySourceOrigin(mock(PropertySource.class), null);
	}

	@Test
	public void createWhenPropertyNameIsEmptyShouldThrowException() {
		this.thrown.expect(IllegalArgumentException.class);
		this.thrown.expectMessage("PropertyName must not be empty");
		new PropertySourceOrigin(mock(PropertySource.class), "");
	}

	@Test
	public void getPropertySourceShouldReturnPropertySource() {
		MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>());
		PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo");
		assertThat(origin.getPropertySource()).isEqualTo(propertySource);
	}

	@Test
	public void getPropertyNameShouldReturnPropertyName() {
		MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>());
		PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo");
		assertThat(origin.getPropertyName()).isEqualTo("foo");
	}

	@Test
	public void toStringShouldShowDetails() {
		MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>());
		PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo");
		assertThat(origin.toString()).isEqualTo("\"foo\" from property source \"test\"");
	}

	@Test
	@SuppressWarnings("unchecked")
	public void getWhenPropertySourceSupportsOriginLookupShouldReturnOrigin() {
		Origin origin = mock(Origin.class);
		PropertySource<?> propertySource = mock(PropertySource.class,
				withSettings().extraInterfaces(OriginLookup.class));
		OriginLookup<String> originCapablePropertySource = (OriginLookup<String>) propertySource;
		given(originCapablePropertySource.getOrigin("foo")).willReturn(origin);
		assertThat(PropertySourceOrigin.get(propertySource, "foo")).isSameAs(origin);
	}

	@Test
	public void getWhenPropertySourceSupportsOriginLookupButNoOriginShouldWrap() {
		PropertySource<?> propertySource = mock(PropertySource.class,
				withSettings().extraInterfaces(OriginLookup.class));
		assertThat(PropertySourceOrigin.get(propertySource, "foo"))
				.isInstanceOf(PropertySourceOrigin.class);
	}

	@Test
	public void getWhenPropertySourceIsNotOriginAwareShouldWrap() {
		MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>());
		PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo");
		assertThat(origin.getPropertySource()).isEqualTo(propertySource);
		assertThat(origin.getPropertyName()).isEqualTo("foo");
	}

}


text:
from django.utils.translation import ugettext_lazy as _
from payment.modules.base import BasePaymentProcessor, ProcessorResult

class PaymentProcessor(BasePaymentProcessor):
    """
    Autosuccess Payment Module
    """
    def __init__(self, settings):
        super(PaymentProcessor, self).__init__('autosuccess', settings)

    def capture_payment(self, testing=False, order=None, amount=None):
        if not order:
            order = self.order

        if amount is None:
            amount = order.balance

        payment = self.record_payment(order=order, amount=amount,
            transaction_id="AUTO", reason_code='0')

        return ProcessorResult(self.key, True, _('Success'), payment)


text:
layout: post
title: Week Two
---

1. What did I do last week?

This week we spent the first two classes discussing solution strategies for the collatz project and introducing the class to the various steps required to set up, test, and submit our solutions. One of the more  heavily focused on areas was caching where Professor Downing discussed eager, lazy, and meta caching in the context of the 3n+1 problem. For the third class we discussed the difference between "L" and "R" values in C++ using the ++ operator as an example, as well as the usage of exceptions in the control flow of our programs.
This was also the first week in which readings were assigned so I read through the approximately 40 pages that comprised chapters 1 and 2 of our object oriented programming book as well as a couple lengthy online articles about collegiate success and happiness. The most surprising part of the readings happened to be the target audience of our textbook, as the book seems to heavily focus at convincing it's readers that  Object Oriented Programming is a worthwhile paradigm while almost all modern programming students were introduced to programming through object oriented languages.

2. What was in my way?

Since I finished the solution rather quickly, I have few tasks that I can create issues for. I am having trouble of thinking up enough issues to solve to satisfy the 15 issue requirement for the project.

3. What will I do next week?

I will finish the unit testing and acceptance testing side of the project as well as submitting my final solution.

Pick of the week :

Since this blog is written in markdown, I've found this online markdown editor to be a very helpful resource [stackedit.io](https://stackedit.io/editor)


text:
using Aragas.Core.Data;
using Aragas.Core.Extensions;
using Aragas.Core.Interfaces;
using Aragas.Core.Packets;

using MineLib.Core.Data;
using MineLib.Core.Data.Anvil;
using MineLib.Core.Data.Structs;
using MineLib.Core.Extensions;

using System;
using Aragas.Core.IO;
using ProtocolModern.Extensions;

namespace MineLib.PacketBuilder.Client.Play
{
    public class SpawnObjectPacket : ProtobufPacket
    {
		public VarInt EntityID;
		public SByte Type;
		public Int32 X;
		public Int32 Y;
		public Int32 Z;
		public Byte Pitch;
		public Byte Yaw;
		public NotSupportedType Data;

        public override VarInt ID { get { return 14; } }

        public override ProtobufPacket ReadPacket(PacketDataReader reader)
        {
			EntityID = reader.Read(EntityID);
			Type = reader.Read(Type);
			X = reader.Read(X);
			Y = reader.Read(Y);
			Z = reader.Read(Z);
			Pitch = reader.Read(Pitch);
			Yaw = reader.Read(Yaw);
			Data = reader.Read(Data);

            return this;
        }

        public override ProtobufPacket WritePacket(PacketStream stream)
        {
			stream.Write(EntityID);
			stream.Write(Type);
			stream.Write(X);
			stream.Write(Y);
			stream.Write(Z);
			stream.Write(Pitch);
			stream.Write(Yaw);
			stream.Write(Data);

            return this;
        }

    }
}


text:
from gusto import *
from firedrake import (IcosahedralSphereMesh, SpatialCoordinate,
                       as_vector, FunctionSpace)
from math import pi
import sys

day = 24.*60.*60.
if '--running-tests' in sys.argv:
    ref_dt = {3: 3000.}
    tmax = 3000.
else:
    # setup resolution and timestepping parameters for convergence test
    ref_dt = {3: 4000., 4: 2000., 5: 1000., 6: 500.}
    tmax = 5*day

# setup shallow water parameters
R = 6371220.
H = 5960.

# setup input that doesn't change with ref level or dt
fieldlist = ['u', 'D']
parameters = ShallowWaterParameters(H=H)

for ref_level, dt in ref_dt.items():

    dirname = "sw_W2_ref%s_dt%s" % (ref_level, dt)
    mesh = IcosahedralSphereMesh(radius=R,
                                 refinement_level=ref_level, degree=3)
    x = SpatialCoordinate(mesh)
    global_normal = x
    mesh.init_cell_orientations(x)

    timestepping = TimesteppingParameters(dt=dt)

    output = OutputParameters(dirname=dirname,
                              dumplist_latlon=['D', 'D_error'],
                              steady_state_error_fields=['D', 'u'],
                              log_level='INFO')

    diagnostic_fields = [RelativeVorticity(), PotentialVorticity(),
                         ShallowWaterKineticEnergy(),
                         ShallowWaterPotentialEnergy(),
                         ShallowWaterPotentialEnstrophy()]

    state = State(mesh, horizontal_degree=1,
                  family="BDM",
                  timestepping=timestepping,
                  output=output,
                  parameters=parameters,
                  diagnostic_fields=diagnostic_fields,
                  fieldlist=fieldlist)

    # interpolate initial conditions
    u0 = state.fields("u")
    D0 = state.fields("D")
    x = SpatialCoordinate(mesh)
    u_max = 2*pi*R/(12*day)  # Maximum amplitude of the zonal wind (m/s)
    uexpr = as_vector([-u_max*x[1]/R, u_max*x[0]/R, 0.0])
    Omega = parameters.Omega
    g = parameters.g
    Dexpr = H - ((R * Omega * u_max + u_max*u_max/2.0)*(x[2]*x[2]/(R*R)))/g
    # Coriolis expression
    fexpr = 2*Omega*x[2]/R
    V = FunctionSpace(mesh, "CG", 1)
    f = state.fields("coriolis", V)
    f.interpolate(fexpr)  # Coriolis frequency (1/s)

    u0.project(uexpr)
    D0.interpolate(Dexpr)
    state.initialise([('u', u0),
                      ('D', D0)])

    ueqn = VectorInvariant(state, u0.function_space())
    Deqn = AdvectionEquation(state, D0.function_space(), equation_form="continuity")
    advected_fields = []
    advected_fields.append(("u", ThetaMethod(state, u0, ueqn)))
    advected_fields.append(("D", SSPRK3(state, D0, Deqn, subcycles=2)))

    linear_solver = ShallowWaterSolver(state)

    # Set up forcing
    sw_forcing = ShallowWaterForcing(state, euler_poincare=False)

    # build time stepper
    stepper = CrankNicolson(state, advected_fields, linear_solver,
                            sw_forcing)

    stepper.run(t=0, tmax=tmax)


text:
using namespace eosio;

proxy::proxy( eosio::name self, eosio::name first_receiver, eosio::datastream<const char*> ds )
:contract( self, first_receiver, ds )
,_config( get_self(), get_self().value )
{}

void proxy::setowner( name owner, uint32_t delay ) {
   require_auth( get_self() );
   auto cfg = _config.get_or_default();
   cfg.owner = owner;
   cfg.delay = delay;
   print( "Setting owner to ", owner, " with delay ", delay, "\n" );
   _config.set( cfg, get_self() );
}

void proxy::on_transfer( name from, name to, asset quantity, const std::string& memo ) {
   print("on_transfer called on ", get_self(), " contract with from = ", from, " and to = ", to, "\n" );
   check( _config.exists(), "Attempting to use unconfigured proxy" );
   auto cfg = _config.get();

   auto self = get_self();
   if( from == self ) {
      check( to == cfg.owner, "proxy may only pay its owner" );
   } else {
      check( to == self, "proxy is not involved in this transfer" );

      auto id =  cfg.next_id++;
      _config.set( cfg, self );

      transaction out;
      eosio::token::transfer_action a( "eosio.token"_n, {self, "active"_n} );
      out.actions.emplace_back( a.to_action( self, cfg.owner, quantity, memo ) );
      out.delay_sec = cfg.delay;
      out.send( id, self );
   }
}

void proxy::on_error( uint128_t sender_id, eosio::ignore<std::vector<char>> ) {
   print( "on_error called on ", get_self(), " contract with sender_id = ", sender_id, "\n" );
   check( _config.exists(), "Attempting use of unconfigured proxy" );

   auto cfg = _config.get();

   auto id = cfg.next_id;
   ++cfg.next_id;
   _config.set( cfg, same_payer );

   print("Resending Transaction: ", sender_id, " as ", id, "\n");

   unsigned_int packed_trx_size;
   get_datastream() >> packed_trx_size;
   transaction trx;
   get_datastream() >> trx;
   trx.transaction_extensions.clear();

   trx.delay_sec = cfg.delay;
   trx.send( id, get_self() );
}


text:
import { prepend, first } from '../../../util'

const moveVolumeNames = (references: Element[]): Element[] => {
  references.forEach((reference: Element): void => {
    const volume = first(reference, ':--PublicationVolume:--isPartOf')
    if (volume !== null) {
      const volumeName = first(volume, ':--isPartOf')
      if (volumeName !== null) {
        prepend(volume, volumeName)
      }
    }
  })
  return references
}

const movePeriodical = (references: Element[]): Element[] => {
  references.forEach((reference: Element): void => {
    const volume = first(reference, ':--Periodical:--isPartOf')
    if (volume !== null) {
      const periodicalToMove = first(volume, ':--isPartOf')
      if (periodicalToMove !== null) {
        prepend(volume, periodicalToMove)
      }
    }
  })
  return references
}

export const format = (references: Element[]): void => {
  moveVolumeNames(movePeriodical(references))
}


text:
@import url(https://fonts.googleapis.com/css?family=Ubuntu);

body, button, a, p, span, div, h1, h2, h3, h4, h5, h6, input, select, option {
    font-family: 'Ubuntu', sans-serif;
}

body {
    padding-top: 70px;
    /* Required padding for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
}

/*video, canvas {
    position: absolute;
}*/

.tracking {
    position: absolute;
}

.facePlaceholder {
    min-width: 320px;
    min-height: 240px;
}

/*style for color picker*/
.image-pick-color {
    display: inline-block;
    max-width: 100%;
    height: auto;
    padding: 4px;
    line-height: 1.42857143;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    -webkit-transition: all .2s ease-in-out;
    -o-transition: all .2s ease-in-out;
    transition: all .2s ease-in-out;
}

.average-color {
    text-align: center;
    /*background-color: #67b168;*/
    border: 2px solid #ddd;
}

.image-panel-color {
    cursor: crosshair;
    display: inline-block;
    max-width: 100%;
    height: auto;
    line-height: 1.42857143;
    -webkit-transition: all .2s ease-in-out;
    -o-transition: all .2s ease-in-out;
    transition: all .2s ease-in-out;
}

.camera-placeholder {
    margin-bottom: 15px;
}

.confirm-colors-button {
    margin-top: 15px;
}

.image-color-select-footer {
    padding: 10px 15px;
    background-color: #f5f5f5;
    border-top: 1px solid #ddd;
    border-bottom-right-radius: 3px;
    border-bottom-left-radius: 3px;
    text-align: -moz-center;
}

.color-name-user-image {
    margin: 25px;
}

.color-name-wrapper {
    margin-top: 45px;
}

.color-name-playlist-user-data {
    margin-top: 25px;
}

.color-preview {
    width: 30px;
    height: 30px;
    border: 2px solid #ddd;
    vertical-align: middle;
    -webkit-border-radius: 100px;
    -moz-border-radius: 100px;
    border-radius: 100px;
}

#progressLine {
    margin: 20px;
    /*width: 400px;*/
    height: 15px;
}

.color-name-facePlaceholder {
    min-width: 192px;
    min-height: 144px;
}


text:
namespace v8 {
namespace internal {

TEST(CodeObjectRegistry, RegisterAlreadyExistingObjectsAndContains) {
  CodeObjectRegistry registry;
  const int elements = 10;
  const int offset = 100;
  for (int i = 0; i < elements; i++) {
    registry.RegisterAlreadyExistingCodeObject(i * offset);
  }

  for (int i = 0; i < elements; i++) {
    CHECK(registry.Contains(i * offset));
  }
}

TEST(CodeObjectRegistry, RegisterNewlyAllocatedObjectsAndContains) {
  CodeObjectRegistry registry;
  const int elements = 10;
  const int offset = 100;
  for (int i = 0; i < elements; i++) {
    registry.RegisterNewlyAllocatedCodeObject(i * offset);
  }

  for (int i = 0; i < elements; i++) {
    CHECK(registry.Contains(i * offset));
  }
}

TEST(CodeObjectRegistry, FindAlreadyExistingObjects) {
  CodeObjectRegistry registry;
  const int elements = 10;
  const int offset = 100;
  const int inner = 2;
  for (int i = 1; i <= elements; i++) {
    registry.RegisterAlreadyExistingCodeObject(i * offset);
  }

  for (int i = 1; i <= elements; i++) {
    for (int j = 0; j < inner; j++) {
      CHECK_EQ(registry.GetCodeObjectStartFromInnerAddress(i * offset + j),
               i * offset);
    }
  }
}

TEST(CodeObjectRegistry, FindNewlyAllocatedObjects) {
  CodeObjectRegistry registry;
  const int elements = 10;
  const int offset = 100;
  const int inner = 2;
  for (int i = 1; i <= elements; i++) {
    registry.RegisterNewlyAllocatedCodeObject(i * offset);
  }

  for (int i = 1; i <= elements; i++) {
    for (int j = 0; j < inner; j++) {
      CHECK_EQ(registry.GetCodeObjectStartFromInnerAddress(i * offset + j),
               i * offset);
    }
  }
}

TEST(CodeObjectRegistry, FindAlternatingObjects) {
  CodeObjectRegistry registry;
  const int elements = 10;
  const int offset = 100;
  const int inner = 2;
  for (int i = 1; i <= elements; i++) {
    if (i % 2 == 0) {
      registry.RegisterAlreadyExistingCodeObject(i * offset);
    } else {
      registry.RegisterNewlyAllocatedCodeObject(i * offset);
    }
  }

  for (int i = 1; i <= elements; i++) {
    for (int j = 0; j < inner; j++) {
      CHECK_EQ(registry.GetCodeObjectStartFromInnerAddress(i * offset + j),
               i * offset);
    }
  }
}
}  // namespace internal
}  // namespace v8


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">CountDownTimer</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>

</resources>


text:
package org.broadinstitute.clio.server.service

import java.net.URI

import com.sksamuel.elastic4s.searches.queries.{BoolQuery, QueryStringQuery}
import org.broadinstitute.clio.server.dataaccess.elasticsearch.ElasticsearchIndex
import org.broadinstitute.clio.server.dataaccess.{PersistenceDAO, SearchDAO}
import org.broadinstitute.clio.transfer.model.BamIndex
import org.broadinstitute.clio.transfer.model.bam.{
  BamExtensions,
  BamKey,
  BamMetadata,
  BamQueryInput
}
import org.broadinstitute.clio.util.model.{DataType, DocumentStatus, Location}

class BamServiceSpec extends IndexServiceSpec[BamIndex.type]("BamService") {

  val elasticsearchIndex: ElasticsearchIndex[BamIndex.type] =
    ElasticsearchIndex.Bam

  val dummyKey = BamKey(Location.GCP, "project1", DataType.RNA, "sample1", 1)

  val dummyInput = BamQueryInput(project = Option("testProject"))

  val dummyKeyQuery = BoolQuery(
    must = Seq(
      QueryStringQuery(
        query = "\"" + dummyKey.location.toString + "\"",
        defaultField = Some("location")
      ),
      QueryStringQuery(
        query = "\"" + dummyKey.project + "\"",
        defaultField = Some("project.exact")
      ),
      QueryStringQuery(
        query = "\"" + dummyKey.sampleAlias + "\"",
        defaultField = Some("sample_alias.exact")
      ),
      QueryStringQuery(
        query = "\"" + dummyKey.version.toString + "\"",
        defaultField = Some("version")
      )
    )
  )

  def getDummyMetadata(
    documentStatus: Option[DocumentStatus]
  ): BamMetadata = {
    BamMetadata(
      bamPath = Option(
        URI.create(s"gs://path/bamPath${BamExtensions.BamExtension}")
      ),
      notes = Option("notable update"),
      documentStatus = documentStatus,
      workspaceName = Option("the workspace")
    )
  }

  def copyDummyMetadataChangeField(metadata: BamMetadata): BamMetadata = {
    metadata.copy(workspaceName = Some(randomString))
  }

  def copyDummyMetadataSetNullField(metadata: BamMetadata): BamMetadata =
    metadata.copy(bamSize = Some(1L))

  def getService(
    persistenceDAO: PersistenceDAO,
    searchDAO: SearchDAO
  ): BamService = {
    new BamService(persistenceDAO, searchDAO)
  }

}


text:
var koa = require('koa');
var serve = require('koa-static');
global.S = require('springbokjs-utils');

var argv = require('minimist')(process.argv.slice(2), {
    alias: {
        'production': 'prod'
    }
});

var app = koa();

if (!argv.production) {
    console.log('Dev mode');
    app.use(require('koa-livereload')({
        port: argv.livereloadPort
    }));
    /*['src', 'node_modules'].forEach((folder) => {
        app.use('/' + folder, serve('../../' + folder));
    });*/
} else {
    console.log('Production mode');
}

// logger

app.use(function *(next){
  yield next;
  console.log('%s %s - %sms', this.method, this.url, this._requestTook);
});

// x-response-time

app.use(function *(next){
  var start = new Date();
  this._requestStartedAt = start;
  yield next;
  var ms = new Date() - start;
  this._requestTook = ms;
  this.set('X-Response-Time', ms + 'ms');
});

// response

app.use(function *(){
  this.body = 'Hello World';
});

//app.get('/', (req, res) => res.render('index', { URL: req.path }));

app.use(serve('../../public'));

var port = argv.port || 3000;
app.listen(port, console.log.bind(null, 'Listening on port ' + port));


text:
<?php
namespace Sw\UtilityBundle\Annotation;

/**
 * Searchable annotation
 * TODO: <INSERT DOCUMENTATION HERE>
 *
 * @Annotation
 *
 * @package Sw\UtilityBundle
 * @author  Guillaume Petit <guillaume.petit@sword-group.com>
 */
class Searchable
{
}


text:
package ru.extas.web;

import com.vaadin.data.util.converter.Converter;
import com.vaadin.data.util.converter.DefaultConverterFactory;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import ru.extas.model.contacts.*;
import ru.extas.model.contacts.Person.Sex;
import ru.extas.model.insurance.A7Form;
import ru.extas.model.insurance.Insurance;
import ru.extas.model.insurance.Policy;
import ru.extas.model.lead.Lead;
import ru.extas.model.product.ProdCredit;
import ru.extas.model.product.ProductExpenditure;
import ru.extas.model.product.ProductInstance;
import ru.extas.model.sale.Sale;
import ru.extas.model.security.*;
import ru.extas.web.commons.converters.*;
import ru.extas.web.contacts.employee.StringToTypeOfEmployment;
import ru.extas.web.contacts.person.*;
import ru.extas.web.insurance.StringToA7FormConverter;
import ru.extas.web.insurance.StringToA7StatusConverter;
import ru.extas.web.insurance.StringToPeriodOfCoverConverter;
import ru.extas.web.insurance.StringToPolicyConverter;
import ru.extas.web.lead.StringToLeadResult;
import ru.extas.web.lead.StringToLeadStatus;
import ru.extas.web.product.String2CreditProgramType;
import ru.extas.web.product.String2ProdInSaleState;
import ru.extas.web.product.String2ProductExpenditureType;
import ru.extas.web.sale.StringToSaleCancelReason;
import ru.extas.web.users.*;

import java.math.BigDecimal;
import java.util.Date;

import static ru.extas.server.ServiceLocator.lookup;

/**
 * Определяет кнверторы по умолчанию
 *
 * @author Valery Orlov
 * @version $Id: $Id
 * @since 0.3
 */
public class ExtaConverterFactory extends DefaultConverterFactory {
	private static final long serialVersionUID = -1489942684787774107L;

	/** {@inheritDoc} */
	@SuppressWarnings("unchecked")
	@Override
	protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> findConverter(final Class<PRESENTATION> presentationType, final Class<MODEL> modelType) {

		// Конверторы дат
		if (presentationType == Date.class && modelType == DateTime.class)
			return (Converter<PRESENTATION, MODEL>) lookup(DateToJodaDTConverter.class);
		if (presentationType == Date.class && modelType == LocalDate.class)
			return (Converter<PRESENTATION, MODEL>) lookup(DateToJodaLDConverter.class);
		if (presentationType == String.class && modelType == DateTime.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToJodaDTConverter.class);
		if (presentationType == String.class && modelType == LocalDate.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToJodaLDConverter.class);
		if (presentationType == String.class && modelType == Date.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToDateTimeConverter.class);

		// Конвертер денег
		if (presentationType == String.class && modelType == BigDecimal.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToMoneyConverter.class);

		// конвертер ролей пользователя
		if (presentationType == String.class && modelType == UserRole.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToUserRoleConverter.class);

		// конвертер ролей доступа к объектам
		if (presentationType == String.class && modelType == AccessRole.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToAccessRoleConverter.class);

		// Конвертер половой принадлежности
		if (presentationType == String.class && modelType == Sex.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToPersonSex.class);

		// Простой конвертор флага
		if (presentationType == String.class && modelType == Boolean.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToBooleanConverter.class);

		// Конвертер полиса БСО
		if (presentationType == String.class && modelType == Policy.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToPolicyConverter.class);

		// Конвертер строк в длинное целое
		if (presentationType == String.class && modelType == Long.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToLongConverter.class);

		// Конвертируем Квитанцию А-7 в строку (номер квитанции)
		if (presentationType == String.class && modelType == A7Form.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToA7FormConverter.class);

		// Конвертер статусов А-7
		if (presentationType == String.class && modelType == A7Form.Status.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToA7StatusConverter.class);

		// Конвертор результата завершения Продажи
		if (presentationType == String.class && modelType == Sale.CancelReason.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToSaleCancelReason.class);

		// Конвертор статуса лида
		if (presentationType == String.class && modelType == Lead.Status.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToLeadStatus.class);

		// Конвертор результата завершения лида
		if (presentationType == String.class && modelType == Lead.Result.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToLeadResult.class);

		// Конвертер периода страхования
		if (presentationType == String.class && modelType == Insurance.PeriodOfCover.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToPeriodOfCoverConverter.class);

		// Конвертер типов кредитных программ
		if (presentationType == String.class && modelType == ProdCredit.ProgramType.class)
			return (Converter<PRESENTATION, MODEL>) lookup(String2CreditProgramType.class);

		// Конвертер разделов системы
		if (presentationType == String.class && modelType == ExtaDomain.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToExtaDomainConverter.class);

		// Конвертер разрешенных действий в рамках правила доступа
		if (presentationType == String.class && modelType == SecureAction.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToSecureActionConverter.class);

		// Конвертер целевых объектов правила доступа
		if (presentationType == String.class && modelType == SecureTarget.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToSecureTargetConverter.class);

		// Конвертер отношение к объекту недвижимости
		if (presentationType == String.class && modelType == RealtyKind.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToRealtyKind.class);

		// Конвертер срока проживания
		if (presentationType == String.class && modelType == PeriodOfResidence.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToPeriodOfResidence.class);

		// Конвертер семейного положения
		if (presentationType == String.class && modelType == MaritalStatus.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToMaritalStatus.class);

		// Конвертер уровня образования
		if (presentationType == String.class && modelType == EducationKind.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToEducationKind.class);

		// Конвертер уровня образования
		if (presentationType == String.class && modelType == TypeOfEmployment.class)
			return (Converter<PRESENTATION, MODEL>) lookup(StringToTypeOfEmployment.class);

		// Конвертер статуса продукта в продаже
		if (presentationType == String.class && modelType == ProductInstance.State.class)
			return (Converter<PRESENTATION, MODEL>) lookup(String2ProdInSaleState.class);

		// Конвертер дополнительной статьи расхода по продукту
		if (presentationType == String.class && modelType == ProductExpenditure.Type.class)
			return (Converter<PRESENTATION, MODEL>) lookup(String2ProductExpenditureType.class);

		// Let default factory handle the rest
		return super.findConverter(presentationType, modelType);
	}
}


text:
package org.apache.servicecomb.serviceregistry.api;

import java.util.Map;

public interface PropertyExtended {
  Map<String, String> getExtendedProperties();
}


text:
using System.Collections.Generic;

namespace HodStudio.XitSoap
{
    public static class ServiceCatalog
    {
        public static Dictionary<string, string> Catalog { get; private set; } = new Dictionary<string, string>();

        public static string GetServiceAddress(string contractName)
        {
            return Catalog[contractName];
        }
    }
}


text:
package entity

import (
	"fmt"
    "regexp"
    "os"
)

var mData []Meeting
var uData []User

func Show() {
	fmt.Println(uData)
	fmt.Println(mData)
}
//read data from data.txt to mData and uData
func Init() {
	tmp_m := Meeting_ReadFromFile()
	tmp_u := User_ReadFromFile()
	for i := 0; i < len(tmp_u); i++ {
		uData = append(uData, tmp_u[i])
	}
	for i := 0; i < len(tmp_m); i++ {
		mData = append(mData, tmp_m[i])
	}
}

func IsEmail(str string) bool {
    var b bool
    b, _ = regexp.MatchString("^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$", str)
    if false == b {
        return b
    }
    return b
}

func IsCellphone(str string) bool {
    var b bool
    b, _ = regexp.MatchString("^1[0-9]{10}$", str)
    if false == b {
        return b
    }
    return b
}

func RegisterUser(name string, password string, email string, phone string) bool {
	var user User
	err := false
	if (IsEmail(email) == false) {
		fmt.Println("Email is error!")
		err = true
	}
	if (IsCellphone(phone) == false) {
		fmt.Println("Phone is error!")
		err = true
	}
	if (len(password) < 6) {
		fmt.Println("The length of password can't be less than 6!")
		err = true
	}
	_, isExit, _:= Query_user(name)
	if (isExit) {
		fmt.Println("This username exits, please use another username!")
		err = true
	}
	if (err) {
		return false
	}
	user.Name = name
	user.Password = password
	user.Email = email
	user.Phone = phone
	uData = append(uData,user)
	User_WriteToFile(uData)
	fmt.Println("Register successfully!")
	return true
}

func Query_meeting_by_title(title string) (Meeting, bool, int){
	for i := 0; i < len(mData); i++ {
		if mData[i].Title == title {
			return mData[i],true, i
		}
	}
	return mData[0], false, 0
}

func Query_meeting_by_participator(name string) []Meeting{
	var tmp_m []Meeting
	for i := 0; i < len(mData); i++ {
		for j := 0;j < len(mData[i].Participator); j++ {
			if mData[i].Participator[j] == name {
				tmp_m = append(tmp_m, mData[i])
			}
		}
	}
	return tmp_m
}

func Query_meeting_by_sponsor(sponsor string) []Meeting {
	var tmp_m []Meeting
	for i := 0; i < len(mData); i++ {
		if mData[i].Sponsor == sponsor {
			tmp_m = append(tmp_m, mData[i])
		}
	}
	return tmp_m
}

func Query_meeting_by_name(name string) []Meeting {
	tmp_m := Query_meeting_by_sponsor(name)
	tmp_tt := Query_meeting_by_participator(name)
	for i := 0; i < len(tmp_tt); i++ {
		tmp_m = append(tmp_m, tmp_tt[i])
	}
	return tmp_m
}
//time is overlap

func Cancell_meeting(title string, sponsor string) bool {
	_,_, i := Query_meeting_by_title(title)
	if (mData[i].Sponsor == sponsor) {
		index := i;
		mData = append(mData[:index],mData[index+1:]...)
		Meeting_WriteToFile(mData)
		return true
	} else {
		return false
	}

}

func Add_participator(name string, title string) bool {
	_,_, index := Query_meeting_by_title(title)
	tmp_mm := Query_meeting_by_name(name)
	for i := 0; i < len(tmp_mm); i++ {
		if IsOverlapping(tmp_mm[i].Start, tmp_mm[i].End, mData[index].Start, mData[index].End) {
			return false
		}
	}
	mData[index].Participator = append(mData[index].Participator,name)
	Meeting_WriteToFile(mData)
	return true
}

func Create_meeting(title string, start Date, end Date,sponsor string) bool {
	is_flag := false
	//meeting title is exist
	var m_meet Meeting
	for i := 0; i < len(mData); i++ {
		if mData[i].Title == title {
			fmt.Println("Meeting is exists!")  //error
			is_flag = true
		}
	}
	tmp_m := Query_meeting_by_name(sponsor)
	if (len(tmp_m) !=0) {
		for j := 0; j < len(tmp_m); j++ {
			if IsOverlapping(tmp_m[j].Start, tmp_m[j].End, start, end) {
				fmt.Println("Your meeting named ",tmp_m[j].Title, " is overlap with the meeting!")
				is_flag = true
			}
		}
	}
	m_meet.Sponsor = sponsor
	m_meet.Start = start
	m_meet.End = end
	m_meet.Title = title
	var m_participator []string
	fmt.Printf("Please input the number of participators : ")
	var n int
	var tt string
    fmt.Scanln(&n)
    for i := 0; i< n; i++ {
    	fmt.Scanln(&tt)
    	if tt == sponsor {
    		fmt.Println("You are the sponsor, and you don't neet to add yourself to participator!")
    		os.Exit(1)
    	}
    	m_participator = append(m_participator, tt)
    }

	count := 0
	for k := 0; k < len(m_participator); k++ {
		flag1 := true
		_,flag, _:= Query_user(m_participator[k])
		if (!flag)  {
			fmt.Println(m_participator[k], " is not registered!")
			is_flag = true
		} else {
			tmp_mm := Query_meeting_by_name(m_participator[k])
			for i := 0; i < len(tmp_mm); i++ {
				if IsOverlapping(tmp_mm[i].Start, tmp_mm[i].End, start, end) {
					flag1 = false
				}
			}
			if !flag1 {
				//time overlap
				fmt.Println(m_participator[k], " can't attend the meeting because of timeoverlap")
				is_flag = true
			} else {
				m_meet.Participator = append(m_meet.Participator, m_participator[k])
				count++;
			}
		}
	}
	if is_flag {
		fmt.Println("Create meeting failed!")
		return false
	}
	if count != 0 {
		mData = append(mData, m_meet);
		Meeting_WriteToFile(mData)
		fmt.Println("Create meeting successfully!")
		return true
	} else {
		fmt.Println("No participator! you can't create it")
		return false
	}

}

func Delete_user(name string) {
	_,_, i := Query_user(name)
	index := i;
	uData = append(uData[:index],uData[index+1:]...)
	User_WriteToFile(uData)
	//empty meeting sponsor
	Empty_meeting(name)

	tmp_m := Query_meeting_by_name(name)
	for i := 0; i< len(tmp_m); i++ {
		Rm_participator(name, tmp_m[i].Title)
	}

}

func Empty_meeting(sponsor string) int {
	count := 0
	for i := 0; i < len(mData); i++ {
        if mData[i].Sponsor == sponsor {
        	count++
            mData = append(mData[:i], mData[i+1:]...)
        }
    }
    Meeting_WriteToFile(mData)
    if count == 0 {
    	return 0
    } else {
    	return 1
    }
}

func Exit_meeting(name string,title string) int {
	return Rm_participator(name, title)
}

func Query_meeting(start Date, end Date, name string) []Meeting{
	var tmp []Meeting
	tmp_m := Query_meeting_by_participator(name)
	tmp_mm := Query_meeting_by_sponsor(name)
	for i := 0; i < len(tmp_m); i++ {
		if IsOverlapping(start, end, tmp_m[i].Start, tmp_m[i].End) {
			tmp = append(tmp, tmp_m[i])
		}
	}
	for i := 0; i < len(tmp_mm); i++ {
		if IsOverlapping(start, end, tmp_mm[i].Start, tmp_mm[i].End) {
			tmp = append(tmp, tmp_mm[i])
		}
	}
	return tmp
}

func Query_user(name string) (User,bool, int){
	for i := 0; i< len(uData); i++ {
		if uData[i].Name == name {
			return uData[i], true, i
		}
	}
	return User{"1","2","3","4"}, false, 0
}

func Rm_participator(name string, title string) int {
	_,flag,index := Query_meeting_by_title(title)
	if  !flag {
		//fmt.Println("It doesn't exists this meeting!")
		return 1
	} else {
		for i := 0; i < len(mData[index].Participator); i++ {
			if mData[index].Participator[i] == name {
				mData[index].Participator = append(mData[index].Participator[:i], mData[index].Participator[i+1:]...)
				Meeting_WriteToFile(mData)
				//fmt.Println("Remove participator successfully!")
				if len(mData[index].Participator) == 0 {
					Cancell_meeting(mData[index].Title, mData[index].Sponsor)    //0 cancell meeting
				}
				return 2
			}
		}
		if (mData[index].Sponsor == name) {
			return 3
		}
		return 4
		//fmt.Println("It doesn't exists the participator!")
	}
}