text:
package algorithms.util;

/**
 * A class to estimate the amount of memory an object takes.
 * The user should know if it is to be on the heap or
 * stack (method local variables) when comparing the results to
 * available memory.
 *
 * Options for other data-types will be added as needed.
 *
 * NOTE: need to consider an option for estimates when
 *    jvm option  UseCompressedOops is used and not used.
 *
 * NOTE: suggested other tools for determinging object size are
 *    java's Instrumentation.getObjectSize()
 *    and third party library JOL
 *        http://openjdk.java.net/projects/code-tools/jol/
 *
 * @author nichole
 */
public class ObjectSpaceEstimator {

    /*
    memory usage of an object:
    overhead of each object + memory required for type padded to 8 byte values

    overhead = ref to class, gc state info, + synchronization info
    OVERHEAD = 16 bytes

    http://users.elis.ugent.be/~leeckhou/papers/SPE06.pdf

    ----------------
    Table III. Java types and their sizes in number of bits when used in the
    heap ('field size' column) and when used on the
    stack ('size on stack' column).
                                         32-bit platform          64-bit platform
                                         Field   Size on          Field   Size on
    Java types                           size    stack            size    stack
    boolean                              32       32              32      64
    byte                                 32       32              32      64
    char                                 32       32              32      64
    short                                32       32              32      64
    int                                  32       32              32      64
    float                                 32       32              32      64
    reference                            32       32              64      64
    array reference                      32       32              32      32
    returnAddress                        32       32              64      64
    long                                 64       64              64      128
    double                               64       64              64      128

    JVM HEAP:
        -- shared among all virtual machine threads.
           holds instance variables, static fields, array elements
        -- strings are stored on the heap
    JVM METHOD AREA: [THIS is logically part of the HEAP,
        but small vms may not gc it.]
        -- shared among all virtual machine threads.
           holds structures for compiled code:
               runtime constant pool
               field data
               method data
               code for methods and constructors

    Thread Stack:
        -- local variables, references to objects, and primitives
        Frame:
            -- new one is created each time a method is invoked and destroyed
               when it's completed.
               (holds data and partial results.)
            -- has a LIFO operand stack (max depth is determined at compile time)
               -- the operand stack is empty when frame is created
               -- jvm loads constants, local variable values, or fields onto operand stack
        -- default size dpends on architecture and impl.  usually is 512K or 1024K
    */

    private int nBoolean = 0;
    private int nByte = 0;
    private int nChar = 0;
    private int nShort = 0;
    private int nInt = 0;
    private int nFloat = 0;
    private int nObjRefs = 0;
    private int nArrayRefs = 0;
    private int nLong = 0;
    private int nDouble = 0;
    private int nReturnAddress = 0;

    /**
     * Strings have special handling.  They are always on the heap and they
     * may be pooled (re-used) for some JVMs.
     */
    private int nStrings = 0;
    private int maxStringLength = 0;

    // sizes in bytes as [heap 32 bit, stack 32 bit, heap 54 bit, stack 64 bit]
    //private final static int objOverheadSz = 16;

    private final static int[] word3264 = new int[]{4, 4, 4, 8};

    private static String arch = System.getProperty("sun.arch.data.model");
    private static boolean is32Bit = ((arch != null) && arch.equals("64")) ? false : true;

    private final static int[] booleanSz = word3264;
    private final static int[] byteSz = word3264;
    private final static int[] charSz = word3264;
    private final static int[] shortSz = word3264;
    private final static int[] intSz  = word3264;
    private final static int[] floatSz = word3264;
    private final static int[] refSz = new int[]{4, 4, 8, 8};
    // the array refs for 64 bit being 4 bytes are due to default compressed ops?
    private final static int[] arrayRefSz = new int[]{4, 4, 4, 4};
    private final static int[] returnAddressSz = new int[]{4, 4, 8, 8};
    private final static int[] longSz = new int[]{8, 8, 8, 16};
    private final static int[] doubleSz = new int[]{8, 8, 8, 16};

    /**
     * @param nBoolean  the number of boolean primitives
     */
    public void setNBooleanFields(int nBoolean) {
        this.nBoolean = nBoolean;
    }

    public static long getWordSize() {
        if (is32Bit) {
            return 4;
        } else {
            return 8;
        }
    }

    public static long getObjectOverhead() {
        if (is32Bit) {
            return 8;
        } else {
            return 16;
        }
    }

    public static long getObjectReferenceSize() {
        int index;
        long overhead;
        if (is32Bit) {
            index = 0;
            overhead = 8;
        } else {
            index = 2;
            overhead = 16;
        }

        return refSz[index];
    }

    public static long getArrayReferenceSize() {
        int index;
        long overhead;
        if (is32Bit) {
            index = 0;
            overhead = 8;
        } else {
            index = 2;
            overhead = 16;
        }
        return arrayRefSz[index];
    }

    /**
     * @param nByte  the number of byte primitives
     */
    public void setNByteFields(int nByte) {
        this.nByte = nByte;
    }

    /**
     * @param nChar the number of char primitives to set
     */
    public void setNCharFields(int nChar) {
        this.nChar = nChar;
    }

    /**
     * @param nShort  the number of short primitives
     */
    public void setNShortFields(int nShort) {
        this.nShort = nShort;
    }

    /**
     * @param nInt  the number of int primitives
     */
    public void setNIntFields(int nInt) {
        this.nInt = nInt;
    }

    /**
     * @param nFloat  the number of float primitives
     */
    public void setNFloatFields(int nFloat) {
        this.nFloat = nFloat;
    }

    /**
     * @param nObjRefs  the number of object references
     */
    public void setNObjRefsFields(int nObjRefs) {
        this.nObjRefs = nObjRefs;
    }

    /**
     * @param nArrayRefs  the number of array references to set
     */
    public void setNArrayRefsFields(int nArrayRefs) {
        this.nArrayRefs = nArrayRefs;
    }

    /**
     * @param nLong  the number of long primitives
     */
    public void setNLongFields(int nLong) {
        this.nLong = nLong;
    }

    /**
     * @param nDouble the number of double primitives
     */
    public void setNDoubleFields(int nDouble) {
        this.nDouble = nDouble;
    }

    /**
     * @param nReturnAddress the nReturnAddress to set
     */
    public void setNReturnAddress(int nReturnAddress) {
        this.nReturnAddress = nReturnAddress;
    }

    /**
     * NOTE: since strings are interned and only one instance exists for same
     * string, should consider not setting this.
     *
     * If only one string estimate is needed, consider using
     * estimateAStringSize()
     *
     * @param numberOfStrings
     * @param maximumNumberOfLetters
     */
    public void setNStrings(int numberOfStrings, int maximumNumberOfLetters) {
        nStrings = numberOfStrings;
        maxStringLength = maximumNumberOfLetters;
    }

    /**
     * A rough estimate of an instance of ArrayList without objects in it.
     *
     * @return
     */
    public static long estimateArrayList() {

        int index;
        long overhead;
        if (is32Bit) {
            index = 0;
            overhead = 8;
        } else {
            index = 2;
            overhead = 16;
        }
        long pad = getWordSize();

        long total = overhead;

        total += longSz[index];
        total += 5 * intSz[index];
        total += 3*arrayRefSz[index];

        return total;

        /*
        final int nLists = 10000;
        final int nObjects = 25;

        long totalMemory = Runtime.getRuntime().totalMemory();
        MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();

        long heapUsage = mbean.getHeapMemoryUsage().getUsed();
        long avail = totalMemory - heapUsage;

        List[] lists = new List[nLists];
        for (int i = 0; i < nLists/2; ++i) {
            lists[i] = new ArrayList();
            for (int j = 0; j < nObjects; ++j) {
                lists[i].add(new Object());
            }
        }

        long heapUsage1 = mbean.getHeapMemoryUsage().getUsed();
        long avail1 = totalMemory - heapUsage1;
        long used1 = heapUsage1 - heapUsage;

        for (int i = nLists/2; i < nLists; ++i) {
            for (int j = 0; j < nObjects; ++j) {
                lists[i].add(new Object());
            }
        }

        long heapUsage2 = mbean.getHeapMemoryUsage().getUsed();
        long avail2 = totalMemory - heapUsage2;
        long used2 = heapUsage2 - heapUsage;

        //System.out.format("%d lists with no objects size =%d%n", nLists, used1);
        //System.out.format("list with %d objects size =%d%n", nObjects, used2);

        long nObjectsSize =
            nObjects * ObjectSpaceEstimator.getReferenceSize();
            //+ nObjects * ObjectSpaceEstimator.getObjectOverhead();

        long diff = used2 - used1;
        diff /= (nLists/2);

        // assume that the List and the fields which are not the backing
        // arrays are small in size compared to the nObjects
        diff /= nObjectsSize;

        //System.out.println("list after subtracting nObjects from difference ="
        //    + diff);

        return diff;
        */
    }

    /**
     * a rough estimate of an instance of TLongLongHashMap without objects
     * in it.
     *
     * @return
     */
    public static long estimateTLongLongHashMap() {

        int index;
        long overhead;
        if (is32Bit) {
            index = 0;
            overhead = 8;
        } else {
            index = 2;
            overhead = 16;
        }
        long pad = getWordSize();

        long total = overhead;

        total += 4 * longSz[index];
        total += booleanSz[index];
        total += refSz[index];
        total += 2*arrayRefSz[index];

        return total;

    }

    /**
     * a rough estimate of an instance of TLongObjectHashMap without objects
     * in it.

     * @return
     */
    public static long estimateTLongObjectHashMap() {
        int index;
        long overhead;
        if (is32Bit) {
            index = 0;
            overhead = 8;
        } else {
            index = 2;
            overhead = 16;
        }
        long pad = getWordSize();

        long total = overhead;

        total += 4 * longSz[index];
        total += booleanSz[index];
        total += refSz[index];
        total += 2*arrayRefSz[index];

        return total;

        /*
        final int nMaps = 10000;
        final int nObjects = 25;

        long totalMemory = Runtime.getRuntime().totalMemory();
        MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();

        long heapUsage = mbean.getHeapMemoryUsage().getUsed();
        long avail = totalMemory - heapUsage;

        TLongObjectHashMap[] maps = new TLongObjectHashMap[nMaps];
        for (int i = 1; i < nMaps/2; ++i) {
            maps[i] = new TLongObjectHashMap();
            for (int j = 0; j < nObjects; ++j) {
                maps[i].put(j, new Object());
            }
        }

        long heapUsage1 = mbean.getHeapMemoryUsage().getUsed();
        long avail1 = totalMemory - heapUsage1;
        long used1 = heapUsage1 - heapUsage;

        for (int i = nMaps/2; i < nMaps; ++i) {
            maps[i] = new TLongObjectHashMap();
            for (int j = 0; j < nObjects; ++j) {
                maps[i].put(j, new Object());
            }
        }

        long heapUsage2 = mbean.getHeapMemoryUsage().getUsed();
        long avail2 = totalMemory - heapUsage2;
        long used2 = heapUsage2 - heapUsage;

        //System.out.format("%d maps with no objects size =%d%n", nMaps, used1);

        //System.out.format("map with %d objects size =%d%n", nObjects, used2);

        long nObjectsSize =
            nObjects * ObjectSpaceEstimator.getReferenceSize();

        long diff = used2 - used1;
        diff /= (nMaps/2);

        // assume that the List and the fields which are not the backing
        // arrays are small in size compared to the nObjects
        diff /= (2*nObjects);

        //System.out.println("map after subtracting nObjects from difference ="
        //    + diff);

        return diff;
        */
    }

    /**
     * estimate the size of an object in bytes for the given settings and for
     * placement on the heap.
     *
     * Note that the string estimates are the maximum size in memory they could
     * occupy and do not include consideration for pooling.
     *
     * @return total size in bytes for the object placed on the heap.
     */
    public long estimateSizeOnHeap() {
        return estimateSize(true);
    }

    /**
     * estimate the size of an object in bytes for the given settings and for
     * placement on the stack (variables specific to a method frame, that is,
     * local variables).
     *
     * Note that the string estimates will not be in the stack estimate as they
     * are purely heap objects.
     *
     * @return total size in bytes for the object places on the stack.
     */
    public long estimateSizeOnStack() {
        return estimateSize(false);
    }

    private long estimateSize(boolean calcForHeap) {

        int index;
        long overhead;
        if (is32Bit) {
            if (calcForHeap) {
                index = 0;
            } else {
                index = 1;
            }
            overhead = 8;
        } else {
            if (calcForHeap) {
                index = 2;
            } else {
                index = 3;
            }
            overhead = 16;
        }
        long pad = getWordSize();

        long total = 0;

        // add fields
        total += nBoolean * booleanSz[index];
        total += nByte * byteSz[index];
        total += nChar * charSz[index];
        total += nShort * shortSz[index];
        total += nInt * intSz[index];
        total += nFloat * floatSz[index];
        total += nObjRefs * refSz[index];
        total += nArrayRefs * arrayRefSz[index];
        total += nLong * longSz[index];
        total += nDouble * doubleSz[index];
        total += nReturnAddress * returnAddressSz[index];

        if (calcForHeap) {
            total += nStrings * estimateAStringSize(maxStringLength);
        }

        // add object overhead
        total += overhead;

        // pad up to 8 byte boundary
        long padding = total % pad;
        total += padding;

        return total;
    }

    public static long estimateLongSize() {

        int idx;
        if (is32Bit) {
            idx = 0;
        } else {
            idx = 2;
        }

        return longSz[idx];
    }

    public static long estimateIntSize() {

        int idx;
        if (is32Bit) {
            idx = 0;
        } else {
            idx = 2;
        }

        return intSz[idx];
    }

    public static long estimateAStringSize(int maxNumberOfLetters) {

        // strings are always on the heap
        int idx;
        if (is32Bit) {
            idx = 0;
        } else {
            idx = 2;
        }

        long total = arrayRefSz[idx];
        total += maxNumberOfLetters * charSz[idx];

        long pad = total % getWordSize();

        total += pad;

        return total;
    }

}


text:
import os
import textwrap
import unittest
from jinja2 import Template

from conans.model.ref import ConanFileReference
from parameterized import parameterized
from conans.test.utils.tools import TestClient

class PythonRequireExportSourcesTest(unittest.TestCase):
    def setUp(self):
        self.pyreq = ConanFileReference.loads("py/req@user/channel")
        conanfile = textwrap.dedent("""\
            import os
            from conans import ConanFile, tools

            class PyReq(ConanFile):
                exports_sources = "exports_sources.txt", "more_exports_sources.txt"
                exports = "exports.txt", "more_exports.txt"

                def source(self, is_empty):
                    self.output.info(">>>> PyReq::source")
                    self.output.info(">>>> - source_folder: {{}}".format(self.source_folder))
                    file_list = sorted(os.listdir(self.source_folder))
                    self.output.info(">>>> - source list: {{}}".format(file_list))
                    if is_empty:
                        assert not file_list, "No files expected, found {{}}".format(file_list)
                    else:
                        assert file_list, "Files expected, but it is empty"
                        assert sorted(["more_exports_sources.txt", "more_exports.txt"]) == file_list
            """.format(pyreq_name=self.pyreq.name))

        self.t = TestClient()
        self.t.save({"conanfile.py": conanfile,
                     "exports_sources.txt": "exports_sources: {}".format(str(self.pyreq)),
                     "exports.txt": "exports: {}".format(str(self.pyreq))})
        self.t.run("export . {}".format(self.pyreq))
        package_layout = self.t.cache.package_layout(self.pyreq)
        self.assertListEqual(['exports_sources.txt'],
                             os.listdir(package_layout.export_sources()))
        self.assertListEqual(sorted(['exports.txt', 'conanfile.py', 'conanmanifest.txt']),
                             sorted(os.listdir(package_layout.export())))

    @parameterized.expand([(False, ), (True, )])
    def test_locate_pyreq_folders(self, empty_exports):
        conanfile = Template(textwrap.dedent("""\
            from conans import ConanFile, python_requires

            base = python_requires("{{ pyreq }}")

            class MyLib(base.PyReq):
                {% if empty %}
                exports_sources = None
                exports = None
                {% endif %}

                def source(self):
                    super(MyLib, self).source(is_empty={{ empty }})

                    self.output.info(">>>> MyLib::source")
                    pyreq = self.python_requires['{{ pyreq.name }}']
                    self.output.info(" - pyreq::ref: {{{}}}".format(str(pyreq.ref)))
                    self.output.info(" - pyreq::exports_sources: {{{}}}".format(pyreq.exports_sources_folder))
                    self.output.info(" - pyreq::exports: {{{}}}".format(pyreq.exports_folder))

            """))
        content = conanfile.render(pyreq=self.pyreq, empty=empty_exports)

        ref = ConanFileReference.loads("lib/version@user/channel")
        self.t.save({"conanfile.py": content}, clean_first=True)
        if not empty_exports:
            # Write some files, these will be exported because they match patterns in pyreq
            self.t.save({"more_exports.txt": "...",
                         "more_exports_sources.txt": "..."})
        self.t.run("create . {}".format(ref))

        # Check things written in 'source' method (source folder executed in consumer context)
        source_folder = self.t.cache.package_layout(ref).source()
        self.assertIn(">>>> PyReq::source", self.t.out)
        self.assertIn(">>>> - source_folder: {}".format(source_folder), self.t.out)
        if not empty_exports:
            self.assertIn(">>>> - source list: ['more_exports.txt', 'more_exports_sources.txt']",
                          self.t.out)
        else:
            self.assertIn(">>>> - source list: []", self.t.out)

        # Access to sources from pyreq, check folders match
        pyreq_layout = self.t.cache.package_layout(self.pyreq)
        self.assertIn(" - pyreq::ref: {}".format(self.pyreq), self.t.out)
        self.assertIn(" - pyreq::exports_sources: %s" % pyreq_layout.export_sources(), self.t.out)
        self.assertIn(" - pyreq::exports: %s" % pyreq_layout.export(), self.t.out)

redpajama_set_name: RedPajamaGithub


text:
/*
 * Qc API
 *
 * Qc API
 *
 * API version: 3.0.0
 * Contact: cloudsupport@telestream.net
 * Generated by: OpenAPI Generator (https://openapi-generator.tech)
 */

package qc

type EnhancedSyntaxTest struct {
	CheckContainer bool `json:"check_container,omitempty"`
	CheckElementaryStream bool `json:"check_elementary_stream,omitempty"`
	RejectOnError bool `json:"reject_on_error,omitempty"`
	Checked bool `json:"checked,omitempty"`
}


text:
typedef enum : NSUInteger {
    kNotificationTypeLike,
    kNotificationTypeComment,
    kNotificationTypeFollowed,
    kNotificationTypeTaggedPost,
    kNotificationTypeTaggedComment
} NotificationType;

@interface Notification : NSObject

@property (nonatomic, retain) NSString *id_notific;
@property NotificationType type;
@property (nonatomic, retain) NSString *id_sender;
@property (nonatomic, retain) NSString *sender_name;
@property (nonatomic, retain) NSString *sender_surname;
@property (nonatomic, retain) NSString *sender_nickname;
@property (nonatomic, retain) UIImage *sender_image;
@property (nonatomic, retain) NSString *sender_image_name;
@property (nonatomic, retain) NSString *id_receiver;
@property (nonatomic, retain) NSString *post_id;
@property (nonatomic, retain) NSString *comment_id;
@property (nonatomic, retain) NSString *title_post;
@property (nonatomic, retain) NSString *descr_comment;
@property BOOL is_new;
@property (nonatomic, retain) NSDate *timestamp;
@property (nonatomic, retain) NSMutableAttributedString *attributedString;

-(id)initWithId:(NSString *)id_notific type:(NSString *)type id_sender:(NSString *)id_sender sender_nickname:(NSString *)sender_nickname sender_name:(NSString *)sender_name sender_surname:(NSString *)sender_surname sender_image:(NSString *)sender_image id_receiver:(NSString *)id_receiver comment_id:(NSString *)comment_id post_id:(NSString *)post_id title_post:(NSString *)title_post descr_comment:(NSString *)descr_comment is_new:(NSString *)is_new timestamp:(NSString *)timestamp;
-(id)initWithEncryptedDictonary:(NSDictionary *)n;
-(id)initWithDictonary:(NSDictionary *)n;

-(NSMutableDictionary *)toDictionary;

@end


text:
/*
   This module generates Helper functions for the C API
*/

#include "idl_program.h"
#include "idl_scope.h"
#include "idl_keyDef.h"
#include "idl_genCorbaCHelper.h"
#include "idl_genCHelper.h"
#include "idl_genLanguageHelper.h"
#include "idl_tmplExp.h"

#include "c_typebase.h"

/* idl_null is an empty function, used to bypass QAC errors */
static void
idl_null(
    void)
{
}

/* fileOpen callback

   return idl_explore to state that the rest of the file needs to be processed
*/
static idl_action
idl_fileOpen(
    idl_scope scope,
    const char *name,
    void *userData)
{
    OS_UNUSED_ARG(scope);
    OS_UNUSED_ARG(name);
    OS_UNUSED_ARG(userData);

    return idl_explore;
}

/* moduleOpen callback

   return idl_explore to state that the rest of the module needs to be processed
*/
static idl_action
idl_moduleOpen(
    idl_scope scope,
    const char *name,
    void *userData)
{
    OS_UNUSED_ARG(scope);
    OS_UNUSED_ARG(name);
    OS_UNUSED_ARG(userData);

    return idl_explore;
}

/* structureOpen callback

   A structure is a type that can be communicated via the DCPS API.
   A structure can have a key list defining all key fields.
   For the structure the following helper functions are defined:
   - a function to query the structures scoped type name
   - a function to query the structures key list
   The name of the functions are:
       __<scope-elements>_<struct-name>__name
   and
       __<scope-elements>_<struct-name>__keys
   respectively.

   return idl_abort to state that the rest of the structure does not need to be processed
*/
static idl_action
idl_structureOpen (
    idl_scope scope,
    const char *name,
    idl_typeStruct structSpec,
    void *userData)
{
    const c_char *key_list;

    OS_UNUSED_ARG(structSpec);
    OS_UNUSED_ARG(userData);

    idl_fileOutPrintf(idl_fileCur(), "const char *\n");
    idl_fileOutPrintf(
        idl_fileCur(),
        "__%s__name(void)\n",
        idl_scopeStack(scope, "_", name));
    idl_fileOutPrintf(idl_fileCur(), "{\n");

    idl_fileOutPrintf(
        idl_fileCur(),
        "    return (const char*)\"%s\";\n",
        idl_scopeStack(scope, "::", name));

    idl_fileOutPrintf(idl_fileCur(), "}\n");
    idl_fileOutPrintf(idl_fileCur(), "\n");
    key_list = idl_keyResolve(idl_keyDefDefGet(), scope, name);
    idl_fileOutPrintf(idl_fileCur(), "const char *\n");
    idl_fileOutPrintf(
        idl_fileCur(),
        "__%s__keys(void)\n",
        idl_scopeStack (scope, "_", name));
    idl_fileOutPrintf(idl_fileCur(), "{\n");
    if (key_list) {
        idl_fileOutPrintf(idl_fileCur(), "    return (const char*)\"%s\";\n", key_list);
    } else {
        idl_fileOutPrintf(idl_fileCur(), "    return (const char*)\"\";\n");
    }
    idl_fileOutPrintf(idl_fileCur(), "}\n");
    idl_fileOutPrintf(idl_fileCur(), "\n");

    return idl_abort;
}

/* unionOpen callback

   A union is a type that can be communicated via the DCPS API.
   A union can have a key list defining all key fields (practically
   only the switch).
   For the union the following helper functions are defined:
   - a function to query the union scoped type name
   - a function to query the union key list
   The name of the functions are:
       __<scope-elements>_<union-name>__name
   and
       __<scope-elements>_<union-name>__keys
   respectively.

   return idl_abort to state that the rest of the union does not need to be processed
*/
static idl_action
idl_unionOpen(
    idl_scope scope,
    const char *name,
    idl_typeUnion unionSpec,
    void *userData)
{
    const c_char *key_list;
    OS_UNUSED_ARG(unionSpec);
    OS_UNUSED_ARG(userData);

    OS_UNUSED_ARG(unionSpec);
    OS_UNUSED_ARG(userData);

    idl_fileOutPrintf(idl_fileCur(), "const char *\n");
    idl_fileOutPrintf(idl_fileCur(), "__%s__name(void)\n",
	idl_scopeStack(scope, "_", name));
    idl_fileOutPrintf(idl_fileCur(), "{\n");

    idl_fileOutPrintf(
        idl_fileCur(),
        "    return (const char*)\"%s\";\n",
        idl_scopeStack(scope, "::", name));

    idl_fileOutPrintf(idl_fileCur(), "}\n");
    idl_fileOutPrintf(idl_fileCur(), "\n");
    key_list = idl_keyResolve(idl_keyDefDefGet(), scope, name);
    idl_fileOutPrintf(idl_fileCur(), "const char *\n");
    idl_fileOutPrintf(
        idl_fileCur(),
        "__%s__keys(void)\n",
        idl_scopeStack(scope, "_", name));
    idl_fileOutPrintf(idl_fileCur(), "{\n");
    if (key_list) {
        idl_fileOutPrintf(
            idl_fileCur(),
            "    return (const char *)\"%s\";\n",
            key_list);
    } else {
        idl_fileOutPrintf(idl_fileCur(), "    return (const char *)\"\";\n");
    }
    idl_fileOutPrintf(idl_fileCur(), "}\n");
    idl_fileOutPrintf(idl_fileCur(), "\n");

    return idl_abort;
}

/* typedefOpen callback

   A typedef of a structure or union is a type that can be
   communicated via the DCPS API.
   For the typedef the following helper functions are defined:
   - a function to query the typedef scoped type name
   - a function to query the typedef key list
   The name of the functions are:
       __<scope-elements>_<typedef-name>__name
   and
       __<scope-elements>_<typedef-name>__keys
   respectively.
*/
static void
idl_typedefOpenClose (
    idl_scope scope,
    const char *name,
    idl_typeDef defSpec,
    void *userData)
{
    switch (idl_typeSpecType(idl_typeDefActual(defSpec))) {
    case idl_tstruct:
        idl_structureOpen(scope, name, idl_typeStruct(idl_typeDefActual(defSpec)), userData);
	break;
    case idl_tunion:
        idl_unionOpen(scope, name, idl_typeUnion(idl_typeDefActual(defSpec)), userData);
	break;
    default:
        /* Empty statement to satisfy QAC */
        idl_null();
	break;
    }
}

/* idl_genCorbaCHelper specifies the local
   callback routines
*/
static struct idl_program
idl_genCorbaCHelper = {
    NULL,
    idl_fileOpen,
    NULL, /* idl_fileClose */
    idl_moduleOpen,
    NULL, /* idl_moduleClose */
    idl_structureOpen,
    NULL, /* idl_structureClose */
    NULL, /* idl_structureMemberOpenClose */
    NULL, /* idl_enumerationOpen */
    NULL, /* idl_enumerationClose */
    NULL, /* idl_enumerationElementOpenClose */
    idl_unionOpen,
    NULL, /* idl_unionClose */
    NULL, /* idl_unionCaseOpenClose */
    NULL, /* idl_unionLabelsOpenClose */
    NULL, /* idl_unionLabelOpenClose */
    idl_typedefOpenClose,
    NULL, /* idl_boundedStringOpenClose */
    NULL, /* idl_sequenceOpenClose */
    NULL, /* idl_constantOpenClose */
    NULL, /* idl_artificialDefaultLabelOpenClose */
    NULL  /* userData */
};

/* genCorbaCxxHelperProgram returns the local
   table of callback routines.
*/
idl_program
idl_genCorbaCHelperProgram(
    void)
{
    return &idl_genCorbaCHelper;
}


text:
namespace EventQueue
{
	struct Event
	{
		enum Types{
			INTERRUPT = 0,
			TILEDONE = 1,
			FRAMEDONE = 2,
			RENDERDONE = 3,
			PRETILE = 4,
			FRAMEUPDATE = 5,
			IPRSTART = 6,
			IPRSTOP = 7,
			IPRPAUSE = 8,
			IPRREMOVE = 9,
			IPRUPDATE = 10,
			IPRFRAMEDONE = 11,
			STARTRENDER = 12,
			FINISH = 13,
			IPRUPDATESCENE = 14,
			USER = 15,
			PIXELSDONE = 16,
			UPDATEUI = 17,
			RENDERERROR = 18,
			INITRENDER = 19,
			INTERACTIVEFBCALLBACK = 20,
			ADDIPRCALLBACKS = 21,
			FRAMERENDER = 22
		};
		enum PixelMode{
			RECT = 0,
			PIXELS = 1
		};
		Types type;
		PixelMode pixelMode;
		size_t numPixels;
		MString message;
		// i use shared ptr here because if I push it into a queue, I make a copy
		// of the original what means I would have to move the move the unique_ptr<>
		// of a const object because it is automatically created Event( const & Event ) and const
		// elements cannot be modified so I have to use another way here
		std::shared_ptr<RV_PIXEL> pixelData;
		std::shared_ptr<MayaTo::CmdArgs> cmdArgsData;

		size_t tile_xmin, tile_xmax, tile_ymin, tile_ymax;
		Event()
		{
			type = INTERRUPT;
			pixelMode = RECT;
			numPixels = 0;
		}
		~Event()
		{
		}
	};

template<typename Data>
class concurrent_queue
{
private:
    std::queue<Data> the_queue;
    mutable boost::mutex the_mutex;
    boost::condition_variable the_condition_variable;
public:
    void push(Data const& data)
    {
        boost::mutex::scoped_lock lock(the_mutex);
        the_queue.push(data);
        lock.unlock();
        the_condition_variable.notify_one();
    }

    bool empty() const
    {
        boost::mutex::scoped_lock lock(the_mutex);
        return the_queue.empty();
    }

    size_t size() const
    {
		return the_queue.size();
    }

    bool try_pop(Data& popped_value)
    {
        boost::mutex::scoped_lock lock(the_mutex);
        if(the_queue.empty())
        {
            return false;
        }

        popped_value=the_queue.front();
        the_queue.pop();
        return true;
    }

    void wait_and_pop(Data& popped_value)
    {
        boost::mutex::scoped_lock lock(the_mutex);
        while(the_queue.empty())
        {
            the_condition_variable.wait(lock);
        }
        popped_value=the_queue.front();
        the_queue.pop();
    }

};

static concurrent_queue<Event> EventList;
static concurrent_queue<Event> LogEventList;

concurrent_queue<Event> *theQueue();
concurrent_queue<Event> *theLogQueue();

} // namespace EventQueue

#endif


text:
If you'd like to run the test suite, fix a bug or add a feature, please follow these steps:

* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
* Check out the latest `master` branch to make sure the feature hasn't been implemented or the bug hasn't been fixed
* Fork the project
* Install all dependencies: `bundle install`
* Start a feature/bugfix branch: `git checkout -b my_feature_name`
* Place a `.env` file in the root of the project with `API_KEY` and `APPLICATION_KEY`:

        API_KEY: myapikey
        APPLICATION_KEY: chefhandlerspecificapplicationkey

  This file is intentionally .gitignored to prevent security exposure.
  You may use your own Datadog account keys, as the keys are filtered from the test recordings.
  Running the test suite will _not_ make calls to Datadog for existing tests, see `spec/support/cassettes/` for more.

* Run `rake` to execute tests, ensure they pass
* Commit and push until you are happy with your contribution
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the `Rakefile`, version, or history.
  If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

## Building and using local snapshots

Sometimes you need to test chef-handler-datadog before a fix is merged.  In this case you need to:

* Set the version in `lib/chef_handler_datadog.rb`
  If the current version is `0.11.0` then you should bump to `0.11.1.pre`.
  This way when the next version is released it will take precedence over your snapshot.
* Run `rake build`, this will create the .gem file in the `pkg/` dir
* Copy the .gem file to your own gem server
* When you include `datadog::dd-handler` in your Chef runlist set `node.override['datadog']['gem_server']` to your gem server URL and `node.override['datadog']['chef_handler_version']` to your `.pre` version.
* Chef will install your version of the gem
* Don't forget to unset `gem_server` and `chef_handler_version` once the handler has been released with your changes


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/dom/PContentParent.h"
#include "RegistryMessageUtils.h"
#include "nsResProtocolHandler.h"

#include "nsChromeRegistryChrome.h"

#if defined(XP_WIN)
#include <windows.h>
#elif defined(XP_MACOSX)
#include <CoreServices/CoreServices.h>
#elif defined(MOZ_WIDGET_GTK2)
#include <gtk/gtk.h>
#endif

#include "nsArrayEnumerator.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsComponentManager.h"
#include "nsEnumeratorUtils.h"
#include "nsNetUtil.h"
#include "nsStringEnumerator.h"
#include "nsTextFormatter.h"
#include "nsUnicharUtils.h"
#include "nsXPCOMCIDInternal.h"
#include "nsZipArchive.h"

#include "mozilla/LookAndFeel.h"

#include "nsICommandLine.h"
#include "nsILocaleService.h"
#include "nsIFile.h"
#include "nsIObserverService.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsIResProtocolHandler.h"
#include "nsIScriptError.h"
#include "nsIVersionComparator.h"
#include "nsIXPConnect.h"
#include "nsIXULAppInfo.h"
#include "nsIXULRuntime.h"

#define UILOCALE_CMD_LINE_ARG "UILocale"

#define MATCH_OS_LOCALE_PREF "intl.locale.matchOS"
#define SELECTED_LOCALE_PREF "general.useragent.locale"
#define SELECTED_SKIN_PREF   "general.skins.selectedSkin"

using namespace mozilla;

static PLDHashOperator
RemoveAll(PLDHashTable *table, PLDHashEntryHdr *entry, uint32_t number, void *arg)
{
  return (PLDHashOperator) (PL_DHASH_NEXT | PL_DHASH_REMOVE);
}

// We use a "best-fit" algorithm for matching locales and themes.
// 1) the exact selected locale/theme
// 2) (locales only) same language, different country
//    e.g. en-GB is the selected locale, only en-US is available
// 3) any available locale/theme

/**
 * Match the language-part of two lang-COUNTRY codes, hopefully but
 * not guaranteed to be in the form ab-CD or abz-CD. "ab" should also
 * work, any other garbage-in will produce undefined results as long
 * as it does not crash.
 */
static bool
LanguagesMatch(const nsACString& a, const nsACString& b)
{
  if (a.Length() < 2 || b.Length() < 2)
    return false;

  nsACString::const_iterator as, ae, bs, be;
  a.BeginReading(as);
  a.EndReading(ae);
  b.BeginReading(bs);
  b.EndReading(be);

  while (*as == *bs) {
    if (*as == '-')
      return true;

    ++as; ++bs;

    // reached the end
    if (as == ae && bs == be)
      return true;

    // "a" is short
    if (as == ae)
      return (*bs == '-');

    // "b" is short
    if (bs == be)
      return (*as == '-');
  }

  return false;
}

nsChromeRegistryChrome::nsChromeRegistryChrome()
  : mProfileLoaded(false)
{
  mPackagesHash.ops = nullptr;
}

nsChromeRegistryChrome::~nsChromeRegistryChrome()
{
  if (mPackagesHash.ops)
    PL_DHashTableFinish(&mPackagesHash);
}

nsresult
nsChromeRegistryChrome::Init()
{
  nsresult rv = nsChromeRegistry::Init();
  if (NS_FAILED(rv))
    return rv;

  mOverlayHash.Init();
  mStyleHash.Init();

  mSelectedLocale = NS_LITERAL_CSTRING("en-US");
  mSelectedSkin = NS_LITERAL_CSTRING("classic/1.0");

  if (!PL_DHashTableInit(&mPackagesHash, &kTableOps,
                         nullptr, sizeof(PackageEntry), 16))
    return NS_ERROR_FAILURE;

  bool safeMode = false;
  nsCOMPtr<nsIXULRuntime> xulrun (do_GetService(XULAPPINFO_SERVICE_CONTRACTID));
  if (xulrun)
    xulrun->GetInSafeMode(&safeMode);

  nsCOMPtr<nsIPrefService> prefserv (do_GetService(NS_PREFSERVICE_CONTRACTID));
  nsCOMPtr<nsIPrefBranch> prefs;

  if (safeMode)
    prefserv->GetDefaultBranch(nullptr, getter_AddRefs(prefs));
  else
    prefs = do_QueryInterface(prefserv);

  if (!prefs) {
    NS_WARNING("Could not get pref service!");
  }
  else {
    nsXPIDLCString provider;
    rv = prefs->GetCharPref(SELECTED_SKIN_PREF, getter_Copies(provider));
    if (NS_SUCCEEDED(rv))
      mSelectedSkin = provider;

    SelectLocaleFromPref(prefs);

    rv = prefs->AddObserver(MATCH_OS_LOCALE_PREF, this, true);
    rv = prefs->AddObserver(SELECTED_LOCALE_PREF, this, true);
    rv = prefs->AddObserver(SELECTED_SKIN_PREF, this, true);
  }

  nsCOMPtr<nsIObserverService> obsService = mozilla::services::GetObserverService();
  if (obsService) {
    obsService->AddObserver(this, "command-line-startup", true);
    obsService->AddObserver(this, "profile-initial-state", true);
  }

  return NS_OK;
}

NS_IMETHODIMP
nsChromeRegistryChrome::CheckForOSAccessibility()
{
  int32_t useAccessibilityTheme =
    LookAndFeel::GetInt(LookAndFeel::eIntID_UseAccessibilityTheme, 0);

  if (useAccessibilityTheme) {
    /* Set the skin to classic and remove pref observers */
    if (!mSelectedSkin.EqualsLiteral("classic/1.0")) {
      mSelectedSkin.AssignLiteral("classic/1.0");
      RefreshSkins();
    }

    nsCOMPtr<nsIPrefBranch> prefs (do_GetService(NS_PREFSERVICE_CONTRACTID));
    if (prefs) {
      prefs->RemoveObserver(SELECTED_SKIN_PREF, this);
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
nsChromeRegistryChrome::GetLocalesForPackage(const nsACString& aPackage,
                                       nsIUTF8StringEnumerator* *aResult)
{
  nsTArray<nsCString> *a = new nsTArray<nsCString>;
  if (!a)
    return NS_ERROR_OUT_OF_MEMORY;

  PackageEntry* entry =
      static_cast<PackageEntry*>(PL_DHashTableOperate(&mPackagesHash,
                                                      & aPackage,
                                                      PL_DHASH_LOOKUP));

  if (PL_DHASH_ENTRY_IS_BUSY(entry)) {
    entry->locales.EnumerateToArray(a);
  }

  nsresult rv = NS_NewAdoptingUTF8StringEnumerator(aResult, a);
  if (NS_FAILED(rv))
    delete a;

  return rv;
}

static nsresult
getUILangCountry(nsACString& aUILang)
{
  nsresult rv;

  nsCOMPtr<nsILocaleService> localeService = do_GetService(NS_LOCALESERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoString uiLang;
  rv = localeService->GetLocaleComponentForUserAgent(uiLang);
  NS_ENSURE_SUCCESS(rv, rv);

  CopyUTF16toUTF8(uiLang, aUILang);
  return NS_OK;
}

NS_IMETHODIMP
nsChromeRegistryChrome::IsLocaleRTL(const nsACString& package, bool *aResult)
{
  *aResult = false;

  nsAutoCString locale;
  GetSelectedLocale(package, locale);
  if (locale.Length() < 2)
    return NS_OK;

  // first check the intl.uidirection.<locale> preference, and if that is not
  // set, check the same preference but with just the first two characters of
  // the locale. If that isn't set, default to left-to-right.
  nsAutoCString prefString = NS_LITERAL_CSTRING("intl.uidirection.") + locale;
  nsCOMPtr<nsIPrefBranch> prefBranch (do_GetService(NS_PREFSERVICE_CONTRACTID));
  if (!prefBranch)
    return NS_OK;

  nsXPIDLCString dir;
  prefBranch->GetCharPref(prefString.get(), getter_Copies(dir));
  if (dir.IsEmpty()) {
    int32_t hyphen = prefString.FindChar('-');
    if (hyphen >= 1) {
      nsAutoCString shortPref(Substring(prefString, 0, hyphen));
      prefBranch->GetCharPref(shortPref.get(), getter_Copies(dir));
    }
  }
  *aResult = dir.EqualsLiteral("rtl");
  return NS_OK;
}

nsresult
nsChromeRegistryChrome::GetSelectedLocale(const nsACString& aPackage,
                                          nsACString& aLocale)
{
  PackageEntry* entry =
      static_cast<PackageEntry*>(PL_DHashTableOperate(&mPackagesHash,
                                                      & aPackage,
                                                      PL_DHASH_LOOKUP));

  if (PL_DHASH_ENTRY_IS_FREE(entry))
    return NS_ERROR_FAILURE;

  aLocale = entry->locales.GetSelected(mSelectedLocale, nsProviderArray::LOCALE);
  if (aLocale.IsEmpty())
    return NS_ERROR_FAILURE;

  return NS_OK;
}

nsresult
nsChromeRegistryChrome::SelectLocaleFromPref(nsIPrefBranch* prefs)
{
  nsresult rv;
  bool matchOSLocale = false;
  rv = prefs->GetBoolPref(MATCH_OS_LOCALE_PREF, &matchOSLocale);

  if (NS_SUCCEEDED(rv) && matchOSLocale) {
    // compute lang and region code only when needed!
    nsAutoCString uiLocale;
    rv = getUILangCountry(uiLocale);
    if (NS_SUCCEEDED(rv))
      mSelectedLocale = uiLocale;
  }
  else {
    nsXPIDLCString provider;
    rv = prefs->GetCharPref(SELECTED_LOCALE_PREF, getter_Copies(provider));
    if (NS_SUCCEEDED(rv)) {
      mSelectedLocale = provider;
    }
  }

  if (NS_FAILED(rv))
    NS_ERROR("Couldn't select locale from pref!");

  return rv;
}

NS_IMETHODIMP
nsChromeRegistryChrome::Observe(nsISupports *aSubject, const char *aTopic,
                                const PRUnichar *someData)
{
  nsresult rv = NS_OK;

  if (!strcmp(NS_PREFBRANCH_PREFCHANGE_TOPIC_ID, aTopic)) {
    nsCOMPtr<nsIPrefBranch> prefs (do_QueryInterface(aSubject));
    NS_ASSERTION(prefs, "Bad observer call!");

    NS_ConvertUTF16toUTF8 pref(someData);

    if (pref.EqualsLiteral(MATCH_OS_LOCALE_PREF) ||
        pref.EqualsLiteral(SELECTED_LOCALE_PREF)) {
        rv = UpdateSelectedLocale();
        if (NS_SUCCEEDED(rv) && mProfileLoaded)
          FlushAllCaches();
    }
    else if (pref.EqualsLiteral(SELECTED_SKIN_PREF)) {
      nsXPIDLCString provider;
      rv = prefs->GetCharPref(pref.get(), getter_Copies(provider));
      if (NS_FAILED(rv)) {
        NS_ERROR("Couldn't get new skin pref!");
        return rv;
      }

      mSelectedSkin = provider;
      RefreshSkins();
    } else {
      NS_ERROR("Unexpected pref!");
    }
  }
  else if (!strcmp("command-line-startup", aTopic)) {
    nsCOMPtr<nsICommandLine> cmdLine (do_QueryInterface(aSubject));
    if (cmdLine) {
      nsAutoString uiLocale;
      rv = cmdLine->HandleFlagWithParam(NS_LITERAL_STRING(UILOCALE_CMD_LINE_ARG),
                                        false, uiLocale);
      if (NS_SUCCEEDED(rv) && !uiLocale.IsEmpty()) {
        CopyUTF16toUTF8(uiLocale, mSelectedLocale);
        nsCOMPtr<nsIPrefBranch> prefs (do_GetService(NS_PREFSERVICE_CONTRACTID));
        if (prefs) {
          prefs->RemoveObserver(SELECTED_LOCALE_PREF, this);
        }
      }
    }
  }
  else if (!strcmp("profile-initial-state", aTopic)) {
    mProfileLoaded = true;
  }
  else {
    NS_ERROR("Unexpected observer topic!");
  }

  return rv;
}

NS_IMETHODIMP
nsChromeRegistryChrome::CheckForNewChrome()
{
  PL_DHashTableEnumerate(&mPackagesHash, RemoveAll, nullptr);
  mOverlayHash.Clear();
  mStyleHash.Clear();
  mOverrideTable.Clear();

  nsComponentManagerImpl::gComponentManager->RereadChromeManifests();
  return NS_OK;
}

nsresult nsChromeRegistryChrome::UpdateSelectedLocale()
{
  nsresult rv = NS_OK;
  nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
  if (prefs) {
    rv = SelectLocaleFromPref(prefs);
    if (NS_SUCCEEDED(rv)) {
      nsCOMPtr<nsIObserverService> obsSvc =
        mozilla::services::GetObserverService();
      NS_ASSERTION(obsSvc, "Couldn't get observer service.");
      obsSvc->NotifyObservers((nsIChromeRegistry*) this,
                              "selected-locale-has-changed", nullptr);
    }
  }

  return rv;
}

static void
SerializeURI(nsIURI* aURI,
             SerializedURI& aSerializedURI)
{
  if (!aURI)
    return;

  aURI->GetSpec(aSerializedURI.spec);
  aURI->GetOriginCharset(aSerializedURI.charset);
}

static PLDHashOperator
EnumerateOverride(nsIURI* aURIKey,
                  nsIURI* aURI,
                  void* aArg)
{
  nsTArray<OverrideMapping>* overrides =
      static_cast<nsTArray<OverrideMapping>*>(aArg);

  SerializedURI chromeURI, overrideURI;

  SerializeURI(aURIKey, chromeURI);
  SerializeURI(aURI, overrideURI);

  OverrideMapping override = {
    chromeURI, overrideURI
  };
  overrides->AppendElement(override);
  return (PLDHashOperator)PL_DHASH_NEXT;
}

struct EnumerationArgs
{
  InfallibleTArray<ChromePackage>& packages;
  const nsCString& selectedLocale;
  const nsCString& selectedSkin;
};

void
nsChromeRegistryChrome::SendRegisteredChrome(
    mozilla::dom::PContentParent* aParent)
{
  InfallibleTArray<ChromePackage> packages;
  InfallibleTArray<ResourceMapping> resources;
  InfallibleTArray<OverrideMapping> overrides;

  EnumerationArgs args = {
    packages, mSelectedLocale, mSelectedSkin
  };
  PL_DHashTableEnumerate(&mPackagesHash, CollectPackages, &args);

  nsCOMPtr<nsIIOService> io (do_GetIOService());
  NS_ENSURE_TRUE_VOID(io);

  nsCOMPtr<nsIProtocolHandler> ph;
  nsresult rv = io->GetProtocolHandler("resource", getter_AddRefs(ph));
  NS_ENSURE_SUCCESS_VOID(rv);

  //FIXME: Some substitutions are set up lazily and might not exist yet
  nsCOMPtr<nsIResProtocolHandler> irph (do_QueryInterface(ph));
  nsResProtocolHandler* rph = static_cast<nsResProtocolHandler*>(irph.get());
  rph->CollectSubstitutions(resources);

  mOverrideTable.EnumerateRead(&EnumerateOverride, &overrides);

  bool success = aParent->SendRegisterChrome(packages, resources, overrides,
                                             mSelectedLocale);
  NS_ENSURE_TRUE_VOID(success);
}

PLDHashOperator
nsChromeRegistryChrome::CollectPackages(PLDHashTable *table,
                                  PLDHashEntryHdr *entry,
                                  uint32_t number,
                                  void *arg)
{
  EnumerationArgs* args = static_cast<EnumerationArgs*>(arg);
  PackageEntry* package = static_cast<PackageEntry*>(entry);

  SerializedURI contentURI, localeURI, skinURI;

  SerializeURI(package->baseURI, contentURI);
  SerializeURI(package->locales.GetBase(args->selectedLocale,
                                        nsProviderArray::LOCALE), localeURI);
  SerializeURI(package->skins.GetBase(args->selectedSkin, nsProviderArray::ANY),
               skinURI);

  ChromePackage chromePackage = {
    package->package,
    contentURI,
    localeURI,
    skinURI,
    package->flags
  };
  args->packages.AppendElement(chromePackage);
  return (PLDHashOperator)PL_DHASH_NEXT;
}

static bool
CanLoadResource(nsIURI* aResourceURI)
{
  bool isLocalResource = false;
  (void)NS_URIChainHasFlags(aResourceURI,
                            nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
                            &isLocalResource);
  return isLocalResource;
}

nsIURI*
nsChromeRegistryChrome::GetBaseURIFromPackage(const nsCString& aPackage,
                                              const nsCString& aProvider,
                                              const nsCString& aPath)
{
  PackageEntry* entry =
      static_cast<PackageEntry*>(PL_DHashTableOperate(&mPackagesHash,
                                                      &aPackage,
                                                      PL_DHASH_LOOKUP));

  if (PL_DHASH_ENTRY_IS_FREE(entry)) {
    if (!mInitialized)
      return nullptr;

    LogMessage("No chrome package registered for chrome://%s/%s/%s",
               aPackage.get(), aProvider.get(), aPath.get());

    return nullptr;
  }

  if (aProvider.EqualsLiteral("locale")) {
    return entry->locales.GetBase(mSelectedLocale, nsProviderArray::LOCALE);
  }
  else if (aProvider.EqualsLiteral("skin")) {
    return entry->skins.GetBase(mSelectedSkin, nsProviderArray::ANY);
  }
  else if (aProvider.EqualsLiteral("content")) {
    return entry->baseURI;
  }
  return nullptr;
}

nsresult
nsChromeRegistryChrome::GetFlagsFromPackage(const nsCString& aPackage,
                                            uint32_t* aFlags)
{
  PackageEntry* entry =
      static_cast<PackageEntry*>(PL_DHashTableOperate(&mPackagesHash,
                                                      & (nsACString&) aPackage,
                                                      PL_DHASH_LOOKUP));
  if (PL_DHASH_ENTRY_IS_FREE(entry))
    return NS_ERROR_NOT_AVAILABLE;

  *aFlags = entry->flags;
  return NS_OK;
}

PLHashNumber
nsChromeRegistryChrome::HashKey(PLDHashTable *table, const void *key)
{
  const nsACString& str = *reinterpret_cast<const nsACString*>(key);
  return HashString(str);
}

bool
nsChromeRegistryChrome::MatchKey(PLDHashTable *table, const PLDHashEntryHdr *entry,
                           const void *key)
{
  const nsACString& str = *reinterpret_cast<const nsACString*>(key);
  const PackageEntry* pentry = static_cast<const PackageEntry*>(entry);
  return str.Equals(pentry->package);
}

void
nsChromeRegistryChrome::ClearEntry(PLDHashTable *table, PLDHashEntryHdr *entry)
{
  PackageEntry* pentry = static_cast<PackageEntry*>(entry);
  pentry->~PackageEntry();
}

bool
nsChromeRegistryChrome::InitEntry(PLDHashTable *table, PLDHashEntryHdr *entry,
                            const void *key)
{
  const nsACString& str = *reinterpret_cast<const nsACString*>(key);

  new (entry) PackageEntry(str);
  return true;
}

const PLDHashTableOps
nsChromeRegistryChrome::kTableOps = {
  PL_DHashAllocTable,
  PL_DHashFreeTable,
  HashKey,
  MatchKey,
  PL_DHashMoveEntryStub,
  ClearEntry,
  PL_DHashFinalizeStub,
  InitEntry
};

nsChromeRegistryChrome::ProviderEntry*
nsChromeRegistryChrome::nsProviderArray::GetProvider(const nsACString& aPreferred, MatchType aType)
{
  int32_t i = mArray.Count();
  if (!i)
    return nullptr;

  ProviderEntry* found = nullptr;  // Only set if we find a partial-match locale
  ProviderEntry* entry;

  while (i--) {
    entry = reinterpret_cast<ProviderEntry*>(mArray[i]);
    if (aPreferred.Equals(entry->provider))
      return entry;

    if (aType != LOCALE)
      continue;

    if (LanguagesMatch(aPreferred, entry->provider)) {
      found = entry;
      continue;
    }

    if (!found && entry->provider.EqualsLiteral("en-US"))
      found = entry;
  }

  if (!found && aType != EXACT)
    return entry;

  return found;
}

nsIURI*
nsChromeRegistryChrome::nsProviderArray::GetBase(const nsACString& aPreferred, MatchType aType)
{
  ProviderEntry* provider = GetProvider(aPreferred, aType);

  if (!provider)
    return nullptr;

  return provider->baseURI;
}

const nsACString&
nsChromeRegistryChrome::nsProviderArray::GetSelected(const nsACString& aPreferred, MatchType aType)
{
  ProviderEntry* entry = GetProvider(aPreferred, aType);

  if (entry)
    return entry->provider;

  return EmptyCString();
}

void
nsChromeRegistryChrome::nsProviderArray::SetBase(const nsACString& aProvider, nsIURI* aBaseURL)
{
  ProviderEntry* provider = GetProvider(aProvider, EXACT);

  if (provider) {
    provider->baseURI = aBaseURL;
    return;
  }

  // no existing entries, add a new one
  provider = new ProviderEntry(aProvider, aBaseURL);
  if (!provider)
    return; // It's safe to silently fail on OOM

  mArray.AppendElement(provider);
}

void
nsChromeRegistryChrome::nsProviderArray::EnumerateToArray(nsTArray<nsCString> *a)
{
  int32_t i = mArray.Count();
  while (i--) {
    ProviderEntry *entry = reinterpret_cast<ProviderEntry*>(mArray[i]);
    a->AppendElement(entry->provider);
  }
}

void
nsChromeRegistryChrome::nsProviderArray::Clear()
{
  int32_t i = mArray.Count();
  while (i--) {
    ProviderEntry* entry = reinterpret_cast<ProviderEntry*>(mArray[i]);
    delete entry;
  }

  mArray.Clear();
}

void
nsChromeRegistryChrome::OverlayListEntry::AddURI(nsIURI* aURI)
{
  int32_t i = mArray.Count();
  while (i--) {
    bool equals;
    if (NS_SUCCEEDED(aURI->Equals(mArray[i], &equals)) && equals)
      return;
  }

  mArray.AppendObject(aURI);
}

void
nsChromeRegistryChrome::OverlayListHash::Add(nsIURI* aBase, nsIURI* aOverlay)
{
  OverlayListEntry* entry = mTable.PutEntry(aBase);
  if (entry)
    entry->AddURI(aOverlay);
}

const nsCOMArray<nsIURI>*
nsChromeRegistryChrome::OverlayListHash::GetArray(nsIURI* aBase)
{
  OverlayListEntry* entry = mTable.GetEntry(aBase);
  if (!entry)
    return nullptr;

  return &entry->mArray;
}

#ifdef MOZ_XUL
NS_IMETHODIMP
nsChromeRegistryChrome::GetStyleOverlays(nsIURI *aChromeURL,
                                         nsISimpleEnumerator **aResult)
{
  const nsCOMArray<nsIURI>* parray = mStyleHash.GetArray(aChromeURL);
  if (!parray)
    return NS_NewEmptyEnumerator(aResult);

  return NS_NewArrayEnumerator(aResult, *parray);
}

NS_IMETHODIMP
nsChromeRegistryChrome::GetXULOverlays(nsIURI *aChromeURL,
                                       nsISimpleEnumerator **aResult)
{
  const nsCOMArray<nsIURI>* parray = mOverlayHash.GetArray(aChromeURL);
  if (!parray)
    return NS_NewEmptyEnumerator(aResult);

  return NS_NewArrayEnumerator(aResult, *parray);
}
#endif // MOZ_XUL

nsIURI*
nsChromeRegistry::ManifestProcessingContext::GetManifestURI()
{
  if (!mManifestURI) {
    nsCString uri;
    mFile.GetURIString(uri);
    NS_NewURI(getter_AddRefs(mManifestURI), uri);
  }
  return mManifestURI;
}

nsIXPConnect*
nsChromeRegistry::ManifestProcessingContext::GetXPConnect()
{
  if (!mXPConnect)
    mXPConnect = do_GetService("@mozilla.org/js/xpc/XPConnect;1");

  return mXPConnect;
}

already_AddRefed<nsIURI>
nsChromeRegistry::ManifestProcessingContext::ResolveURI(const char* uri)
{
  nsIURI* baseuri = GetManifestURI();
  if (!baseuri)
    return NULL;

  nsCOMPtr<nsIURI> resolved;
  nsresult rv = NS_NewURI(getter_AddRefs(resolved), uri, baseuri);
  if (NS_FAILED(rv))
    return NULL;

  return resolved.forget();
}

static void
EnsureLowerCase(char *aBuf)
{
  for (; *aBuf; ++aBuf) {
    char ch = *aBuf;
    if (ch >= 'A' && ch <= 'Z')
      *aBuf = ch + 'a' - 'A';
  }
}

void
nsChromeRegistryChrome::ManifestContent(ManifestProcessingContext& cx, int lineno,
                                        char *const * argv, bool platform,
                                        bool contentaccessible)
{
  char* package = argv[0];
  char* uri = argv[1];

  EnsureLowerCase(package);

  nsCOMPtr<nsIURI> resolved = cx.ResolveURI(uri);
  if (!resolved) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "During chrome registration, unable to create URI '%s'.", uri);
    return;
  }

  if (!CanLoadResource(resolved)) {
    LogMessageWithContext(resolved, lineno, nsIScriptError::warningFlag,
                          "During chrome registration, cannot register non-local URI '%s' as content.",
                          uri);
    return;
  }

  PackageEntry* entry =
    static_cast<PackageEntry*>(PL_DHashTableOperate(&mPackagesHash,
                                                    & (const nsACString&) nsDependentCString(package),
                                                    PL_DHASH_ADD));
  if (!entry)
    return;

  entry->baseURI = resolved;

  if (platform)
    entry->flags |= PLATFORM_PACKAGE;
  if (contentaccessible)
    entry->flags |= CONTENT_ACCESSIBLE;
}

void
nsChromeRegistryChrome::ManifestLocale(ManifestProcessingContext& cx, int lineno,
                                       char *const * argv, bool platform,
                                       bool contentaccessible)
{
  char* package = argv[0];
  char* provider = argv[1];
  char* uri = argv[2];

  EnsureLowerCase(package);

  nsCOMPtr<nsIURI> resolved = cx.ResolveURI(uri);
  if (!resolved) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "During chrome registration, unable to create URI '%s'.", uri);
    return;
  }

  if (!CanLoadResource(resolved)) {
    LogMessageWithContext(resolved, lineno, nsIScriptError::warningFlag,
                          "During chrome registration, cannot register non-local URI '%s' as content.",
                          uri);
    return;
  }

  PackageEntry* entry =
    static_cast<PackageEntry*>(PL_DHashTableOperate(&mPackagesHash,
                                                    & (const nsACString&) nsDependentCString(package),
                                                    PL_DHASH_ADD));
  if (!entry)
    return;

  entry->locales.SetBase(nsDependentCString(provider), resolved);
}

void
nsChromeRegistryChrome::ManifestSkin(ManifestProcessingContext& cx, int lineno,
                                     char *const * argv, bool platform,
                                     bool contentaccessible)
{
  char* package = argv[0];
  char* provider = argv[1];
  char* uri = argv[2];

  EnsureLowerCase(package);

  nsCOMPtr<nsIURI> resolved = cx.ResolveURI(uri);
  if (!resolved) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "During chrome registration, unable to create URI '%s'.", uri);
    return;
  }

  if (!CanLoadResource(resolved)) {
    LogMessageWithContext(resolved, lineno, nsIScriptError::warningFlag,
                          "During chrome registration, cannot register non-local URI '%s' as content.",
                          uri);
    return;
  }

  PackageEntry* entry =
    static_cast<PackageEntry*>(PL_DHashTableOperate(&mPackagesHash,
                                                    & (const nsACString&) nsDependentCString(package),
                                                    PL_DHASH_ADD));
  if (!entry)
    return;

  entry->skins.SetBase(nsDependentCString(provider), resolved);
}

void
nsChromeRegistryChrome::ManifestOverlay(ManifestProcessingContext& cx, int lineno,
                                        char *const * argv, bool platform,
                                        bool contentaccessible)
{
  char* base = argv[0];
  char* overlay = argv[1];

  nsCOMPtr<nsIURI> baseuri = cx.ResolveURI(base);
  nsCOMPtr<nsIURI> overlayuri = cx.ResolveURI(overlay);
  if (!baseuri || !overlayuri) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "During chrome registration, unable to create URI.");
    return;
  }

  if (!CanLoadResource(overlayuri)) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "Cannot register non-local URI '%s' as an overlay.", overlay);
    return;
  }

  mOverlayHash.Add(baseuri, overlayuri);
}

void
nsChromeRegistryChrome::ManifestStyle(ManifestProcessingContext& cx, int lineno,
                                      char *const * argv, bool platform,
                                      bool contentaccessible)
{
  char* base = argv[0];
  char* overlay = argv[1];

  nsCOMPtr<nsIURI> baseuri = cx.ResolveURI(base);
  nsCOMPtr<nsIURI> overlayuri = cx.ResolveURI(overlay);
  if (!baseuri || !overlayuri) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "During chrome registration, unable to create URI.");
    return;
  }

  if (!CanLoadResource(overlayuri)) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "Cannot register non-local URI '%s' as a style overlay.", overlay);
    return;
  }

  mStyleHash.Add(baseuri, overlayuri);
}

void
nsChromeRegistryChrome::ManifestOverride(ManifestProcessingContext& cx, int lineno,
                                         char *const * argv, bool platform,
                                         bool contentaccessible)
{
  char* chrome = argv[0];
  char* resolved = argv[1];

  nsCOMPtr<nsIURI> chromeuri = cx.ResolveURI(chrome);
  nsCOMPtr<nsIURI> resolveduri = cx.ResolveURI(resolved);
  if (!chromeuri || !resolveduri) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "During chrome registration, unable to create URI.");
    return;
  }

  if (!CanLoadResource(resolveduri)) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "Cannot register non-local URI '%s' for an override.", resolved);
    return;
  }
  mOverrideTable.Put(chromeuri, resolveduri);
}

void
nsChromeRegistryChrome::ManifestResource(ManifestProcessingContext& cx, int lineno,
                                         char *const * argv, bool platform,
                                         bool contentaccessible)
{
  char* package = argv[0];
  char* uri = argv[1];

  EnsureLowerCase(package);
  nsDependentCString host(package);

  nsCOMPtr<nsIIOService> io = mozilla::services::GetIOService();
  if (!io) {
    NS_WARNING("No IO service trying to process chrome manifests");
    return;
  }

  nsCOMPtr<nsIProtocolHandler> ph;
  nsresult rv = io->GetProtocolHandler("resource", getter_AddRefs(ph));
  if (NS_FAILED(rv))
    return;

  nsCOMPtr<nsIResProtocolHandler> rph = do_QueryInterface(ph);

  bool exists = false;
  rv = rph->HasSubstitution(host, &exists);
  if (exists) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "Duplicate resource declaration for '%s' ignored.", package);
    return;
  }

  nsCOMPtr<nsIURI> resolved = cx.ResolveURI(uri);
  if (!resolved) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "During chrome registration, unable to create URI '%s'.", uri);
    return;
  }

  if (!CanLoadResource(resolved)) {
    LogMessageWithContext(cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
                          "Warning: cannot register non-local URI '%s' as a resource.",
                          uri);
    return;
  }

  rph->SetSubstitution(host, resolved);
}


text:
Übersetzen Sie die folgenden Sätze auf Schweizerdeutsch.

Wenn Sie die Schweizerdeutsche Version sehen wollen, klicken Sie darauf.

1

Das
ist ein Tisch.

Das
isch en Tisch.

2

Der
Tisch ist alt.

De
Tisch isch alt.

3

Das
ist ein Buch.

Das
isch es Buech.

4

Das
Buch ist dick.

S
Buech isch dick.

5

Das
ist eine CD.

Das
isch e CD.

6

Die CD
ist neu.

D CD
isch neu.

7

Wir
sprechen Französisch.

Mir
reded Französisch.

8

Marco
hat ein Wörterbuch.

De
Marco hät es Wörterbuech.

9

Lily
spricht sehr gut Portugiesisch.

D Lily
redet sehr guet Portugiesisch.

10

Ich habe
ein paar Bücher.

Ich ha-n-es
paar Büecher.

11

Sie
müssen viel Englisch üben.

Sie
müend viel Englisch üebe.

12

Das
sind Übungsbücher.

Das
sind Üebigsbüecher.

13

Ich spreche
ein bisschen Polnisch.

Ich rede-n-es
bitzli Polnisch.

14

Ihr
sprecht nicht gut Italienisch.

Ihr
reded nöd guet Italienisch.

15

Habt ihr
auch CDs?

Händ ihr
au CDs?


text:
require 'rubygems'
require 'secret_mail'
require 'secret_mail/../../db/create_tables'
require 'fileutils'

config = YAML::load(File.open("config/config.yaml"))

db_file = config["db"]["database"]
file_exist = false
if File.exists?(db_file)
   puts "Db already exists"
   file_exist = true
   exit
end

SecretMail::MailAction.mail_domain config["secret_mail"]["mail_domain"]
ActiveRecord::Base.establish_connection(config["db"])
ActiveRecord::Base.connection

CreateTables.up
domain = SecretMail::MailAction.mail_domain

SecretMail::MailAction.new({
	:secret_mail => "blogger@#{domain}",
	:action => "create",
	:params => "mail_to_blogger"
}).save

SecretMail::MailAction.new({
	:secret_mail => "wordpress@#{domain}",
	:action => "create",
	:params => "mail_to_wordpress"
}).save

SecretMail::MailAction.new({
	:secret_mail => "posterous@#{domain}",
	:action => "create",
	:params => "mail_to_wordpress"
}).save

SecretMail::MailAction.new({
        :secret_mail => config["test"]["secret_mail"],
	:action => "mail_to_wordpress",
        :from => config["test"]["mail_from"],
	:params => config["test"]["mail_to"]
}).save


text:
using HtmlAgilityPack;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RazorGenerator.Testing;

namespace RazorGeneratorMvc5.Tests
{
    [TestClass]
    public class ViewsTests
    {
        [TestMethod]
        public void TestIndexView()
        {
            // Instantiate the view directly. This is made possible by
            // the fact that we precompiled it
            var view = new RazorGeneratorMvc5.Views.Home.Index();

            // Set up the data that needs to be accessed by the view
            view.ViewBag.Message = "Testing";

            // Render it in an HtmlAgilityPack HtmlDocument. Note that
            // you can pass a 'model' object here if your view needs one.
            // Generally, what you do here is similar to how a controller
            //action sets up data for its view.
            HtmlDocument doc = view.RenderAsHtml();

            // Use the HtmlAgilityPack object model to verify the view.
            // Here, we simply check that the first <h2> tag contains
            // what we put in view.ViewBag.Message
            HtmlNode node = doc.DocumentNode.Element("h2");
            Assert.AreEqual("Testing", node.InnerHtml.Trim());
        }

        [TestMethod]
        public void TestAccountLoginView()
        {
            var view = new RazorGeneratorMvc5.Views.Account.Login();

            // This blows up...
            HtmlDocument doc = view.RenderAsHtml();
        }
    }
}


text:
#include "variance.h"
#include "onyx_int.h"

SADFunction *vp8_sad16x16;
SADFunction *vp8_sad16x8;
SADFunction *vp8_sad8x16;
SADFunction *vp8_sad8x8;
SADFunction *vp8_sad4x4;

variance_function *vp8_variance4x4;
variance_function *vp8_variance8x8;
variance_function *vp8_variance8x16;
variance_function *vp8_variance16x8;
variance_function *vp8_variance16x16;

variance_function *vp8_mse16x16;

sub_pixel_variance_function *vp8_sub_pixel_variance4x4;
sub_pixel_variance_function *vp8_sub_pixel_variance8x8;
sub_pixel_variance_function *vp8_sub_pixel_variance8x16;
sub_pixel_variance_function *vp8_sub_pixel_variance16x8;
sub_pixel_variance_function *vp8_sub_pixel_variance16x16;

int (*vp8_block_error)(short *coeff, short *dqcoeff);
int (*vp8_mbblock_error)(MACROBLOCK *mb, int dc);

int (*vp8_mbuverror)(MACROBLOCK *mb);
unsigned int (*vp8_get_mb_ss)(short *);
void (*vp8_short_fdct4x4)(short *input, short *output, int pitch);
void (*vp8_short_fdct8x4)(short *input, short *output, int pitch);
void (*vp8_fast_fdct4x4)(short *input, short *output, int pitch);
void (*vp8_fast_fdct8x4)(short *input, short *output, int pitch);
void (*short_walsh4x4)(short *input, short *output, int pitch);

void (*vp8_subtract_b)(BLOCK *be, BLOCKD *bd, int pitch);
void (*vp8_subtract_mby)(short *diff, unsigned char *src, unsigned char *pred, int stride);
void (*vp8_subtract_mbuv)(short *diff, unsigned char *usrc, unsigned char *vsrc, unsigned char *pred, int stride);
void (*vp8_fast_quantize_b)(BLOCK *b, BLOCKD *d);

unsigned int (*vp8_get16x16pred_error)(unsigned char *src_ptr, int src_stride, unsigned char *ref_ptr, int ref_stride);
unsigned int (*vp8_get8x8var)(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride, unsigned int *SSE, int *Sum);
unsigned int (*vp8_get16x16var)(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride, unsigned int *SSE, int *Sum);
unsigned int (*vp8_get4x4sse_cs)(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride);

// c imports
extern int block_error_c(short *coeff, short *dqcoeff);
extern int vp8_mbblock_error_c(MACROBLOCK *mb, int dc);

extern int vp8_mbuverror_c(MACROBLOCK *mb);
extern unsigned int vp8_get8x8var_c(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride, unsigned int *SSE, int *Sum);
extern void short_fdct4x4_c(short *input, short *output, int pitch);
extern void short_fdct8x4_c(short *input, short *output, int pitch);
extern void vp8_short_walsh4x4_c(short *input, short *output, int pitch);

extern void vp8_subtract_b_c(BLOCK *be, BLOCKD *bd, int pitch);
extern void subtract_mby_c(short *diff, unsigned char *src, unsigned char *pred, int stride);
extern void subtract_mbuv_c(short *diff, unsigned char *usrc, unsigned char *vsrc, unsigned char *pred, int stride);
extern void vp8_fast_quantize_b_c(BLOCK *b, BLOCKD *d);

extern SADFunction sad16x16_c;
extern SADFunction sad16x8_c;
extern SADFunction sad8x16_c;
extern SADFunction sad8x8_c;
extern SADFunction sad4x4_c;

extern variance_function variance16x16_c;
extern variance_function variance8x16_c;
extern variance_function variance16x8_c;
extern variance_function variance8x8_c;
extern variance_function variance4x4_c;
extern variance_function mse16x16_c;

extern sub_pixel_variance_function sub_pixel_variance4x4_c;
extern sub_pixel_variance_function sub_pixel_variance8x8_c;
extern sub_pixel_variance_function sub_pixel_variance8x16_c;
extern sub_pixel_variance_function sub_pixel_variance16x8_c;
extern sub_pixel_variance_function sub_pixel_variance16x16_c;

extern unsigned int vp8_get_mb_ss_c(short *);
extern unsigned int vp8_get16x16pred_error_c(unsigned char *src_ptr, int src_stride, unsigned char *ref_ptr, int ref_stride);
extern unsigned int vp8_get8x8var_c(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride, unsigned int *SSE, int *Sum);
extern unsigned int vp8_get16x16var_c(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride, unsigned int *SSE, int *Sum);
extern unsigned int vp8_get4x4sse_cs_c(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride);

// ppc
extern int vp8_block_error_ppc(short *coeff, short *dqcoeff);

extern void vp8_short_fdct4x4_ppc(short *input, short *output, int pitch);
extern void vp8_short_fdct8x4_ppc(short *input, short *output, int pitch);

extern void vp8_subtract_mby_ppc(short *diff, unsigned char *src, unsigned char *pred, int stride);
extern void vp8_subtract_mbuv_ppc(short *diff, unsigned char *usrc, unsigned char *vsrc, unsigned char *pred, int stride);

extern SADFunction vp8_sad16x16_ppc;
extern SADFunction vp8_sad16x8_ppc;
extern SADFunction vp8_sad8x16_ppc;
extern SADFunction vp8_sad8x8_ppc;
extern SADFunction vp8_sad4x4_ppc;

extern variance_function vp8_variance16x16_ppc;
extern variance_function vp8_variance8x16_ppc;
extern variance_function vp8_variance16x8_ppc;
extern variance_function vp8_variance8x8_ppc;
extern variance_function vp8_variance4x4_ppc;
extern variance_function vp8_mse16x16_ppc;

extern sub_pixel_variance_function vp8_sub_pixel_variance4x4_ppc;
extern sub_pixel_variance_function vp8_sub_pixel_variance8x8_ppc;
extern sub_pixel_variance_function vp8_sub_pixel_variance8x16_ppc;
extern sub_pixel_variance_function vp8_sub_pixel_variance16x8_ppc;
extern sub_pixel_variance_function vp8_sub_pixel_variance16x16_ppc;

extern unsigned int vp8_get8x8var_ppc(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride, unsigned int *SSE, int *Sum);
extern unsigned int vp8_get16x16var_ppc(unsigned char *src_ptr, int  source_stride, unsigned char *ref_ptr, int  recon_stride, unsigned int *SSE, int *Sum);

void vp8_cmachine_specific_config(void)
{
    // Pure C:
    vp8_mbuverror               = vp8_mbuverror_c;
    vp8_fast_quantize_b           = vp8_fast_quantize_b_c;
    vp8_short_fdct4x4            = vp8_short_fdct4x4_ppc;
    vp8_short_fdct8x4            = vp8_short_fdct8x4_ppc;
    vp8_fast_fdct4x4             = vp8_short_fdct4x4_ppc;
    vp8_fast_fdct8x4             = vp8_short_fdct8x4_ppc;
    short_walsh4x4               = vp8_short_walsh4x4_c;

    vp8_variance4x4             = vp8_variance4x4_ppc;
    vp8_variance8x8             = vp8_variance8x8_ppc;
    vp8_variance8x16            = vp8_variance8x16_ppc;
    vp8_variance16x8            = vp8_variance16x8_ppc;
    vp8_variance16x16           = vp8_variance16x16_ppc;
    vp8_mse16x16                = vp8_mse16x16_ppc;

    vp8_sub_pixel_variance4x4     = vp8_sub_pixel_variance4x4_ppc;
    vp8_sub_pixel_variance8x8     = vp8_sub_pixel_variance8x8_ppc;
    vp8_sub_pixel_variance8x16    = vp8_sub_pixel_variance8x16_ppc;
    vp8_sub_pixel_variance16x8    = vp8_sub_pixel_variance16x8_ppc;
    vp8_sub_pixel_variance16x16   = vp8_sub_pixel_variance16x16_ppc;

    vp8_get_mb_ss                 = vp8_get_mb_ss_c;
    vp8_get16x16pred_error       = vp8_get16x16pred_error_c;
    vp8_get8x8var               = vp8_get8x8var_ppc;
    vp8_get16x16var             = vp8_get16x16var_ppc;
    vp8_get4x4sse_cs            = vp8_get4x4sse_cs_c;

    vp8_sad16x16                = vp8_sad16x16_ppc;
    vp8_sad16x8                 = vp8_sad16x8_ppc;
    vp8_sad8x16                 = vp8_sad8x16_ppc;
    vp8_sad8x8                  = vp8_sad8x8_ppc;
    vp8_sad4x4                  = vp8_sad4x4_ppc;

    vp8_block_error              = vp8_block_error_ppc;
    vp8_mbblock_error            = vp8_mbblock_error_c;

    vp8_subtract_b               = vp8_subtract_b_c;
    vp8_subtract_mby             = vp8_subtract_mby_ppc;
    vp8_subtract_mbuv            = vp8_subtract_mbuv_ppc;
}


text:
// HTMLParser Library v0.7 - A java-based parser for HTML
// Copyright (C) Dec 31, 2000 Somik Raha
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// For any questions or suggestions, you can write to me at :
// Email :somik@kizna.com
//
// Postal Address :
// Somik Raha
// R&D Team
// Kizna Corporation
// 2-1-17-6F, Sakamoto Bldg., Moto Azabu, Minato ku, Tokyo, 106 0046, JAPAN

package com.liyo.html;

// HTMLParser Library v0.82 - A java-based parser for HTML
// Copyright (C) Dec 31, 2000 Somik Raha
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// For any questions or suggestions, you can write to me at :
// Email :somik@kizna.com
//
// Postal Address :
// Somik Raha
// R&D Team
// Kizna Corporation
// 2-1-17-6F, Sakamoto Bldg., Moto Azabu, Minato ku, Tokyo, 106 0046, JAPAN

/**
 * Normal text in the html document is identified and represented by this class.
 */
public class HTMLStringNode implements HTMLNode {
	/**
     * The text of the string.
     */
    protected String text;
    /**
     * The beginning position of the tag in the line
     */
    protected int textBegin;
    /**
     * The ending position of the tag in the line
     */
    protected int textEnd;

    /**
     * Constructor takes in the text string, beginning and ending posns.
     *
     * @param text The contents of the string line
     * @param textBegin The beginning position of the string
     * @param textEnd The ending positiong of the string
     */
    public HTMLStringNode(String text, int textBegin, int textEnd) {
        this.text = text;
        this.textBegin = textBegin;
        this.textEnd = textEnd;
    }

    /**
     * Returns the beginning position of the string.
     */
    public int elementBegin() {
        return textBegin;
    }

    /**
     * Returns the ending position fo the tag
     */
    public int elementEnd() {
        return textEnd;
    }

    /**
     * Returns the text of the string line
     */
    public String getText() {
        return text;
    }

    /**
     * Locate the remark tag withing the input string, by parsing from the given position
     *
     * @param reader HTML reader to be provided so as to allow reading of next line
     * @param input Input String
     * @param position Position to start parsing from
     */
    public static HTMLNode find(HTMLReader reader, String input, int position) {
        String text = "";
        int state = 0;
        int textBegin = position;
        int textEnd = position;
        for (int i = position; (i < input.length() && state != 2); i++) {
            // When the input has ended but no text is found, we end up returning null
            if (input.charAt(i) == '<' && state == 0) {
                return null;
            }
            if (input.charAt(i) == '<') {
                state = 2;
                textEnd = i - 1;
            }
            if (state == 0) {
                if (input.charAt(i) != ' ') state = 1;
            }
            if (state == 1) {
                text += input.charAt(i);
            }
            if (state == 1 && i == input.length() - 1) {
                state = 2;
                textEnd = i;
            }
        }
		if (textBegin <= textEnd) {
			return new HTMLStringNode(text, textBegin, textEnd);
		} else {
			return null;
		}
    }

    /**
     * Print the contents of the string line.
     */
    public void print() {
        System.out.println("Text = " + text + "; begins at : " + elementBegin() + "; ends at : " + elementEnd());
    }

}


text:
package org.springframework.security.web.firewall;

import static org.junit.Assert.fail;

import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

/**
 * @author Luke Taylor
 */
public class DefaultHttpFirewallTests {
    public String[] unnormalizedPaths = {
            "/..",
            "/./path/",
            "/path/path/.",
            "/path/path//.",
            "./path/../path//.",
            "./path",
            ".//path",
            "."
    };

    @Test
    public void unnormalizedPathsAreRejected() throws Exception {
        DefaultHttpFirewall fw = new DefaultHttpFirewall();

        MockHttpServletRequest request;
        for (String path : unnormalizedPaths) {
            request = new MockHttpServletRequest();
            request.setServletPath(path);
            try {
                fw.getFirewalledRequest(request);
                fail(path + " is un-normalized");
            } catch (RequestRejectedException expected) {
            }
            request.setPathInfo(path);
            try {
                fw.getFirewalledRequest(request);
                fail(path + " is un-normalized");
            } catch (RequestRejectedException expected) {
            }
        }
    }
}


text:
import { Component } from '@angular/core';

import ImagesService from './images.service';
import ImageEditComponent from './image-edit.component';
import LoginService from './login.service';

import template from './images.template.html';

@Component({
  // directives: [ImageEditComponent],
  selector: 'images',
  template,
})
export default class ImagesComponent {
  constructor(imagesService: ImagesService, loginService: LoginService) {
    this.imagesService = imagesService;
    this.loginService = loginService;
  }

  fetchImages() {
    this.imagesService.getImages().subscribe(images => { this.images = images; });
  }

  ngOnInit() {
    this.fetchImages();
  }

  onSelect(image) {
    this.selectedImage = image;
  }

  onNew() {
    this.selectedImage = {
      title: 'New image',
      text: 'Insert text here.',
    };
  }

  onRefresh() {
    this.fetchImages();
  }
}


text:
"use strict";

exports.__esModule = true;

var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _trimEnd = require("lodash/trimEnd");

var _trimEnd2 = _interopRequireDefault(_trimEnd);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var SPACES_RE = /^[ \t]+$/;

var Buffer = function () {
  function Buffer(map) {
    (0, _classCallCheck3.default)(this, Buffer);
    this._map = null;
    this._buf = [];
    this._last = "";
    this._queue = [];
    this._position = {
      line: 1,
      column: 0
    };
    this._sourcePosition = {
      identifierName: null,
      line: null,
      column: null,
      filename: null
    };

    this._map = map;
  }

  Buffer.prototype.get = function get() {
    this._flush();

    var map = this._map;
    var result = {
      code: (0, _trimEnd2.default)(this._buf.join("")),
      map: null,
      rawMappings: map && map.getRawMappings()
    };

    if (map) {
      Object.defineProperty(result, "map", {
        configurable: true,
        enumerable: true,
        get: function get() {
          return this.map = map.get();
        },
        set: function set(value) {
          Object.defineProperty(this, "map", { value: value, writable: true });
        }
      });
    }

    return result;
  };

  Buffer.prototype.append = function append(str) {
    this._flush();
    var _sourcePosition = this._sourcePosition,
        line = _sourcePosition.line,
        column = _sourcePosition.column,
        filename = _sourcePosition.filename,
        identifierName = _sourcePosition.identifierName;

    this._append(str, line, column, identifierName, filename);
  };

  Buffer.prototype.queue = function queue(str) {
    if (str === "\n") while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) {
      this._queue.shift();
    }var _sourcePosition2 = this._sourcePosition,
        line = _sourcePosition2.line,
        column = _sourcePosition2.column,
        filename = _sourcePosition2.filename,
        identifierName = _sourcePosition2.identifierName;

    this._queue.unshift([str, line, column, identifierName, filename]);
  };

  Buffer.prototype._flush = function _flush() {
    var item = void 0;
    while (item = this._queue.pop()) {
      this._append.apply(this, item);
    }
  };

  Buffer.prototype._append = function _append(str, line, column, identifierName, filename) {
    if (this._map && str[0] !== "\n") {
      this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename);
    }

    this._buf.push(str);
    this._last = str[str.length - 1];

    for (var i = 0; i < str.length; i++) {
      if (str[i] === "\n") {
        this._position.line++;
        this._position.column = 0;
      } else {
        this._position.column++;
      }
    }
  };

  Buffer.prototype.removeTrailingNewline = function removeTrailingNewline() {
    if (this._queue.length > 0 && this._queue[0][0] === "\n") this._queue.shift();
  };

  Buffer.prototype.removeLastSemicolon = function removeLastSemicolon() {
    if (this._queue.length > 0 && this._queue[0][0] === ";") this._queue.shift();
  };

  Buffer.prototype.endsWith = function endsWith(suffix) {
    if (suffix.length === 1) {
      var last = void 0;
      if (this._queue.length > 0) {
        var str = this._queue[0][0];
        last = str[str.length - 1];
      } else {
        last = this._last;
      }

      return last === suffix;
    }

    var end = this._last + this._queue.reduce(function (acc, item) {
      return item[0] + acc;
    }, "");
    if (suffix.length <= end.length) {
      return end.slice(-suffix.length) === suffix;
    }

    return false;
  };

  Buffer.prototype.hasContent = function hasContent() {
    return this._queue.length > 0 || !!this._last;
  };

  Buffer.prototype.source = function source(prop, loc) {
    if (prop && !loc) return;

    var pos = loc ? loc[prop] : null;

    this._sourcePosition.identifierName = loc && loc.identifierName || null;
    this._sourcePosition.line = pos ? pos.line : null;
    this._sourcePosition.column = pos ? pos.column : null;
    this._sourcePosition.filename = loc && loc.filename || null;
  };

  Buffer.prototype.withSource = function withSource(prop, loc, cb) {
    if (!this._map) return cb();

    var originalLine = this._sourcePosition.line;
    var originalColumn = this._sourcePosition.column;
    var originalFilename = this._sourcePosition.filename;
    var originalIdentifierName = this._sourcePosition.identifierName;

    this.source(prop, loc);

    cb();

    this._sourcePosition.line = originalLine;
    this._sourcePosition.column = originalColumn;
    this._sourcePosition.filename = originalFilename;
    this._sourcePosition.identifierName = originalIdentifierName;
  };

  Buffer.prototype.getCurrentColumn = function getCurrentColumn() {
    var extra = this._queue.reduce(function (acc, item) {
      return item[0] + acc;
    }, "");
    var lastIndex = extra.lastIndexOf("\n");

    return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex;
  };

  Buffer.prototype.getCurrentLine = function getCurrentLine() {
    var extra = this._queue.reduce(function (acc, item) {
      return item[0] + acc;
    }, "");

    var count = 0;
    for (var i = 0; i < extra.length; i++) {
      if (extra[i] === "\n") count++;
    }

    return this._position.line + count;
  };

  return Buffer;
}();

exports.default = Buffer;
module.exports = exports["default"];


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RestaurantManager.Models
{
    public class Class1
    {
    }
}


text:
Chat

          <form ng-submit="sendMessage();">
            <fieldset class="row">

                <input type="text" id="messageText" name="messageText" class="form-control" ng-model="messageText" placeholder="Enter new message">

                  <button type="submit" class="btn btn-primary" ng-disabled="!messageText.length">Submit</button>

            </fieldset>
          </form>

News Feed

              <button id="single-button" type="button" class="btn btn-primary" dropdown-toggle ng-disabled="disabled">
                {{feedDefault}}
              </button>

                  {{feed.title}}

          <input type="text" class="form-control" id="inputFeedURL" autocomplete="off" placeholder="Enter Feed URL" data-ng-model="feedSrc" />

              <button id="single-button"
                      type="button"
                      ng-disabled="!feedSrc.length"
                      class="btn btn-primary"
                      ng-click="loadFeed(feedSrc, $event, 'Custom');">
                Go
              </button>

{{feed.title}}

{{feed.contentSnippet}}

              {{feed.publishedDate}}


text:
[![Build Status](https://travis-ci.org/ivanStraltsou/code-wars.svg?branch=master)](https://travis-ci.org/ivanStraltsou/code-wars)
Function sequence invocation
================

Implement `sequence` function to flatten the execution stack

Example:

```javascript
add(1, 3); // 4
multiply(2, 4); // 8
concat('Hello ', 'Code Wars!'); // Hello Code Wars!
log('result'); // logs `result`

// sequence invocation example
log(concat(add(multiply(5, 8), 2), ' is the answer')) === sequence(add, multiply, concat, log)(5, 8)(2)(' is the answer')()
```


text:
@implementation RXPrisonBreak

+ (void)prisonBreakCheck {
    if([self prisonBreak]) {
        //越狱 设备
        [UserDefaults setObject:@"1" forKey:prisonBreakDefault];
    }
    else {
        //没有 越狱
        [UserDefaults setObject:@"0" forKey:prisonBreakDefault];
    }
    [UserDefaults synchronize];
}

+ (BOOL)prisonBreak {

    if([self isJailBreakOne]) {
        return YES;
    }

    if([self isJailBreakTwo]) {
        return YES;
    }

    if([self isJailBreakThree]) {
        return YES;
    }

    if([self isJailbroken]) {
        return YES;
    }

    return NO;
}

#pragma mark - ~~~~~~~~~~~ 1. 判定常见的越狱文件 ~~~~~~~~~~~~~~~
+ (BOOL)isJailBreakOne {
    NSArray * tool_pathes = @[@"/Applications/Cydia.app",
                              @"/Library/MobileSubstrate/MobileSubstrate.dylib",
                              @"/bin/bash",
                              @"/usr/sbin/sshd",
                              @"/etc/apt"];

    for(int i=0; i< tool_pathes.count; i++) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:tool_pathes[i]]) {
//             RXLog(@"The device is jail broken!");
            return YES;
        }
    }
//     RXLog(@"The device is NOT jail broken!");
    return NO;
}

#pragma mark - ~~~~~~~~~~~ 2. 判断cydia的URL scheme ~~~~~~~~~~~~~~~

+ (BOOL)isJailBreakTwo {
    if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://"]]) {
//         RXLog(@"The device is jail broken!");
        return YES;
    }
//     RXLog(@"The device is NOT jail broken!");
    return NO;
}

#pragma mark - ~~~~~~~~~~~ 3. 读取系统所有应用的名称 ~~~~~~~~~~~~~~~
+ (BOOL)isJailBreakThree {
    if([[NSFileManager defaultManager] fileExistsAtPath:USER_APP_PATH]) {
//         RXLog(@"The device is jail broken!");
        NSArray *applist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:USER_APP_PATH error:nil];
//         RXLog(@"applist = %@", applist);
        return YES;
    }
     RXLog(@"The device is NOT jail broken!");
    return NO;
}

#pragma mark - ~~~~~~~~~~~ 4. 使用stat方法来判定cydia是否存在 ~~~~~~~~~~~~~~~

//int checkInject()
//{
//    int ret;
//    Dl_info dylib_info;
//    int (*func_stat)(const char*, struct stat*) = stat;
//
//    if ((ret = dladdr(func_stat, &dylib_info)) && strncmp(dylib_info.dli_fname, dylib_name, strlen(dylib_name))) {
//        return 0;
//    }
//    return 1;
//}
//
//int checkCydia()
//{
//    // first ,check whether library is inject
//    struct stat stat_info;
//
//    if (!checkInject()) {
//        if (0 == stat(CYDIA_APP_PATH, &stat_info)) {
//            return 1;
//        }
//    } else {
//        return 1;
//    }
//    return 0;
//}
//
//+ (BOOL)isJailBreakFour
//{
//    if (checkCydia()) {
////         RXLog(@"The device is jail broken!");
//        return YES;
//    }
////     RXLog(@"The device is NOT jail broken!");
//    return NO;
//}

#pragma mark - ~~~~~~~~~~~ 5. 读取环境变量 ~~~~~~~~~~~~~~~
//char* printEnv(void)
//{
//    charchar *env = getenv("DYLD_INSERT_LIBRARIES");
//     RXLog(@"%s", env);
//    return env;
//}
//
//+ (BOOL)isJailBreakFive
//{
//    if (printEnv()) {
////         RXLog(@"The device is jail broken!");
//        return YES;
//    }
////     RXLog(@"The device is NOT jail broken!");
//    return NO;
//}

#pragma mark - ~~~~~~~~~~~ 6 ~~~~~~~~~~~~~~~
+ (BOOL)isJailbroken {
    BOOL jailbroken = NO;
    NSString *cydiaPath = @"/Applications/Cydia.app";
    NSString *aptPath = @"/private/var/lib/apt/";

    if ([[NSFileManager defaultManager] fileExistsAtPath:cydiaPath]) {
        jailbroken = YES;
    }

    if ([[NSFileManager defaultManager] fileExistsAtPath:aptPath]) {
        jailbroken = YES;
    }

    return jailbroken;

}

@end


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Management.WebSites.Models;
using System;
using System.Management.Automation;
using System.Text.RegularExpressions;

namespace Microsoft.Azure.Commands.WebApps.Validations
{
    public class ValidateServerFarmAttribute : ValidateArgumentsAttribute
    {
        protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
        {
            var serverFarm = arguments as ServerFarmWithRichSku;
            if (serverFarm == null)
            {
                throw new ValidationMetadataException("Argument 'ServerFarm' must be of type Microsoft.Azure.Management.WebSites.Models.ServerFarmWithRichSku");
            }

            ValidateSku(serverFarm.Sku);
        }

        private void ValidateSku(SkuDescription sku)
        {
            if (sku == null)
            {
                throw new ValidationMetadataException("Argument 'ServerFarm.SKU' cannot be null");
            }

            const string skuNamePattern = "^[fdbspFDBSP][1-9]$";
            if (!Regex.IsMatch(sku.Name, skuNamePattern))
            {
                throw new ValidationMetadataException("Argument 'ServerFarm.SKU.Name' must conform to format first letter of sku name and numerical value of worker size. Worker Size [Small = 1, Medium = 2, Large = 3, ExtraLarge = 4] For instance, F1 means free small workers, P3 means premium large workers. ");
            }

            const string tierPattern = "^(Free|Shared|Basic|Standard|Premium)$";
            if (!Regex.IsMatch(sku.Tier, tierPattern, RegexOptions.IgnoreCase))
            {
                throw new ValidationMetadataException("Argument 'ServerFarm.SKU.Tier' must be one of Free|Shared|Basic|Standard|Premium");
            }

            var firstLetter = string.Equals("Shared", sku.Tier, StringComparison.OrdinalIgnoreCase) ? 'D' : sku.Tier[0];
            if (char.ToUpperInvariant(firstLetter) != char.ToUpperInvariant(sku.Name[0]))
            {
                throw new ValidationMetadataException(string.Format("Arguments 'ServerFarm.SKU.Name' and 'ServerFarm.SKU.Tier' must point to the same tier. [F = Free, D = Shared, B = Basic, S = Standard, P = Premium]. Current values: SKU.Name = {0}, SKU.Tier = {1}", sku.Name, sku.Tier));
            }
        }

        public override string ToString()
        {
            return "[ValidateServerFarm]";
        }
    }
}


text:
package seedu.address.logic.parser;

import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_ADDRESS;
import static seedu.address.logic.parser.CliSyntax.PREFIX_EMAIL;
import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME;
import static seedu.address.logic.parser.CliSyntax.PREFIX_PHONE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG;

import java.util.Set;
import java.util.stream.Stream;

import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.person.Address;
import seedu.address.model.person.Email;
import seedu.address.model.person.Name;
import seedu.address.model.person.Person;
import seedu.address.model.person.Phone;
import seedu.address.model.person.ReadOnlyPerson;
import seedu.address.model.tag.Tag;

/**
 * Parses input arguments and creates a new AddCommand object
 */
public class AddCommandParser implements Parser<AddCommand> {

    /**
     * Parses the given {@code String} of arguments in the context of the AddCommand
     * and returns an AddCommand object for execution.
     * @throws ParseException if the user input does not conform the expected format
     */
    public AddCommand parse(String args) throws ParseException {
        ArgumentMultimap argMultimap =
                ArgumentTokenizer.tokenize(args, PREFIX_NAME, PREFIX_PHONE, PREFIX_EMAIL, PREFIX_ADDRESS, PREFIX_TAG);

        if (!arePrefixesPresent(argMultimap, PREFIX_NAME, PREFIX_ADDRESS, PREFIX_PHONE, PREFIX_EMAIL)
                || !argMultimap.getPreamble().isEmpty()) {
            throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
        }

        try {
            Name name = ParserUtil.parseName(argMultimap.getValue(PREFIX_NAME)).get();
            Phone phone = ParserUtil.parsePhone(argMultimap.getValue(PREFIX_PHONE)).get();
            Email email = ParserUtil.parseEmail(argMultimap.getValue(PREFIX_EMAIL)).get();
            Address address = ParserUtil.parseAddress(argMultimap.getValue(PREFIX_ADDRESS)).get();
            Set<Tag> tagList = ParserUtil.parseTags(argMultimap.getAllValues(PREFIX_TAG));

            ReadOnlyPerson person = new Person(name, phone, email, address, tagList);

            return new AddCommand(person);
        } catch (IllegalValueException ive) {
            throw new ParseException(ive.getMessage(), ive);
        }
    }

    /**
     * Returns true if none of the prefixes contains empty {@code Optional} values in the given
     * {@code ArgumentMultimap}.
     */
    private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) {
        return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent());
    }

}