text:
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * 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/Util.h"

#if defined(MOZ_WIDGET_GTK2)
#include "gfxPlatformGtk.h"
#define gfxToolkitPlatform gfxPlatformGtk
#elif defined(MOZ_WIDGET_QT)
#include <qfontinfo.h>
#include "gfxQtPlatform.h"
#define gfxToolkitPlatform gfxQtPlatform
#elif defined(XP_WIN)
#include "gfxWindowsPlatform.h"
#define gfxToolkitPlatform gfxWindowsPlatform
#elif defined(ANDROID)
#include "mozilla/dom/ContentChild.h"
#include "gfxAndroidPlatform.h"
#include "mozilla/Omnijar.h"
#include "nsIInputStream.h"
#include "nsNetUtil.h"
#define gfxToolkitPlatform gfxAndroidPlatform
#endif

#ifdef ANDROID
#include "nsXULAppAPI.h"
#include <dirent.h>
#include <android/log.h>
#define ALOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gecko" , ## args)
#endif

#include "ft2build.h"
#include FT_FREETYPE_H
#include FT_TRUETYPE_TAGS_H
#include FT_TRUETYPE_TABLES_H
#include "cairo-ft.h"

#include "gfxFT2FontList.h"
#include "gfxFT2Fonts.h"
#include "gfxUserFontSet.h"
#include "gfxFontUtils.h"

#include "nsServiceManagerUtils.h"
#include "nsTArray.h"
#include "nsUnicharUtils.h"

#include "nsDirectoryServiceUtils.h"
#include "nsDirectoryServiceDefs.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsISimpleEnumerator.h"

#include "mozilla/scache/StartupCache.h"
#include <sys/stat.h>

#ifdef XP_WIN
#include "nsIWindowsRegKey.h"
#include <windows.h>
#endif

using namespace mozilla;

#ifdef PR_LOGGING
static PRLogModuleInfo *gFontInfoLog = PR_NewLogModule("fontInfoLog");
#endif /* PR_LOGGING */

#undef LOG
#define LOG(args) PR_LOG(gFontInfoLog, PR_LOG_DEBUG, args)
#define LOG_ENABLED() PR_LOG_TEST(gFontInfoLog, PR_LOG_DEBUG)

static __inline void
BuildKeyNameFromFontName(nsAString &aName)
{
#ifdef XP_WIN
    if (aName.Length() >= LF_FACESIZE)
        aName.Truncate(LF_FACESIZE - 1);
#endif
    ToLowerCase(aName);
}

/*
 * FT2FontEntry
 * gfxFontEntry subclass corresponding to a specific face that can be
 * rendered by freetype. This is associated with a face index in a
 * file (normally a .ttf/.otf file holding a single face, but in principle
 * there could be .ttc files with multiple faces).
 * The FT2FontEntry can create the necessary FT_Face on demand, and can
 * then create a Cairo font_face and scaled_font for drawing.
 */

cairo_scaled_font_t *
FT2FontEntry::CreateScaledFont(const gfxFontStyle *aStyle)
{
    cairo_font_face_t *cairoFace = CairoFontFace();
    if (!cairoFace) {
        return nullptr;
    }

    cairo_scaled_font_t *scaledFont = nullptr;

    cairo_matrix_t sizeMatrix;
    cairo_matrix_t identityMatrix;

    // XXX deal with adjusted size
    cairo_matrix_init_scale(&sizeMatrix, aStyle->size, aStyle->size);
    cairo_matrix_init_identity(&identityMatrix);

    // synthetic oblique by skewing via the font matrix
    bool needsOblique = !IsItalic() &&
            (aStyle->style & (NS_FONT_STYLE_ITALIC | NS_FONT_STYLE_OBLIQUE));

    if (needsOblique) {
        const double kSkewFactor = 0.25;

        cairo_matrix_t style;
        cairo_matrix_init(&style,
                          1,                //xx
                          0,                //yx
                          -1 * kSkewFactor,  //xy
                          1,                //yy
                          0,                //x0
                          0);               //y0
        cairo_matrix_multiply(&sizeMatrix, &sizeMatrix, &style);
    }

    cairo_font_options_t *fontOptions = cairo_font_options_create();

    if (gfxPlatform::GetPlatform()->RequiresLinearZoom()) {
        cairo_font_options_set_hint_metrics(fontOptions, CAIRO_HINT_METRICS_OFF);
    }

    scaledFont = cairo_scaled_font_create(cairoFace,
                                          &sizeMatrix,
                                          &identityMatrix, fontOptions);
    cairo_font_options_destroy(fontOptions);

    NS_ASSERTION(cairo_scaled_font_status(scaledFont) == CAIRO_STATUS_SUCCESS,
                 "Failed to make scaled font");

    return scaledFont;
}

FT2FontEntry::~FT2FontEntry()
{
    // Do nothing for mFTFace here since FTFontDestroyFunc is called by cairo.
    mFTFace = nullptr;

#ifndef ANDROID
    if (mFontFace) {
        cairo_font_face_destroy(mFontFace);
        mFontFace = nullptr;
    }
#endif
}

gfxFont*
FT2FontEntry::CreateFontInstance(const gfxFontStyle *aFontStyle, bool aNeedsBold)
{
    cairo_scaled_font_t *scaledFont = CreateScaledFont(aFontStyle);
    if (!scaledFont) {
        return nullptr;
    }
    gfxFont *font = new gfxFT2Font(scaledFont, this, aFontStyle, aNeedsBold);
    cairo_scaled_font_destroy(scaledFont);
    return font;
}

/* static */
FT2FontEntry*
FT2FontEntry::CreateFontEntry(const gfxProxyFontEntry &aProxyEntry,
                              const uint8_t *aFontData,
                              uint32_t aLength)
{
    // Ownership of aFontData is passed in here; the fontEntry must
    // retain it as long as the FT_Face needs it, and ensure it is
    // eventually deleted.
    FT_Face face;
    FT_Error error =
        FT_New_Memory_Face(gfxToolkitPlatform::GetPlatform()->GetFTLibrary(),
                           aFontData, aLength, 0, &face);
    if (error != FT_Err_Ok) {
        NS_Free((void*)aFontData);
        return nullptr;
    }
    if (FT_Err_Ok != FT_Select_Charmap(face, FT_ENCODING_UNICODE)) {
        FT_Done_Face(face);
        NS_Free((void*)aFontData);
        return nullptr;
    }
    // Create our FT2FontEntry, which inherits the name of the proxy
    // as it's not guaranteed that the face has valid names (bug 737315)
    FT2FontEntry* fe =
        FT2FontEntry::CreateFontEntry(face, nullptr, 0, aProxyEntry.Name(),
                                      aFontData);
    if (fe) {
        fe->mItalic = aProxyEntry.mItalic;
        fe->mWeight = aProxyEntry.mWeight;
        fe->mStretch = aProxyEntry.mStretch;
    }
    return fe;
}

class FTUserFontData {
public:
    FTUserFontData(FT_Face aFace, const uint8_t* aData)
        : mFace(aFace), mFontData(aData)
    {
    }

    ~FTUserFontData()
    {
        FT_Done_Face(mFace);
        if (mFontData) {
            NS_Free((void*)mFontData);
        }
    }

private:
    FT_Face        mFace;
    const uint8_t *mFontData;
};

static void
FTFontDestroyFunc(void *data)
{
    FTUserFontData *userFontData = static_cast<FTUserFontData*>(data);
    delete userFontData;
}

/* static */
FT2FontEntry*
FT2FontEntry::CreateFontEntry(const FontListEntry& aFLE)
{
    FT2FontEntry *fe = new FT2FontEntry(aFLE.faceName());
    fe->mFilename = aFLE.filepath();
    fe->mFTFontIndex = aFLE.index();
    fe->mWeight = aFLE.weight();
    fe->mStretch = aFLE.stretch();
    fe->mItalic = aFLE.italic();
    return fe;
}

/* static */
FT2FontEntry*
FT2FontEntry::CreateFontEntry(FT_Face aFace,
                              const char* aFilename, uint8_t aIndex,
                              const nsAString& aName,
                              const uint8_t *aFontData)
{
    static cairo_user_data_key_t key;

    FT2FontEntry *fe = new FT2FontEntry(aName);
    fe->mItalic = aFace->style_flags & FT_STYLE_FLAG_ITALIC;
    fe->mFTFace = aFace;
    int flags = gfxPlatform::GetPlatform()->FontHintingEnabled() ?
                FT_LOAD_DEFAULT :
                (FT_LOAD_NO_AUTOHINT | FT_LOAD_NO_HINTING);
    fe->mFontFace = cairo_ft_font_face_create_for_ft_face(aFace, flags);
    fe->mFilename = aFilename;
    fe->mFTFontIndex = aIndex;
    FTUserFontData *userFontData = new FTUserFontData(aFace, aFontData);
    cairo_font_face_set_user_data(fe->mFontFace, &key,
                                  userFontData, FTFontDestroyFunc);

    TT_OS2 *os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(aFace, ft_sfnt_os2));
    uint16_t os2weight = 0;
    if (os2 && os2->version != 0xffff) {
        // Technically, only 100 to 900 are valid, but some fonts
        // have this set wrong -- e.g. "Microsoft Logo Bold Italic" has
        // it set to 6 instead of 600.  We try to be nice and handle that
        // as well.
        if (os2->usWeightClass >= 100 && os2->usWeightClass <= 900)
            os2weight = os2->usWeightClass;
        else if (os2->usWeightClass >= 1 && os2->usWeightClass <= 9)
            os2weight = os2->usWeightClass * 100;
    }

    if (os2weight != 0)
        fe->mWeight = os2weight;
    else if (aFace->style_flags & FT_STYLE_FLAG_BOLD)
        fe->mWeight = 700;
    else
        fe->mWeight = 400;

    NS_ASSERTION(fe->mWeight >= 100 && fe->mWeight <= 900, "Invalid final weight in font!");

    return fe;
}

// construct font entry name for an installed font from names in the FT_Face,
// and then create our FT2FontEntry
static FT2FontEntry*
CreateNamedFontEntry(FT_Face aFace, const char* aFilename, uint8_t aIndex)
{
    if (!aFace->family_name) {
        return nullptr;
    }
    nsAutoString fontName;
    AppendUTF8toUTF16(aFace->family_name, fontName);
    if (aFace->style_name && strcmp("Regular", aFace->style_name)) {
        fontName.AppendLiteral(" ");
        AppendUTF8toUTF16(aFace->style_name, fontName);
    }
    return FT2FontEntry::CreateFontEntry(aFace, aFilename, aIndex, fontName);
}

FT2FontEntry*
gfxFT2Font::GetFontEntry()
{
    return static_cast<FT2FontEntry*> (mFontEntry.get());
}

cairo_font_face_t *
FT2FontEntry::CairoFontFace()
{
    static cairo_user_data_key_t key;

    if (!mFontFace) {
        FT_Face face;
        if (FT_Err_Ok != FT_New_Face(gfxToolkitPlatform::GetPlatform()->GetFTLibrary(),
                                     mFilename.get(), mFTFontIndex, &face)) {
            NS_WARNING("failed to create freetype face");
            return nullptr;
        }
        if (FT_Err_Ok != FT_Select_Charmap(face, FT_ENCODING_UNICODE)) {
            NS_WARNING("failed to select Unicode charmap, text may be garbled");
        }
        mFTFace = face;
        int flags = gfxPlatform::GetPlatform()->FontHintingEnabled() ?
                    FT_LOAD_DEFAULT :
                    (FT_LOAD_NO_AUTOHINT | FT_LOAD_NO_HINTING);
        mFontFace = cairo_ft_font_face_create_for_ft_face(face, flags);
        FTUserFontData *userFontData = new FTUserFontData(face, nullptr);
        cairo_font_face_set_user_data(mFontFace, &key,
                                      userFontData, FTFontDestroyFunc);
    }
    return mFontFace;
}

nsresult
FT2FontEntry::ReadCMAP()
{
    if (mCharacterMap) {
        return NS_OK;
    }

    nsRefPtr<gfxCharacterMap> charmap = new gfxCharacterMap();

    AutoFallibleTArray<uint8_t,16384> buffer;
    nsresult rv = GetFontTable(TTAG_cmap, buffer);

    if (NS_SUCCEEDED(rv)) {
        bool unicodeFont;
        bool symbolFont;
        rv = gfxFontUtils::ReadCMAP(buffer.Elements(), buffer.Length(),
                                    *charmap, mUVSOffset,
                                    unicodeFont, symbolFont);
    }

    mHasCmapTable = NS_SUCCEEDED(rv);
    if (mHasCmapTable) {
        gfxPlatformFontList *pfl = gfxPlatformFontList::PlatformFontList();
        mCharacterMap = pfl->FindCharMap(charmap);
    } else {
        // if error occurred, initialize to null cmap
        mCharacterMap = new gfxCharacterMap();
    }
    return rv;
}

nsresult
FT2FontEntry::GetFontTable(uint32_t aTableTag,
                           FallibleTArray<uint8_t>& aBuffer)
{
    // Ensure existence of mFTFace
    CairoFontFace();
    NS_ENSURE_TRUE(mFTFace, NS_ERROR_FAILURE);

    FT_Error status;
    FT_ULong len = 0;
    status = FT_Load_Sfnt_Table(mFTFace, aTableTag, 0, nullptr, &len);
    if (status != FT_Err_Ok || len == 0) {
        return NS_ERROR_FAILURE;
    }

    if (!aBuffer.SetLength(len)) {
        return NS_ERROR_OUT_OF_MEMORY;
    }
    uint8_t *buf = aBuffer.Elements();
    status = FT_Load_Sfnt_Table(mFTFace, aTableTag, 0, buf, &len);
    NS_ENSURE_TRUE(status == FT_Err_Ok, NS_ERROR_FAILURE);

    return NS_OK;
}

void
FT2FontEntry::SizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf,
                                  FontListSizes*    aSizes) const
{
    gfxFontEntry::SizeOfExcludingThis(aMallocSizeOf, aSizes);
    aSizes->mFontListSize +=
        mFilename.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
}

void
FT2FontEntry::SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf,
                                  FontListSizes*    aSizes) const
{
    aSizes->mFontListSize += aMallocSizeOf(this);
    SizeOfExcludingThis(aMallocSizeOf, aSizes);
}

/*
 * FT2FontFamily
 * A standard gfxFontFamily; just adds a method used to support sending
 * the font list from chrome to content via IPC.
 */

void
FT2FontFamily::AddFacesToFontList(InfallibleTArray<FontListEntry>* aFontList)
{
    for (int i = 0, n = mAvailableFonts.Length(); i < n; ++i) {
        const FT2FontEntry *fe =
            static_cast<const FT2FontEntry*>(mAvailableFonts[i].get());
        if (!fe) {
            continue;
        }

        aFontList->AppendElement(FontListEntry(Name(), fe->Name(),
                                               fe->mFilename,
                                               fe->Weight(), fe->Stretch(),
                                               fe->IsItalic(),
                                               fe->mFTFontIndex));
    }
}

/*
 * Startup cache support for the font list:
 * We store the list of families and faces, with their style attributes and the
 * corresponding font files, in the startup cache.
 * This allows us to recreate the gfxFT2FontList collection of families and
 * faces without instantiating Freetype faces for each font file (in order to
 * find their attributes), leading to significantly quicker startup.
 */

#define CACHE_KEY "font.cached-list"

class FontNameCache {
public:
    FontNameCache()
        : mWriteNeeded(false)
    {
        mOps = (PLDHashTableOps) {
            PL_DHashAllocTable,
            PL_DHashFreeTable,
            StringHash,
            HashMatchEntry,
            MoveEntry,
            PL_DHashClearEntryStub,
            PL_DHashFinalizeStub,
            NULL
        };

        if (!PL_DHashTableInit(&mMap, &mOps, nullptr,
                               sizeof(FNCMapEntry), 0))
        {
            mMap.ops = nullptr;
            LOG(("initializing the map failed"));
        }

        NS_ABORT_IF_FALSE(XRE_GetProcessType() == GeckoProcessType_Default,
                          "StartupCacheFontNameCache should only be used in chrome process");
        mCache = mozilla::scache::StartupCache::GetSingleton();

        Init();
    }

    ~FontNameCache()
    {
        if (!mMap.ops) {
            return;
        }
        if (!mWriteNeeded || !mCache) {
            PL_DHashTableFinish(&mMap);
            return;
        }

        nsAutoCString buf;
        PL_DHashTableEnumerate(&mMap, WriteOutMap, &buf);
        PL_DHashTableFinish(&mMap);
        mCache->PutBuffer(CACHE_KEY, buf.get(), buf.Length() + 1);
    }

    void Init()
    {
        if (!mMap.ops || !mCache) {
            return;
        }
        uint32_t size;
        char* buf;
        if (NS_FAILED(mCache->GetBuffer(CACHE_KEY, &buf, &size))) {
            return;
        }

        LOG(("got: %s from the cache", nsDependentCString(buf, size).get()));

        const char* beginning = buf;
        const char* end = strchr(beginning, ';');
        while (end) {
            nsCString filename(beginning, end - beginning);
            beginning = end + 1;
            if (!(end = strchr(beginning, ';'))) {
                break;
            }
            nsCString faceList(beginning, end - beginning);
            beginning = end + 1;
            if (!(end = strchr(beginning, ';'))) {
                break;
            }
            uint32_t timestamp = strtoul(beginning, NULL, 10);
            beginning = end + 1;
            if (!(end = strchr(beginning, ';'))) {
                break;
            }
            uint32_t filesize = strtoul(beginning, NULL, 10);

            FNCMapEntry* mapEntry =
                static_cast<FNCMapEntry*>
                (PL_DHashTableOperate(&mMap, filename.get(), PL_DHASH_ADD));
            if (mapEntry) {
                mapEntry->mFilename.Assign(filename);
                mapEntry->mTimestamp = timestamp;
                mapEntry->mFilesize = filesize;
                mapEntry->mFaces.Assign(faceList);
                // entries from the startupcache are marked "non-existing"
                // until we have confirmed that the file still exists
                mapEntry->mFileExists = false;
            }

            beginning = end + 1;
            end = strchr(beginning, ';');
        }

        // Should we use free() or delete[] here? See bug 684700.
        free(buf);
    }

    virtual void
    GetInfoForFile(nsCString& aFileName, nsCString& aFaceList,
                   uint32_t *aTimestamp, uint32_t *aFilesize)
    {
        if (!mMap.ops) {
            return;
        }
        PLDHashEntryHdr *hdr =
            PL_DHashTableOperate(&mMap, aFileName.get(), PL_DHASH_LOOKUP);
        if (!hdr) {
            return;
        }
        FNCMapEntry* entry = static_cast<FNCMapEntry*>(hdr);
        if (entry && entry->mTimestamp && entry->mFilesize) {
            *aTimestamp = entry->mTimestamp;
            *aFilesize = entry->mFilesize;
            aFaceList.Assign(entry->mFaces);
            // this entry does correspond to an existing file
            // (although it might not be up-to-date, in which case
            // it will get overwritten via CacheFileInfo)
            entry->mFileExists = true;
        }
    }

    virtual void
    CacheFileInfo(nsCString& aFileName, nsCString& aFaceList,
                  uint32_t aTimestamp, uint32_t aFilesize)
    {
        if (!mMap.ops) {
            return;
        }
        FNCMapEntry* entry =
            static_cast<FNCMapEntry*>
            (PL_DHashTableOperate(&mMap, aFileName.get(), PL_DHASH_ADD));
        if (entry) {
            entry->mFilename.Assign(aFileName);
            entry->mTimestamp = aTimestamp;
            entry->mFilesize = aFilesize;
            entry->mFaces.Assign(aFaceList);
            entry->mFileExists = true;
        }
        mWriteNeeded = true;
    }

private:
    mozilla::scache::StartupCache* mCache;
    PLDHashTable mMap;
    bool mWriteNeeded;

    PLDHashTableOps mOps;

    static PLDHashOperator WriteOutMap(PLDHashTable *aTable,
                                       PLDHashEntryHdr *aHdr,
                                       uint32_t aNumber, void *aData)
    {
        FNCMapEntry* entry = static_cast<FNCMapEntry*>(aHdr);
        if (!entry->mFileExists) {
            // skip writing entries for files that are no longer present
            return PL_DHASH_NEXT;
        }

        nsAutoCString* buf = reinterpret_cast<nsAutoCString*>(aData);
        buf->Append(entry->mFilename);
        buf->Append(';');
        buf->Append(entry->mFaces);
        buf->Append(';');
        buf->AppendInt(entry->mTimestamp);
        buf->Append(';');
        buf->AppendInt(entry->mFilesize);
        buf->Append(';');
        return PL_DHASH_NEXT;
    }

    typedef struct : public PLDHashEntryHdr {
    public:
        nsCString mFilename;
        uint32_t  mTimestamp;
        uint32_t  mFilesize;
        nsCString mFaces;
        bool      mFileExists;
    } FNCMapEntry;

    static PLDHashNumber StringHash(PLDHashTable *table, const void *key)
    {
        return HashString(reinterpret_cast<const char*>(key));
    }

    static bool HashMatchEntry(PLDHashTable *table,
                                 const PLDHashEntryHdr *aHdr, const void *key)
    {
        const FNCMapEntry* entry =
            static_cast<const FNCMapEntry*>(aHdr);
        return entry->mFilename.Equals(reinterpret_cast<const char*>(key));
    }

    static void MoveEntry(PLDHashTable *table, const PLDHashEntryHdr *aFrom,
                          PLDHashEntryHdr *aTo)
    {
        FNCMapEntry* to = static_cast<FNCMapEntry*>(aTo);
        const FNCMapEntry* from = static_cast<const FNCMapEntry*>(aFrom);
        to->mFilename.Assign(from->mFilename);
        to->mTimestamp = from->mTimestamp;
        to->mFilesize = from->mFilesize;
        to->mFaces.Assign(from->mFaces);
        to->mFileExists = from->mFileExists;
    }
};

/***************************************************************
 *
 * gfxFT2FontList
 *
 */

// For Mobile, we use gfxFT2Fonts, and we build the font list by directly
// scanning the system's Fonts directory for OpenType and TrueType files.

gfxFT2FontList::gfxFT2FontList()
{
}

void
gfxFT2FontList::AppendFacesFromCachedFaceList(nsCString& aFileName,
                                              bool aStdFile,
                                              nsCString& aFaceList)
{
    const char *beginning = aFaceList.get();
    const char *end = strchr(beginning, ',');
    while (end) {
        nsString familyName =
            NS_ConvertUTF8toUTF16(beginning, end - beginning);
        ToLowerCase(familyName);
        beginning = end + 1;
        if (!(end = strchr(beginning, ','))) {
            break;
        }
        nsString faceName =
            NS_ConvertUTF8toUTF16(beginning, end - beginning);
        beginning = end + 1;
        if (!(end = strchr(beginning, ','))) {
            break;
        }
        uint32_t index = strtoul(beginning, NULL, 10);
        beginning = end + 1;
        if (!(end = strchr(beginning, ','))) {
            break;
        }
        bool italic = (*beginning != '0');
        beginning = end + 1;
        if (!(end = strchr(beginning, ','))) {
            break;
        }
        uint32_t weight = strtoul(beginning, NULL, 10);
        beginning = end + 1;
        if (!(end = strchr(beginning, ','))) {
            break;
        }
        int32_t stretch = strtol(beginning, NULL, 10);

        FontListEntry fle(familyName, faceName, aFileName,
                          weight, stretch, italic, index);
        AppendFaceFromFontListEntry(fle, aStdFile);

        beginning = end + 1;
        end = strchr(beginning, ',');
    }
}

static void
AppendToFaceList(nsCString& aFaceList,
                 nsAString& aFamilyName, FT2FontEntry* aFontEntry)
{
    aFaceList.Append(NS_ConvertUTF16toUTF8(aFamilyName));
    aFaceList.Append(',');
    aFaceList.Append(NS_ConvertUTF16toUTF8(aFontEntry->Name()));
    aFaceList.Append(',');
    aFaceList.AppendInt(aFontEntry->mFTFontIndex);
    aFaceList.Append(',');
    aFaceList.Append(aFontEntry->IsItalic() ? '1' : '0');
    aFaceList.Append(',');
    aFaceList.AppendInt(aFontEntry->Weight());
    aFaceList.Append(',');
    aFaceList.AppendInt(aFontEntry->Stretch());
    aFaceList.Append(',');
}

void
FT2FontEntry::CheckForBrokenFont()
{
    NS_ASSERTION(mFamily != nullptr, "font entry must belong to a family");

    // note if the family is in the "bad underline" blacklist
    if (mFamily->IsBadUnderlineFamily()) {
        mIsBadUnderlineFont = true;
    }

    // bug 721719 - set the IgnoreGSUB flag on entries for Roboto
    // because of unwanted on-by-default "ae" ligature.
    // (See also AppendFaceFromFontListEntry.)
    if (mFamily->Name().EqualsLiteral("roboto")) {
        mIgnoreGSUB = true;
    }

    // bug 706888 - set the IgnoreGSUB flag on the broken version of
    // Droid Sans Arabic from certain phones, as identified by the
    // font checksum in the 'head' table
    else if (mFamily->Name().EqualsLiteral("droid sans arabic")) {
        const TT_Header *head = static_cast<const TT_Header*>
            (FT_Get_Sfnt_Table(mFTFace, ft_sfnt_head));
        if (head && head->CheckSum_Adjust == 0xe445242) {
            mIgnoreGSUB = true;
        }
    }
}

void
gfxFT2FontList::AppendFacesFromFontFile(nsCString& aFileName,
                                        bool aStdFile,
                                        FontNameCache *aCache)
{
    nsCString faceList;
    uint32_t filesize = 0, timestamp = 0;
    if (aCache) {
        aCache->GetInfoForFile(aFileName, faceList, &timestamp, &filesize);
    }

    struct stat s;
    int statRetval = stat(aFileName.get(), &s);
    if (!faceList.IsEmpty() && 0 == statRetval &&
        s.st_mtime == timestamp && s.st_size == filesize)
    {
        LOG(("using cached font info for %s", aFileName.get()));
        AppendFacesFromCachedFaceList(aFileName, aStdFile, faceList);
        return;
    }

#ifdef XP_WIN
    FT_Library ftLibrary = gfxWindowsPlatform::GetPlatform()->GetFTLibrary();
#elif defined(ANDROID)
    FT_Library ftLibrary = gfxAndroidPlatform::GetPlatform()->GetFTLibrary();
#endif
    FT_Face dummy;
    if (FT_Err_Ok == FT_New_Face(ftLibrary, aFileName.get(), -1, &dummy)) {
        LOG(("reading font info via FreeType for %s", aFileName.get()));
        nsCString faceList;
        timestamp = s.st_mtime;
        filesize = s.st_size;
        for (FT_Long i = 0; i < dummy->num_faces; i++) {
            FT_Face face;
            if (FT_Err_Ok != FT_New_Face(ftLibrary, aFileName.get(), i, &face)) {
                continue;
            }
            if (FT_Err_Ok != FT_Select_Charmap(face, FT_ENCODING_UNICODE)) {
                FT_Done_Face(face);
                continue;
            }
            FT2FontEntry* fe =
                CreateNamedFontEntry(face, aFileName.get(), i);
            if (fe) {
                NS_ConvertUTF8toUTF16 name(face->family_name);
                BuildKeyNameFromFontName(name);
                gfxFontFamily *family = mFontFamilies.GetWeak(name);
                if (!family) {
                    family = new FT2FontFamily(name);
                    mFontFamilies.Put(name, family);
                    if (mBadUnderlineFamilyNames.Contains(name)) {
                        family->SetBadUnderlineFamily();
                    }
                }
                fe->mStandardFace = aStdFile;
                family->AddFontEntry(fe);

                // this depends on the entry having been added to its family
                fe->CheckForBrokenFont();

                AppendToFaceList(faceList, name, fe);
#ifdef PR_LOGGING
                if (LOG_ENABLED()) {
                    LOG(("(fontinit) added (%s) to family (%s)"
                         " with style: %s weight: %d stretch: %d",
                         NS_ConvertUTF16toUTF8(fe->Name()).get(),
                         NS_ConvertUTF16toUTF8(family->Name()).get(),
                         fe->IsItalic() ? "italic" : "normal",
                         fe->Weight(), fe->Stretch()));
                }
#endif
            }
        }
        FT_Done_Face(dummy);
        if (aCache && 0 == statRetval && !faceList.IsEmpty()) {
            aCache->CacheFileInfo(aFileName, faceList, timestamp, filesize);
        }
    }
}

// Called on each family after all fonts are added to the list;
// this will sort faces to give priority to "standard" font files
// if aUserArg is non-null (i.e. we're using it as a boolean flag)
static PLDHashOperator
FinalizeFamilyMemberList(nsStringHashKey::KeyType aKey,
                         nsRefPtr<gfxFontFamily>& aFamily,
                         void* aUserArg)
{
    gfxFontFamily *family = aFamily.get();
    bool sortFaces = (aUserArg != nullptr);

    family->SetHasStyles(true);

    if (sortFaces) {
        family->SortAvailableFonts();
    }
    family->CheckForSimpleFamily();

    return PL_DHASH_NEXT;
}

#ifdef ANDROID

#define JAR_READ_BUFFER_SIZE 1024

nsresult
CopyFromUriToFile(nsCString aSpec, nsIFile* aLocalFile)
{
    nsCOMPtr<nsIURI> uri;
    nsCOMPtr<nsIInputStream> inputStream;
    nsresult rv = NS_NewURI(getter_AddRefs(uri), aSpec);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = NS_OpenURI(getter_AddRefs(inputStream), uri);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIOutputStream> outputStream;
    rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), aLocalFile);
    NS_ENSURE_SUCCESS(rv, rv);

    char buf[JAR_READ_BUFFER_SIZE];
    while (true) {
        uint32_t read;
        uint32_t written;

        rv = inputStream->Read(buf, JAR_READ_BUFFER_SIZE, &read);
        NS_ENSURE_SUCCESS(rv, rv);

        rv = outputStream->Write(buf, read, &written);
        NS_ENSURE_SUCCESS(rv, rv);

        if (written != read) {
            return NS_ERROR_FAILURE;
        }

        if (read != JAR_READ_BUFFER_SIZE) {
            break;
        }
    }
    return NS_OK;
}

#define JAR_LAST_MODIFED_TIME "jar-last-modified-time"

void ExtractFontsFromJar(nsIFile* aLocalDir)
{
    bool exists;
    bool allFontsExtracted = true;
    nsCString jarPath;
    int64_t jarModifiedTime;
    uint32_t longSize;
    char* cachedModifiedTimeBuf;
    nsZipFind* find;

    nsRefPtr<nsZipArchive> reader = Omnijar::GetReader(Omnijar::Type::GRE);
    nsCOMPtr<nsIFile> jarFile = Omnijar::GetPath(Omnijar::Type::GRE);

    Omnijar::GetURIString(Omnijar::Type::GRE, jarPath);
    jarFile->GetLastModifiedTime(&jarModifiedTime);

    mozilla::scache::StartupCache* cache = mozilla::scache::StartupCache::GetSingleton();
    if (cache && NS_SUCCEEDED(cache->GetBuffer(JAR_LAST_MODIFED_TIME, &cachedModifiedTimeBuf, &longSize))
        && longSize == sizeof(int64_t)) {
        if (jarModifiedTime < *((int64_t*) cachedModifiedTimeBuf)) {
            return;
        }
    }

    aLocalDir->Exists(&exists);
    if (!exists) {
        aLocalDir->Create(nsIFile::DIRECTORY_TYPE, 0700);
    }

    static const char* sJarSearchPaths[] = {
        "res/fonts/*.ttf$",
    };

    for (int i = 0; i < ArrayLength(sJarSearchPaths); i++) {
        reader->FindInit(sJarSearchPaths[i], &find);
        while (true) {
            const char* tmpPath;
            uint16_t len;
            find->FindNext(&tmpPath, &len);
            if (!tmpPath) {
                break;
            }

            nsCString path(tmpPath, len);
            nsCOMPtr<nsIFile> localFile (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID));
            if (NS_FAILED(localFile->InitWithFile(aLocalDir))) {
                allFontsExtracted = false;
                continue;
            }

            int32_t lastSlash = path.RFindChar('/');
            nsCString fileName;
            if (lastSlash == kNotFound) {
                fileName = path;
            } else {
                fileName = Substring(path, lastSlash + 1);
            }
            if (NS_FAILED(localFile->AppendNative(fileName))) {
                allFontsExtracted = false;
                continue;
            }
            int64_t lastModifiedTime;
            localFile->Exists(&exists);
            localFile->GetLastModifiedTime(&lastModifiedTime);
            if (!exists || lastModifiedTime < jarModifiedTime) {
                nsCString spec;
                spec.Append(jarPath);
                spec.Append(path);
                if (NS_FAILED(CopyFromUriToFile(spec, localFile))) {
                    localFile->Remove(true);
                    allFontsExtracted = false;
                }
            }
        }
    }
    if (allFontsExtracted && cache) {
        cache->PutBuffer(JAR_LAST_MODIFED_TIME, (char*)&jarModifiedTime, sizeof(int64_t));
    }
}

#endif

void
gfxFT2FontList::FindFonts()
{
#ifdef XP_WIN
    nsTArray<nsString> searchPaths(3);
    nsTArray<nsString> fontPatterns(3);
    fontPatterns.AppendElement(NS_LITERAL_STRING("\\*.ttf"));
    fontPatterns.AppendElement(NS_LITERAL_STRING("\\*.ttc"));
    fontPatterns.AppendElement(NS_LITERAL_STRING("\\*.otf"));
    wchar_t pathBuf[256];
    SHGetSpecialFolderPathW(0, pathBuf, CSIDL_WINDOWS, 0);
    searchPaths.AppendElement(pathBuf);
    SHGetSpecialFolderPathW(0, pathBuf, CSIDL_FONTS, 0);
    searchPaths.AppendElement(pathBuf);
    nsCOMPtr<nsIFile> resDir;
    NS_GetSpecialDirectory(NS_APP_RES_DIR, getter_AddRefs(resDir));
    if (resDir) {
        resDir->Append(NS_LITERAL_STRING("fonts"));
        nsAutoString resPath;
        resDir->GetPath(resPath);
        searchPaths.AppendElement(resPath);
    }
    WIN32_FIND_DATAW results;
    for (uint32_t i = 0;  i < searchPaths.Length(); i++) {
        const nsString& path(searchPaths[i]);
        for (uint32_t j = 0; j < fontPatterns.Length(); j++) {
            nsAutoString pattern(path);
            pattern.Append(fontPatterns[j]);
            HANDLE handle = FindFirstFileExW(pattern.get(),
                                             FindExInfoStandard,
                                             &results,
                                             FindExSearchNameMatch,
                                             NULL,
                                             0);
            bool moreFiles = handle != INVALID_HANDLE_VALUE;
            while (moreFiles) {
                nsAutoString filePath(path);
                filePath.AppendLiteral("\\");
                filePath.Append(results.cFileName);
                AppendFacesFromFontFile(NS_ConvertUTF16toUTF8(filePath));
                moreFiles = FindNextFile(handle, &results);
            }
            if (handle != INVALID_HANDLE_VALUE)
                FindClose(handle);
        }
    }
#elif defined(ANDROID)
    gfxFontCache *fc = gfxFontCache::GetCache();
    if (fc)
        fc->AgeAllGenerations();
    mPrefFonts.Clear();
    mCodepointsWithNoFonts.reset();

    mCodepointsWithNoFonts.SetRange(0,0x1f);     // C0 controls
    mCodepointsWithNoFonts.SetRange(0x7f,0x9f);  // C1 controls

    if (XRE_GetProcessType() != GeckoProcessType_Default) {
        // Content process: ask the Chrome process to give us the list
        InfallibleTArray<FontListEntry> fonts;
        mozilla::dom::ContentChild::GetSingleton()->SendReadFontList(&fonts);
        for (uint32_t i = 0, n = fonts.Length(); i < n; ++i) {
            AppendFaceFromFontListEntry(fonts[i], false);
        }
        // Passing null for userdata tells Finalize that it does not need
        // to sort faces (because they were already sorted by chrome,
        // so we just maintain the existing order)
        mFontFamilies.Enumerate(FinalizeFamilyMemberList, nullptr);
        LOG(("got font list from chrome process: %d faces in %d families",
            fonts.Length(), mFontFamilies.Count()));
        return;
    }

    // Chrome process: get the cached list (if any)
    FontNameCache fnc;

    // ANDROID_ROOT is the root of the android system, typically /system;
    // font files are in /$ANDROID_ROOT/fonts/
    nsCString root;
    char *androidRoot = PR_GetEnv("ANDROID_ROOT");
    if (androidRoot) {
        root = androidRoot;
    } else {
        root = NS_LITERAL_CSTRING("/system");
    }
    root.Append("/fonts");

    FindFontsInDir(root, &fnc);

    if (mFontFamilies.Count() == 0) {
        // if we can't find/read the font directory, we are doomed!
        NS_RUNTIMEABORT("Could not read the system fonts directory");
    }

    // look for fonts shipped with the product
    nsCOMPtr<nsIFile> localDir;
    nsresult rv = NS_GetSpecialDirectory(NS_APP_RES_DIR,
                                         getter_AddRefs(localDir));
    if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(localDir->Append(NS_LITERAL_STRING("fonts")))) {
        ExtractFontsFromJar(localDir);
        nsCString localPath;
        rv = localDir->GetNativePath(localPath);
        if (NS_SUCCEEDED(rv)) {
            FindFontsInDir(localPath, &fnc);
        }
    }

    // look for locally-added fonts in the profile
    rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_LOCAL_50_DIR,
                                getter_AddRefs(localDir));
    if (NS_SUCCEEDED(rv)) {
        nsCString localPath;
        rv = localDir->GetNativePath(localPath);
        if (NS_SUCCEEDED(rv)) {
            FindFontsInDir(localPath, &fnc);
        }
    }

    // Finalize the families by sorting faces into standard order
    // and marking "simple" families.
    // Passing non-null userData here says that we want faces to be sorted.
    mFontFamilies.Enumerate(FinalizeFamilyMemberList, this);
#endif // XP_WIN && ANDROID
}

#ifdef ANDROID
void
gfxFT2FontList::FindFontsInDir(const nsCString& aDir, FontNameCache *aFNC)
{
    static const char* sStandardFonts[] = {
        "DroidSans.ttf",
        "DroidSans-Bold.ttf",
        "DroidSerif-Regular.ttf",
        "DroidSerif-Bold.ttf",
        "DroidSerif-Italic.ttf",
        "DroidSerif-BoldItalic.ttf",
        "DroidSansMono.ttf",
        "DroidSansArabic.ttf",
        "DroidSansHebrew.ttf",
        "DroidSansThai.ttf",
        "MTLmr3m.ttf",
        "MTLc3m.ttf",
        "DroidSansJapanese.ttf",
        "DroidSansFallback.ttf"
    };

    DIR *d = opendir(aDir.get());
    if (!d) {
        return;
    }

    struct dirent *ent = NULL;
    while ((ent = readdir(d)) != NULL) {
        int namelen = strlen(ent->d_name);
        if (namelen <= 4) {
            // cannot be a usable font filename
            continue;
        }
        const char *ext = ent->d_name + namelen - 4;
        if (strcasecmp(ext, ".ttf") == 0 ||
            strcasecmp(ext, ".otf") == 0 ||
            strcasecmp(ext, ".ttc") == 0) {
            bool isStdFont = false;
            for (unsigned int i = 0;
                 i < ArrayLength(sStandardFonts) && !isStdFont; i++) {
                isStdFont = strcmp(sStandardFonts[i], ent->d_name) == 0;
            }

            nsCString s(aDir);
            s.Append('/');
            s.Append(ent->d_name, namelen);

            // Add the face(s) from this file to our font list;
            // note that if we have cached info for this file in fnc,
            // and the file is unchanged, we won't actually need to read it.
            // If the file is new/changed, this will update the FontNameCache.
            AppendFacesFromFontFile(s, isStdFont, aFNC);
        }
    }

    closedir(d);
}
#endif

void
gfxFT2FontList::AppendFaceFromFontListEntry(const FontListEntry& aFLE,
                                            bool aStdFile)
{
    FT2FontEntry* fe = FT2FontEntry::CreateFontEntry(aFLE);
    if (fe) {
        fe->mStandardFace = aStdFile;
        nsAutoString name(aFLE.familyName());
        gfxFontFamily *family = mFontFamilies.GetWeak(name);
        if (!family) {
            family = new FT2FontFamily(name);
            mFontFamilies.Put(name, family);
            if (mBadUnderlineFamilyNames.Contains(name)) {
                family->SetBadUnderlineFamily();
            }
        }
        family->AddFontEntry(fe);

        // this depends on the entry having been added to its family
        fe->CheckForBrokenFont();
    }
}

static PLDHashOperator
AddFamilyToFontList(nsStringHashKey::KeyType aKey,
                    nsRefPtr<gfxFontFamily>& aFamily,
                    void* aUserArg)
{
    InfallibleTArray<FontListEntry>* fontlist =
        reinterpret_cast<InfallibleTArray<FontListEntry>*>(aUserArg);

    FT2FontFamily *family = static_cast<FT2FontFamily*>(aFamily.get());
    family->AddFacesToFontList(fontlist);

    return PL_DHASH_NEXT;
}

void
gfxFT2FontList::GetFontList(InfallibleTArray<FontListEntry>* retValue)
{
    mFontFamilies.Enumerate(AddFamilyToFontList, retValue);
}

nsresult
gfxFT2FontList::InitFontList()
{
    // reset font lists
    gfxPlatformFontList::InitFontList();

    FindFonts();

    return NS_OK;
}

struct FullFontNameSearch {
    FullFontNameSearch(const nsAString& aFullName)
        : mFullName(aFullName), mFontEntry(nullptr)
    { }

    nsString     mFullName;
    gfxFontEntry *mFontEntry;
};

// callback called for each family name, based on the assumption that the
// first part of the full name is the family name
static PLDHashOperator
FindFullName(nsStringHashKey::KeyType aKey,
             nsRefPtr<gfxFontFamily>& aFontFamily,
             void* userArg)
{
    FullFontNameSearch *data = reinterpret_cast<FullFontNameSearch*>(userArg);

    // does the family name match up to the length of the family name?
    const nsString& family = aFontFamily->Name();

    nsString fullNameFamily;
    data->mFullName.Left(fullNameFamily, family.Length());

    // if so, iterate over faces in this family to see if there is a match
    if (family.Equals(fullNameFamily)) {
        nsTArray<nsRefPtr<gfxFontEntry> >& fontList = aFontFamily->GetFontList();
        int index, len = fontList.Length();
        for (index = 0; index < len; index++) {
            if (fontList[index]->Name().Equals(data->mFullName)) {
                data->mFontEntry = fontList[index];
                return PL_DHASH_STOP;
            }
        }
    }

    return PL_DHASH_NEXT;
}

gfxFontEntry*
gfxFT2FontList::LookupLocalFont(const gfxProxyFontEntry *aProxyEntry,
                                const nsAString& aFontName)
{
    // walk over list of names
    FullFontNameSearch data(aFontName);

    mFontFamilies.Enumerate(FindFullName, &data);

    return data.mFontEntry;
}

gfxFontEntry*
gfxFT2FontList::GetDefaultFont(const gfxFontStyle* aStyle, bool& aNeedsBold)
{
#ifdef XP_WIN
    HGDIOBJ hGDI = ::GetStockObject(SYSTEM_FONT);
    LOGFONTW logFont;
    if (hGDI && ::GetObjectW(hGDI, sizeof(logFont), &logFont)) {
        nsAutoString resolvedName;
        if (ResolveFontName(nsDependentString(logFont.lfFaceName), resolvedName)) {
            return FindFontForFamily(resolvedName, aStyle, aNeedsBold);
        }
    }
#elif defined(ANDROID)
    nsAutoString resolvedName;
    if (ResolveFontName(NS_LITERAL_STRING("Roboto"), resolvedName) ||
        ResolveFontName(NS_LITERAL_STRING("Droid Sans"), resolvedName)) {
        return FindFontForFamily(resolvedName, aStyle, aNeedsBold);
    }
#endif
    /* TODO: what about Qt or other platforms that may use this? */
    return nullptr;
}

gfxFontEntry*
gfxFT2FontList::MakePlatformFont(const gfxProxyFontEntry *aProxyEntry,
                                 const uint8_t *aFontData,
                                 uint32_t aLength)
{
    // The FT2 font needs the font data to persist, so we do NOT free it here
    // but instead pass ownership to the font entry.
    // Deallocation will happen later, when the font face is destroyed.
    return FT2FontEntry::CreateFontEntry(*aProxyEntry, aFontData, aLength);
}


text:
namespace Microsoft.Azure.Management.Migrate.ResourceMover.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// The operation error info.
    /// </summary>
    public partial class OperationErrorAdditionalInfo
    {
        /// <summary>
        /// Initializes a new instance of the OperationErrorAdditionalInfo
        /// class.
        /// </summary>
        public OperationErrorAdditionalInfo()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the OperationErrorAdditionalInfo
        /// class.
        /// </summary>
        /// <param name="type">The error type.</param>
        /// <param name="info">The operation error info.</param>
        public OperationErrorAdditionalInfo(string type = default(string), MoveErrorInfo info = default(MoveErrorInfo))
        {
            Type = type;
            Info = info;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets the error type.
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string Type { get; private set; }

        /// <summary>
        /// Gets the operation error info.
        /// </summary>
        [JsonProperty(PropertyName = "info")]
        public MoveErrorInfo Info { get; private set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package chatty.gui.components;

import chatty.User;
import chatty.gui.UserListener;
import chatty.gui.UserlistModel;
import chatty.gui.components.menus.ContextMenuListener;
import chatty.gui.components.menus.UserContextMenu;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JList;

/**
 *
 * @author tduva
 */
public class UserList extends JList<User> {

    private final UserlistModel<User> data;
    private final ContextMenuListener contextMenuListener;
    private final UserListener userListener;

    public UserList(ContextMenuListener contextMenuListener,
            UserListener userListener) {
        data = new UserlistModel<>();
        this.setModel(data);
        this.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    userSelected(e);
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
                openContextMenu(e);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                openContextMenu(e);
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
        this.contextMenuListener = contextMenuListener;
        this.userListener = userListener;
    }

    public void addUser(User user) {
        data.add(user);
    }

    public void removeUser(User user) {
        data.remove(user);
    }

    public void updateUser(User user) {
        data.remove(user);
        data.add(user);
        //TODO: this didnt sort the user correctly after opping, maybe it can be fixed?
        //userlistData.updated(user);
    }

    public void resort() {
        data.sort();
    }

    public void clearUsers() {
        data.clear();
    }

    public int getNumUsers() {
        return data.getSize();
    }

    public ArrayList<User> getData() {
        return data.getData();
    }

    /**
     * Open context menu for this user, if the event points at one.
     *
     * @param e
     */
    private void openContextMenu(MouseEvent e) {
        if (e.isPopupTrigger()) {
            User user = getUser(e);
            if (user != null) {
                UserContextMenu m = new UserContextMenu(user, contextMenuListener);
                m.show(this, e.getX(), e.getY());
            }
        }
    }

    /**
     * Gets the user from the item this mouse event points to.
     *
     * @param e
     * @return The user or null if there is none
     */
    private User getUser(MouseEvent e) {
        int index = locationToIndex(e.getPoint());
        Rectangle bounds = getCellBounds(index, index);
        if (bounds != null && bounds.contains(e.getPoint())) {
            setSelectedIndex(index);
            return getSelectedValue();
        }
        return null;
    }

    /**
     * Called when a user is double-clicked to tell the GUI to perform the
     * User-selected action (open the User Info dialog).
     *
     * @param e
     */
    private void userSelected(MouseEvent e) {
        User user = getUser(e);
        if (user != null) {
            userListener.userClicked(user, e);
        }
    }

}


text:
This repository contains Ansible configurations that can be used to bring up
a simple Mesos/Marathon/Chronos cluster. It will create a cluster with a
single master and two slaves.

## Instructions
You can start the cluster with the following commands:

    vagrant up
    ./init-cluster.sh

This will start the three Vagrant machines, install a mesos cluster on them,
and install two sample Marathon apps, and a smaple Chronos app. This will take
a long time if it is the first time you have run it as it will have to
download the vm images, the packages and the docker images.

The `./init-cluster.sh` script will add all the files in `task-data/marathon`
to Marathon on the master and all the files in `task-data/chronos` to Chronos.
You can use the existing files in these directories as templates for your own
Marathon and chronos services.

## Details

### master-1
- **Role:** Master
- **OS:** CentOS 7
- **Apps:** Zookeeper, [Mesos](http://192.168.77.254:5050/), [Marathon](http://192.168.77.254:8080/), [Chronos](http://192.168.77.254:4400/)
- **IP:** `192.168.77.254`

### slave-1
- **Role:** Slave
- **OS:** CentOS 7
- **Apps:** Mesos, Docker, [HAProxy](http://192.168.77.10:9090/)
- **IP:** `192.168.77.10`

### slave-2
- **Role:** Slave
- **OS:** CentOS 7
- **Apps:** Mesos, Docker, [HAProxy](http://192.168.77.11:9090/)
- **IP:** `192.168.77.11`


text:
cd "$(dirname "$0")"

set -x -e

mkdir -p dlib
if [ ! -f dlib/shape_predictor_68_face_landmarks.dat ]; then
  wget http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2 \
    -O dlib/shape_predictor_68_face_landmarks.dat.bz2
  bunzip2 dlib/shape_predictor_68_face_landmarks.dat.bz2
fi

set +x
echo ==========
echo The nn4.v1.t7 and celeb-classifier.nn4.v1.pkl models are
echo copyright Carnegie Mellon University and are licensed under
echo the Apache 2.0 License.
echo ==========
set -x
mkdir -p openface
if [ ! -f openface/nn4.v1.t7 ]; then
  wget http://openface-models.storage.cmusatyalab.org/nn4.v1.t7 \
    -O openface/nn4.v1.t7
  wget http://openface-models.storage.cmusatyalab.org/celeb-classifier.nn4.v1.pkl \
    -O openface/celeb-classifier.nn4.v1.pkl
fi


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

namespace Sabio.Web.Domain.Tests
{
    public class TestEmployee
    {
        public int Id { get; set; }

        public string LastName { get; set; }

        public string FirstName { get; set; }

        public DateTime Dob { get; set; }

        public string Title { get; set; }

        public int Status { get; set; }
    }
}


text:
(function() {
	'use strict';

	angular.module('ngInterview', [
		'ngRoute',
		'ngInterview.currentDate',
		'ngInterview.students'
	]);
})();


text:
@import "../fonts/GilliusADF/gilliusno2.css";
@import "../fonts/GilliusADF/gilliusadf-cond.css";
/*
 * main.less, step 5
 */
/*
 * font-nice-names.less
 */
/*
 * fonts.less
 */
body {
  font-family: gillius_adf_no2, Helvetica, Arial, Verdana, Geneva, sans-serif;
}
body > header {
  font-family: gillius_adfcondensed, Impact, Verdana, Geneva, sans-serif;
}
body > header h1 {
  font-family: gillius_adfcondensed, Impact, Verdana, Geneva, sans-serif;
  font-style: italic;
}
body > footer {
  font-family: gillius_adfcondensed, Impact, Verdana, Geneva, sans-serif;
}
body > footer em {
  font-style: italic;
}
body > footer em strong {
  font-weight: bold;
}
body > footer strong {
  font-weight: bold;
}
body > footer strong em {
  font-style: italic;
}
body > section h1,
body > section h2,
body > section h3,
body > section h4 {
  font-family: gillius_adfcondensed, Impact, Verdana, Geneva, sans-serif;
  font-weight: bold;
}
body > section article footer {
  font-family: gillius_adfcondensed, Impact, Verdana, Geneva, sans-serif;
}
/*
 * colors-nice.less
 */
body {
  background-color: #444;
}
a {
  color: bisque;
  text-decoration: none;
}
a:hover {
  color: chocolate;
}
body > header {
  background-color: black;
}
body > header h1 {
  color: lightgray;
}
body > header p {
  color: lightblue;
}
body > header nav {
  background-color: black;
  color: bisque;
}
body > footer {
  background-color: brown;
  color: bisque;
}
body > section article {
  background-color: #eee;
}
body > section article h2 {
  background-color: brown;
  color: beige;
}
body > section article h3,
body > section article h4 {
  background-color: salmon;
}
body > section article a {
  color: brown;
}
body > section article footer {
  background-color: brown;
  color: bisque;
}
body > section aside {
  background-color: chocolate;
}
body > section aside menu {
  background-color: brown;
}
/*
 * basci-lists.less
 */
body > section > article ul {
  list-style-type: disc;
  list-style-position: inside;
}
body > section > article ul li {
  margin-left: 1em;
}
/*
 * width.less
 */
body > header {
  width: 100%;
}
body > footer {
  width: 100%;
}
body > section {
  max-width: 960px;
}
body > section article {
  max-width: 560px;
}
body > section aside {
  max-width: 200px;
}
body > section aside menu {
  width: 100%;
}
/*
 * spacing.less
 */
body {
  margin: auto;
}
body > header {
  margin: 0 auto 1em auto;
}
body > header h1 {
  margin: 0 0.3em 0.3em 0.3em;
}
body > header p {
  margin: 0 0.3em 0.3em 0.3em;
}
body > footer {
  margin: 1em 0 0.3em 0;
  padding: 0.2em;
}
body > section {
  margin: 1em auto;
}
body > section article {
  margin: 1em;
  padding: 1em;
}
body > section article p {
  margin: 0.1em 0.3em 0.9em 0.3em;
}
body > section article footer {
  font-size: 0.8em;
  line-height: 1.6em;
}
body > section aside {
  margin: 1em;
  padding: 1em;
}
body > header h1 {
  font-size: 2em;
  line-height: 1.9em;
}
body > header p {
  line-height: 1.5em;
}
body > header nav {
  line-height: 1.9em;
}
body > footer {
  font-size: 0.8em;
  line-height: 1.9em;
}
body > section p,
body > section li {
  line-height: 1.4em;
}
body > section h2,
body > section h3,
body > section h4 {
  line-height: 1.5em;
}
body > section h2 {
  font-size: 2.15em;
}
body > section h3 {
  font-size: 1.85em;
}
body > section h4 {
  font-size: 1.65em;
}
body > section article footer {
  line-height: 1.9em;
}
body > section aside h2 {
  font-size: 1.35em;
}
/*
 * positions.less
 */
body > section article {
  display: inline-block;
  webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  vertical-align: top;
}
body > section aside {
  display: inline-block;
  webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  vertical-align: top;
}
/*
 * nav-menus.less
 */
body > header nav a {
  border-right: 2px solid #ccc;
  margin: 1em;
  padding: 0.5em;
}
body > section aside menu h2 {
  text-align: center;
}
body > section aside menu a {
  display: block;
  margin: 0.5em;
  padding: 0.5em;
}
body > section p,
body > section li {
  text-align: justify;
}


text:
package config

import (
	"github.com/majestrate/XD/lib/configparser"
	"github.com/majestrate/XD/lib/log"
	"github.com/majestrate/XD/lib/network/i2p"
	"github.com/majestrate/XD/lib/util"
	"os"
)

type I2PConfig struct {
	Addr            string
	Keyfile         string
	Name            string
	nameWasProvided bool
	I2CPOptions     map[string]string
	Disabled        bool
}

func (cfg *I2PConfig) Load(section *configparser.Section) error {
	cfg.I2CPOptions = make(map[string]string)
	if section == nil {
		cfg.Addr = i2p.DEFAULT_ADDRESS
		cfg.Keyfile = ""
		cfg.Name = util.RandStr(5)
		cfg.Disabled = DisableI2PByDefault
	} else {
		cfg.Disabled = section.Get("disabled", "") == "1"
		cfg.Addr = section.Get("address", i2p.DEFAULT_ADDRESS)
		cfg.Keyfile = section.Get("keyfile", "")
		gen := util.RandStr(5)
		cfg.Name = section.Get("session", gen)
		cfg.nameWasProvided = cfg.Name != gen
		opts := section.Options()
		for k, v := range opts {
			if k == "address" || k == "keyfile" || k == "session" || k == "disabled" {
				continue
			}
			cfg.I2CPOptions[k] = v
		}
	}
	return nil
}

func (cfg *I2PConfig) Save(s *configparser.Section) error {
	opts := make(map[string]string)
	if cfg.I2CPOptions != nil {
		for k, v := range cfg.I2CPOptions {
			opts[k] = v
		}
	}
	opts["address"] = cfg.Addr
	if cfg.Keyfile != "" {
		opts["keyfile"] = cfg.Keyfile
	}
	if cfg.nameWasProvided {
		opts["session"] = cfg.Name
	}
	if cfg.Disabled {
		opts["disabled"] = "1"
	} else {
		opts["disabled"] = "0"
	}
	for k := range opts {
		s.Add(k, opts[k])
	}
	return nil
}

// create an i2p session from this config
func (cfg *I2PConfig) CreateSession() i2p.Session {
	log.Infof("create new i2p session with %s", cfg.Addr)
	return i2p.NewSession(util.RandStr(5), cfg.Addr, cfg.Keyfile, cfg.I2CPOptions)
}

// EnvI2PAddress is the name of the environmental variable to set the i2p address for XD
const EnvI2PAddress = "XD_I2P_ADDRESS"

func (cfg *I2PConfig) LoadEnv() {
	addr := os.Getenv(EnvI2PAddress)
	if addr != "" {
		cfg.Addr = addr
	}
}


text:
package proxy

import (
	"context"
	"sort"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"github.com/stretchr/testify/require"
	"k8s.io/client-go/tools/clientcmd"
	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"

	"github.com/gravitational/teleport/api/types"
	testingkubemock "github.com/gravitational/teleport/lib/kube/proxy/testing/kube_server"
	"github.com/gravitational/teleport/lib/services"
)

// TestWatcher verifies that kubernetes agent properly detects and applies
// changes to kube_cluster resources.
func TestWatcher(t *testing.T) {
	kubeMock, err := testingkubemock.NewKubeAPIMock()
	require.NoError(t, err)
	t.Cleanup(func() { kubeMock.Close() })

	ctx := context.Background()

	reconcileCh := make(chan types.KubeClusters)
	// Setup kubernetes server that proxies one static kube cluster and
	// watches for kube_clusters with label group=a.
	testCtx := setupTestContext(ctx, t, testConfig{
		clusters: []kubeClusterConfig{{"kube0", kubeMock.URL}},
		resourceMatchers: []services.ResourceMatcher{
			{Labels: types.Labels{
				"group": []string{"a"},
			}},
		},
		onReconcile: func(kcs types.KubeClusters) {
			reconcileCh <- kcs
		},
	})

	require.Len(t, testCtx.kubeServer.fwd.kubeClusters(), 1)
	kube0 := testCtx.kubeServer.fwd.kubeClusters()[0]

	// Only kube0 should be registered initially.
	select {
	case a := <-reconcileCh:
		sort.Sort(a)
		require.Empty(t, cmp.Diff(types.KubeClusters{kube0}, a,
			cmpopts.IgnoreFields(types.Metadata{}, "ID"),
		))
	case <-time.After(time.Second):
		t.Fatal("Didn't receive reconcile event after 1s.")
	}

	// Create kube_cluster with label group=a.
	kube1, err := makeDynamicKubeCluster(t, "kube1", kubeMock.URL, map[string]string{"group": "a"})
	require.NoError(t, err)
	err = testCtx.authServer.CreateKubernetesCluster(ctx, kube1)
	require.NoError(t, err)

	// It should be registered.
	select {
	case a := <-reconcileCh:
		sort.Sort(a)
		require.Empty(t, cmp.Diff(types.KubeClusters{kube0, kube1}, a,
			cmpopts.IgnoreFields(types.Metadata{}, "ID"),
		))
	case <-time.After(time.Second):
		t.Fatal("Didn't receive reconcile event after 1s.")
	}

	// Try to update kube0 which is registered statically.
	kube0Updated, err := makeDynamicKubeCluster(t, "kube0", kubeMock.URL, map[string]string{"group": "a", types.OriginLabel: types.OriginDynamic})
	require.NoError(t, err)
	err = testCtx.authServer.CreateKubernetesCluster(ctx, kube0Updated)
	require.NoError(t, err)

	// It should not be registered, old kube0 should remain.
	select {
	case a := <-reconcileCh:
		sort.Sort(a)
		require.Empty(t, cmp.Diff(types.KubeClusters{kube0, kube1}, a,
			cmpopts.IgnoreFields(types.Metadata{}, "ID"),
		))
	case <-time.After(time.Second):
		t.Fatal("Didn't receive reconcile event after 1s.")
	}

	// Create kube_cluster with label group=b.
	kube2, err := makeDynamicKubeCluster(t, "kube2", kubeMock.URL, map[string]string{"group": "b"})
	require.NoError(t, err)
	err = testCtx.authServer.CreateKubernetesCluster(ctx, kube2)
	require.NoError(t, err)

	// It shouldn't be registered.
	select {
	case a := <-reconcileCh:
		sort.Sort(a)
		require.Empty(t, cmp.Diff(types.KubeClusters{kube0, kube1}, a,
			cmpopts.IgnoreFields(types.Metadata{}, "ID"),
		))
	case <-time.After(time.Second):
		t.Fatal("Didn't receive reconcile event after 1s.")
	}

	// Update kube2 labels so it matches.
	kube2.SetStaticLabels(map[string]string{"group": "a", types.OriginLabel: types.OriginDynamic})
	err = testCtx.authServer.UpdateKubernetesCluster(ctx, kube2)
	require.NoError(t, err)

	// Both should be registered now.
	select {
	case a := <-reconcileCh:
		sort.Sort(a)
		require.Empty(t, cmp.Diff(types.KubeClusters{kube0, kube1, kube2}, a,
			cmpopts.IgnoreFields(types.Metadata{}, "ID"),
		))
	case <-time.After(time.Second):
		t.Fatal("Didn't receive reconcile event after 1s.")
	}

	// Update kube2 expiry so it gets re-registered.
	kube2.SetExpiry(time.Now().Add(1 * time.Hour))
	kube2.SetKubeconfig(newKubeConfig(t, "random", "https://api.cluster.com"))
	err = testCtx.authServer.UpdateKubernetesCluster(ctx, kube2)
	require.NoError(t, err)

	// kube2 should get updated.
	select {
	case a := <-reconcileCh:
		sort.Sort(a)
		require.Empty(t, cmp.Diff(types.KubeClusters{kube0, kube1, kube2}, a,
			cmpopts.IgnoreFields(types.Metadata{}, "ID"),
		))
		// make sure credentials were updated as well.
		require.Equal(t, "api.cluster.com:443", testCtx.kubeServer.fwd.clusterDetails["kube2"].kubeCreds.getTargetAddr())
	case <-time.After(time.Second):
		t.Fatal("Didn't receive reconcile event after 1s.")
	}

	// Update kube1 labels so it doesn't match.
	kube1.SetStaticLabels(map[string]string{"group": "c", types.OriginLabel: types.OriginDynamic})
	err = testCtx.authServer.UpdateKubernetesCluster(ctx, kube1)
	require.NoError(t, err)

	// Only kube0 and kube2 should remain registered.
	select {
	case a := <-reconcileCh:
		sort.Sort(a)
		require.Empty(t, cmp.Diff(types.KubeClusters{kube0, kube2}, a,
			cmpopts.IgnoreFields(types.Metadata{}, "ID"),
		))
	case <-time.After(time.Second):
		t.Fatal("Didn't receive reconcile event after 1s.")
	}

	// Remove kube2.
	err = testCtx.authServer.DeleteKubernetesCluster(ctx, kube2.GetName())
	require.NoError(t, err)

	// Only static kube_cluster should remain.
	select {
	case a := <-reconcileCh:
		require.Empty(t, cmp.Diff(types.KubeClusters{kube0}, a,
			cmpopts.IgnoreFields(types.Metadata{}, "ID"),
		))
	case <-time.After(time.Second):
		t.Fatal("Didn't receive reconcile event after 1s.")
	}
}

func makeDynamicKubeCluster(t *testing.T, name, url string, labels map[string]string) (*types.KubernetesClusterV3, error) {
	return makeKubeCluster(t, name, url, labels, map[string]string{
		types.OriginLabel: types.OriginDynamic,
	})
}

func makeKubeCluster(t *testing.T, name string, url string, labels map[string]string, additionalLabels map[string]string) (*types.KubernetesClusterV3, error) {
	if labels == nil {
		labels = make(map[string]string)
	}
	for k, v := range additionalLabels {
		labels[k] = v
	}
	return types.NewKubernetesClusterV3(types.Metadata{
		Name:   name,
		Labels: labels,
	}, types.KubernetesClusterSpecV3{
		Kubeconfig: newKubeConfig(t, name, url),
	})
}

func newKubeConfig(t *testing.T, name, url string) []byte {
	kubeConf := clientcmdapi.NewConfig()

	kubeConf.Clusters[name] = &clientcmdapi.Cluster{
		Server:                url,
		InsecureSkipTLSVerify: true,
	}
	kubeConf.AuthInfos[name] = &clientcmdapi.AuthInfo{}

	kubeConf.Contexts[name] = &clientcmdapi.Context{
		Cluster:  name,
		AuthInfo: name,
	}

	buf, err := clientcmd.Write(*kubeConf)
	require.NoError(t, err)
	return buf
}


text:
package com.twitter.http2;

import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.concurrent.Future;

/**
 * An {@link HttpMessage} that adds support for streaming content using {@linkplain Pipe pipes}.
 * @see Pipe
 */
public interface StreamedHttpMessage extends HttpMessage {

    /**
     * Gets the pipe for sending the message body as {@linkplain HttpContent} objects.
     * A {@linkplain LastHttpContent last http content} will indicate the end of the body.
     *
     * @return the message body pipe.
     * @see RFC 2616, 3.6.1 Chunked Transfer Coding
     * @see RFC 2616, 4.3 Message Body
     */
    Pipe<HttpContent> getContent();

    /**
     * Adds content to the pipe. This returns a future for determining whether the message was received.
     * If the chunk is the last chunk then the pipe will be closed.
     *

     * An {@link LastHttpContent} can be used for the trailer part of a chunked-encoded request.

     *

     * This method is preferable to {@code getContent().send()} because it does additional checks.

     *
     * @param content the content to send
     * @return a future indicating when the message was received.
     */
    Future<Void> addContent(HttpContent content);
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Getting Started — django-google-address 0.1.0 documentation</title>

    <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />

        <link rel="index" title="Index"
              href="../genindex.html"/>
        <link rel="search" title="Search" href="../search.html"/>
    <link rel="top" title="django-google-address 0.1.0 documentation" href="../index.html"/>
        <link rel="next" title="Settings" href="settings.html"/>
        <link rel="prev" title="django-google-address" href="../index.html"/>

             django-google-address

                0.1.0

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Contents:

Getting Started

Installing

Configuring

Using

Settings

Models

Filtering

          django-google-address

Docs »

Getting Started

             View page source

Getting Started¶

The module is easy to use and you can get started with django-google-address in just a few minutes.

Installing¶

Install the module like any other python module:

pip install django-google-address

Add it to INSTALLED_APPS on settings.py:

INSTALLED_APPS = [
  ...,
  'google_address'
]

Migrate:

./manage.py migrate

Configuring¶

There are two settings you can and should use to make the module work correctly.
Here is an example of such configuration:

GOOGLE_ADDRESS = {
  'API_KEY': 'BIzaSyFCcHqskKlpsUJ5jdQGVzdP-7uNu9O4g8w'
  'API_LANGUAGE': 'en_US'
}

You can read more about configuring at Settings section.

Using¶

Create an Address object with the raw address. Requests will be made to the Google API when saving the address:

>>> from google_address.models import Address
>>> a = Address(raw="Av. Paulista, 1000")
>>> a.save()
>>> a.address_line
'Avenida Paulista, 1000, Bela Vista, São Paulo, SP, Brazil'

You can easily use foreign keys to the model:

class Building(models.Model):
  address = models.ForeignKey('google_address.Address')

        Next

         Previous

        © Copyright 2017, Leonardo Arroyo.

  Built with Sphinx using a theme provided by Read the Docs.


text:
gitCleanHelp() {
	echo "recusive git clean and remote pull\n"
	echo "\tUseage: update-all-git-repository [option] \n"
	echo "\tOption: \n\t\tCleanWorking - Clean working directory and fetch all remote git repositories"
}

gitCleanPull() {
	echo "git fetch ..."
	git fetch --progress --prune origin
	echo "git pull ..."
	git pull --rebase --progress
	echo "git reset master ..."
	git reset --hard origin/master
}

gitCleanWorkingDir() {
	echo "stash cleaning ..."
	git stash clear
	echo "working dir cleaning ..."
	git clean -fdx *
	echo "checkout last HEAD"
	git checkout . --force
}

gitCleanAndPull() {
	gitCleanWorkingDir
	gitCleanPull
}

rDir() {
	for d in "$1"/*; do
		[ $d = "." -o $d = ".." -o -f $d ] && continue
		[ "${d#*.git}" = "$d" ] && continue
		echo "\n\n############\n$d"
   		cd $d && $2 && cd ..
   		done
}

if [ "${1#-h}" != "$1" -o "${1#help}" != "$1" -o "${1#--help}" != "$1" ]; then
	gitCleanHelp
	exit 0
fi

if [ "$2" != "" ]; then
	workingDir="$2"
else
	workingDir=`pwd`
fi

echo "working directory: $workingDir"

if [ "$1"="CleanWorking" ]; then
	rDir $workingDir gitCleanAndPull
else
	rDir $workingDir gitCleanPull
fi

echo "\n\n------------------------------\nFinish git cleaning or pull"


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

namespace Scurry.Jobs.RiverJob.Contexts.Mouths
{
    [Serializable]
    [JsonObject]
    public class Mouth
    {
        public string Url { get; set; }

        public string Index { get; set; }

        public string Type { get; set; }

        public int MaxBulkSize { get; set; }

        public Mapping Mapping { get; set; }

        public bool DeleteExisting { get; set; }

        Mouth()
        {
            MaxBulkSize = 100;
            DeleteExisting = false;
        }
    }

    [Serializable]
    [JsonObject]
    public class Mapping
    {
        public Parent Parent { get; set; }
    }

    [Serializable]
    [JsonObject]
    public class Parent
    {
        public string Type { get; set; }
    }
}


text:
package org.jsefa.flr.annotation;

import java.lang.reflect.Field;

import org.jsefa.common.accessor.ObjectAccessorProvider;
import org.jsefa.common.annotation.AnnotationException;
import org.jsefa.common.converter.SimpleTypeConverter;
import org.jsefa.common.converter.provider.SimpleTypeConverterProvider;
import org.jsefa.common.mapping.TypeMapping;
import org.jsefa.common.util.GeneralConstants;
import org.jsefa.common.validator.provider.ValidatorProvider;
import org.jsefa.flr.mapping.FlrSimpleTypeMapping;
import org.jsefa.rbf.annotation.RbfAnnotations;
import org.jsefa.rbf.annotation.RbfTypeMappingFactory;
import org.jsefa.rbf.mapping.RbfTypeMappingRegistry;

/**
 * Factory for creating {@link TypeMapping}s from annotated classes.
 *

 * It is thread-safe.
 *
 * @author Norman Lahme-Huetig
 *
 */
public final class FlrTypeMappingFactory extends RbfTypeMappingFactory {

    private static final RbfAnnotations ANNOTATIONS = new RbfAnnotations(FlrDataType.class, FlrField.class,
            FlrSubRecord.class, FlrSubRecordList.class);

    private char defaultPadCharacter;

    /**
     * Constructs a new FlrTypeMappingFactory.
     *
     * @param typeMappingRegistry the type mapping registry. New types will be registered using that registry.
     * @param objectAccessorProvider the object accessor provider to use
     * @param simpleTypeConverterProvider the simple type converter provider to use
     * @param validatorProvider the validator provider to use
     * @param defaultPadCharacter the default pad character to be used
     */
    public FlrTypeMappingFactory(RbfTypeMappingRegistry typeMappingRegistry,
            SimpleTypeConverterProvider simpleTypeConverterProvider,
            ValidatorProvider validatorProvider, ObjectAccessorProvider objectAccessorProvider,
            char defaultPadCharacter) {
        super(typeMappingRegistry, simpleTypeConverterProvider, validatorProvider, objectAccessorProvider,
                ANNOTATIONS);
        this.defaultPadCharacter = defaultPadCharacter;
    }

    /**
     * {@inheritDoc}
     */
    protected TypeMapping<String> createSimpleTypeMapping(Class<?> objectType, String dataTypeName,
            SimpleTypeConverter converter, Field field) {
        FlrField fieldAnnotation = field.getAnnotation(FlrField.class);
        if (fieldAnnotation.length() <= 0) {
            throw new AnnotationException("Field length of field " + field.getName() + " of class "
                    + field.getDeclaringClass().getName() + " must be > 0");
        }
        char padCharacter = fieldAnnotation.padCharacter();
        if (padCharacter == GeneralConstants.DEFAULT_CHARACTER) {
            padCharacter = this.defaultPadCharacter;
        }
        return new FlrSimpleTypeMapping(objectType, dataTypeName, converter, fieldAnnotation.length(),
                padCharacter, fieldAnnotation.align());
    }

}


text:
from exabgp.configuration.environment import environment

class Error (StandardError):
	def __init__ (self):
		self.message = ''
		self.debug = environment.settings().debug.configuration

	def set (self, message):
		self.message = message
		if self.debug:
			print '\n%s\n' % self.message
			from pdb import set_trace
			set_trace()
			return True
		return False

	def throw (self,message):
		self.message = message
		if self.debug:
			print '\n%s\n' % message
			from pdb import set_trace
			set_trace()
		else:
			raise self

	def clear (self):
		self.message = ''

	def __repr__ (self):
		return self.message


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.VNavigationDrawer = undefined;

var _VNavigationDrawer = require('./VNavigationDrawer');

var _VNavigationDrawer2 = _interopRequireDefault(_VNavigationDrawer);

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

exports.VNavigationDrawer = _VNavigationDrawer2.default;
exports.default = _VNavigationDrawer2.default;
//# sourceMappingURL=index.js.map


text:
<?xml version="1.0" encoding="UTF-8"?>
    <project name="build-jnlp-servlet-test" default="build-jnlp-servlet-test"
             xmlns:mvn="antlib:org.apache.maven.artifact.ant">
        <description>
            Builds JNLP servlet test
        </description>

            <!-- Preamble definitions -->
        <dirname property="project.root.dir" file="${ant.file}"/>
        <dirname property="artifacts.root.dir" file="${project.root.dir}"/>
        <property name="module.root.folder" value="${project.root.dir}"/>
        <property name="module.base.target.name" value="jnlp-servlet-test"/>
        <property name="default.classpath.ref.name" value="jnlp.servlet.path"/>
        <import file="${artifacts.root.dir}${file.separator}build-base.xml"/>

            <!-- define dependencies -->
        <mvn:dependencies     pathId="jnlp.servlet.dependencies.path" useScope="compile"
                            settingsFile="${maven.settings.file.path}"
                >
            <localRepository path="${maven.local.repository.folder}" layout="default"/>

            <dependency groupId="javax.servlet"
                        artifactId="servlet-api"
                        version="${servlet.api.jar.version}"
                        scope="compile"/>
        </mvn:dependencies>

        <path id="jnlp.servlet.path">
            <path refid="community.modules.jars"/>
            <path refid="jnlp.servlet.dependencies.path"/>
        </path>

        <property name="signed.test.jars.folder" value="${community.root.dir}${file.separator}signed"/>
        <target name="build-jnlp-servlet-test" depends="community-base" description="Build JNLP test servlet">
            <mkdir dir="${signed.test.jars.folder}"/>
            <copy preservelastmodified="true" flatten="true" todir="${signed.test.jars.folder}">
                <fileset dir="${community.lib.folder}" includes="**/*.${jar.file.suffix}"/>
                <fileset dir="${maven.local.repository.folder}" includes="**/*.${jar.file.suffix}"/>
            </copy>

            <delete>
                <fileset dir="${signed.test.jars.folder}"
                         includes="*-sources.${jar.file.suffix},*-javadoc.${jar.file.suffix}"/>
            </delete>

            <signjar    alias="${sign.keystore.alias}"
                        storepass="${sign.keystore.password}"
                        keystore="${sign.keystore.location}"
                        lazy="true"
                >
                <path>
                    <fileset dir="${signed.test.jars.folder}" includes="*.${jar.file.suffix}"/>
                </path>
            </signjar>
        </target>

        <target name="clean-jnlp-servlet-test" depends="clean-module-target-build" description="Cleans the JMX Tomcat servlet">
            <delete dir="${signed.test.jars.folder}"/>
        </target>
    </project>


text:
"""Setup script of zinnia-twitter"""
from setuptools import setup
from setuptools import find_packages

import zinnia_twitter

setup(
    name='zinnia-twitter',
    version=zinnia_twitter.__version__,

    description='Twitter plugin for django-blog-zinnia',
    long_description=open('README.rst').read(),

    keywords='django, zinnia, twitter',

    author=zinnia_twitter.__author__,
    author_email=zinnia_twitter.__email__,
    url=zinnia_twitter.__url__,

    packages=find_packages(exclude=['demo_zinnia_twitter']),
    classifiers=[
        'Framework :: Django',
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'License :: OSI Approved :: BSD License',
        'Topic :: Software Development :: Libraries :: Python Modules'],

    license=zinnia_twitter.__license__,
    include_package_data=True,
    zip_safe=False,
    install_requires=['tweepy']
)


text:
using System;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.Shell;

namespace MDK.VisualStudio
{
    /// <summary>
    /// Provides a base class for a Visual Studio menu command.
    /// </summary>
    public abstract class Command
    {
        /// <summary>
        /// Creates a new instance of a <see cref="Command"/>.
        /// </summary>
        /// <param name="package">The Visual Studio package this command belongs to</param>
        protected Command(ExtendedPackage package)
        {
            Package = package;
        }

        /// <summary>
        /// The Visual Studio package this command belongs to
        /// </summary>
        public ExtendedPackage Package { get; }

        /// <summary>
        /// The ID of the command group this command belongs to
        /// </summary>
        public abstract Guid GroupId { get; }

        /// <summary>
        /// The package-wide unique ID of this command
        /// </summary>
        public abstract int Id { get; }

        /// <summary>
        /// Gets the service provider from the owner MDKPackage.
        /// </summary>
        protected IServiceProvider ServiceProvider => Package;

        /// <summary>
        /// The inner command
        /// </summary>
        protected OleMenuCommand OleCommand { get; private set; }

        /// <summary>
        /// Initializes this command.
        /// </summary>
        public virtual void Initialize()
        {
            if (!(ServiceProvider.GetService(typeof(IMenuCommandService)) is OleMenuCommandService commandService))
            {
                Package.LogPackageError(GetType().FullName, new InvalidOperationException("Cannot retrieve menu command service"));
                return;
            }

            var menuCommandId = new CommandID(GroupId, Id);
            OleCommand = new OleMenuCommand((s, e) => OnExecute(), menuCommandId);
            OleCommand.BeforeQueryStatus += (s, e) => OnBeforeQueryStatus();
            commandService.AddCommand(OleCommand);
        }

        /// <summary>
        /// Called to change the state of a command
        /// </summary>
        protected abstract void OnBeforeQueryStatus();

        /// <summary>
        /// Called when a user invokes this command.
        /// </summary>
        protected abstract void OnExecute();
    }
}


text:
package zipkin.collector.kafka10;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zipkin.Span;
import zipkin.SpanDecoder;
import zipkin.collector.Collector;
import zipkin.collector.CollectorMetrics;

import static zipkin.SpanDecoder.DETECTING_DECODER;
import static zipkin.storage.Callback.NOOP;

/** Consumes spans from Kafka messages, ignoring malformed input */
final class KafkaCollectorWorker implements Runnable {
  private static final Logger LOG = LoggerFactory.getLogger(KafkaCollectorWorker.class);

  final Consumer<byte[], byte[]> kafkaConsumer;
  final Collector collector;
  final CollectorMetrics metrics;
  /** Kafka topic partitions currently assigned to this worker. List is not modifiable. */
  final AtomicReference<List<TopicPartition>> assignedPartitions =
      new AtomicReference<>(Collections.emptyList());

  KafkaCollectorWorker(KafkaCollector.Builder builder) {
    kafkaConsumer = new KafkaConsumer<>(builder.properties);
    List<String> topics = Arrays.asList(builder.topic.split(","));
    kafkaConsumer.subscribe(topics, new ConsumerRebalanceListener() {
      @Override public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
        assignedPartitions.set(Collections.emptyList());
      }

      @Override public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
        assignedPartitions.set(Collections.unmodifiableList(new ArrayList<>(partitions)));
      }
    });
    this.collector = builder.delegate.build();
    this.metrics = builder.metrics;
  }

  @Override
  public void run() {
    try {
      LOG.info("Kafka consumer starting polling loop.");
      while (true) {
        final ConsumerRecords<byte[], byte[]> consumerRecords = kafkaConsumer.poll(1000);
        LOG.debug("Kafka polling returned batch of {} messages.", consumerRecords.count());
        for (ConsumerRecord<byte[], byte[]> record : consumerRecords) {
          metrics.incrementMessages();
          final byte[] bytes = record.value();

          if (bytes.length == 0) {
            metrics.incrementMessagesDropped();
          } else {
            // If we received legacy single-span encoding, decode it into a singleton list
            if (bytes[0] <= 16 && bytes[0] != 12 /* thrift, but not a list */) {
              metrics.incrementBytes(bytes.length);
              try {
                Span span = SpanDecoder.THRIFT_DECODER.readSpan(bytes);
                collector.accept(Collections.singletonList(span), NOOP);
              } catch (RuntimeException e) {
                metrics.incrementMessagesDropped();
              }
            } else {
              collector.acceptSpans(bytes, DETECTING_DECODER, NOOP);
            }
          }
        }
      }
    } finally {
      LOG.info("Kafka consumer polling loop stopped.");
      LOG.info("Closing Kafka consumer...");
      kafkaConsumer.close();
      LOG.info("Kafka consumer closed.");
    }
  }
}


text:
package pt.up.fe.lpoo.towerdefense;

import java.util.ArrayList;

import pt.up.fe.lpoo.framework.Image;

/**
 * Super class for all drawable game objects other than tiles.
 *  Implements comparable for visibility calculations purposes.
 * @author Joao Marinheiro
 * @author Luis Cleto
 */
public abstract class GameObj implements Comparable<GameObj>{
	/**
	 * @return returns the x position of the center of the object in the map
	 */
	public abstract int getCenterX();
	/**
	 * @return returns the y position of the center of the object in the map
	 */
	public abstract int getCenterY();

	/**
	 * Compares two game objects. A game object is 'smaller' than another if it should be drawn before the other
	 *  (deppending on whether any of them is a ground object and their y position)
	 */
	@Override
	public int compareTo(GameObj other){
		if ((getCenterY() < other.getCenterY() && !(other.isGroundObject())) || this.isGroundObject())
        {
            return -1;
        }
        if ((getCenterY() > other.getCenterY() && !(this.isGroundObject())) || other.isGroundObject())
        {
            return 1;
        }
        return 0;
	}
	/**
	 * @return returns true if the object is part of the ground terrain, false otherwise
	 */
	public abstract boolean isGroundObject();
	/**
	 * @return returns the object's current image to be drawn
	 */
	public abstract Image getCurrentImage();
	/**
	 * @return returns any status effects currently affecting the object
	 */
	public abstract ArrayList<StatusEffect> getStatusEffects();
	/**
	 * @return returns the x position of the upper left corner of the object (for drawing)
	 */
	public abstract int getX();
	/**
	 * @return returns the y position of the upper left corner of the object (for drawing)
	 */
	public abstract int getY();
}


text:
package common_test

import (
	"fmt"
	"testing"

	. "github.com/FactomProject/FactomCode/common"
)

func TestIncreaseBalanceMarshalUnmarshal(t *testing.T) {
	ib1 := NewIncreaseBalance()
	pub := new([32]byte)
	copy(pub[:], byteof(0xaa))
	ib1.ECPubKey = pub
	ib1.TXID.SetBytes(byteof(0xbb))
	ib1.NumEC = uint64(13)
	p, err := ib1.MarshalBinary()
	if err != nil {
		t.Error(err)
	}
	ib2 := NewIncreaseBalance()
	ib2.UnmarshalBinary(p)

	q, err := ib2.MarshalBinary()
	if err != nil {
		t.Error(err)
	}
	if string(p) != string(q) {
		t.Errorf("ib1 = %x\n", p)
		t.Errorf("ib2 = %x\n", q)
	}
}

func TestInvalidIncreaseBalanceUnmarshal(t *testing.T) {
	fmt.Printf("\n---\nTestInvalidIncreaseBalanceUnmarshal\n---\n")

	ib := NewIncreaseBalance()
	_, err := ib.UnmarshalBinaryData(nil)
	if err == nil {
		t.Error("We expected errors but we didn't get any")
	}
	ib = NewIncreaseBalance()
	_, err = ib.UnmarshalBinaryData([]byte{})
	if err == nil {
		t.Error("We expected errors but we didn't get any")
	}

	ib = NewIncreaseBalance()
	err = ib.UnmarshalBinary(nil)
	if err == nil {
		t.Error("We expected errors but we didn't get any")
	}
	ib = NewIncreaseBalance()
	err = ib.UnmarshalBinary([]byte{})
	if err == nil {
		t.Error("We expected errors but we didn't get any")
	}
}


text:
module MongoModel
  module Associations
    module Base
      class Definition
        attr_reader :owner, :name, :options

        def initialize(owner, name, options={})
          @owner, @name, @options = owner, name, options
        end

        def for(instance)
          association_class.new(self, instance)
        end

        def define!
          owner.instance_exec(self, &self.class.properties) if self.class.properties
          owner.instance_exec(self, &self.class.methods) if self.class.methods

          self
        end

        def klass
          case options[:class]
          when Class
            options[:class]
          when String
            options[:class].constantize
          else
            name.to_s.classify.constantize
          end
        end

        def singular_name
          name.to_s.singularize
        end

        def polymorphic?
          options[:polymorphic]
        end

        def collection?
          true
        end

        def scope
          klass.scoped.apply_finder_options(scope_options)
        end

        def scope_options
          options.slice(:conditions, :select, :offset, :limit, :order)
        end

        def self.properties
          @properties = Proc.new if block_given?
          @properties
        end

        def self.methods(&block)
          @methods = Proc.new if block_given?
          @methods
        end

      private
        def association_class
          self.class::Association rescue Base::Association
        end
      end
    end
  end
end


text:
package org.mbari.vars.ui.javafx.imgfx;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.control.TextInputDialog;
import javafx.scene.image.ImageView;
import javafx.scene.shape.Shape;
import org.mbari.imgfx.etc.rx.events.AddLocalizationEvent;
import org.mbari.imgfx.etc.rx.events.RemoveLocalizationEvent;
import org.mbari.imgfx.roi.*;
import org.mbari.vars.services.model.Annotation;
import org.mbari.vars.services.model.Association;
import org.mbari.vars.ui.commands.CreateAnnotationAtIndexWithAssociationCmd;
import org.mbari.vars.ui.commands.CreateAssociationsCmd;
import org.mbari.vcr4j.VideoIndex;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

public class AnnotationBuilder {
    private final IFXToolBox toolBox;
    private final BooleanProperty localizeExistingAnnotation = new SimpleBooleanProperty();
    private final BooleanProperty addComment = new SimpleBooleanProperty();

    private final RoiBoundingBox roiBoundingBox = new RoiBoundingBox();
    private final RoiLine roiLine = new RoiLine();
    private final RoiMarker roiMarker = new RoiMarker();
    private final RoiPolygon roiPolygon = new RoiPolygon();

    public AnnotationBuilder(IFXToolBox toolBox) {
        this.toolBox = toolBox;
        init();
    }

    private void init() {
        toolBox.getEventBus()
                .toObserverable()
                .ofType(AddLocalizationEvent.class)
                .subscribe(event -> addNewLocalization(event.localization()));
    }

    private void addNewLocalization(Localization<? extends DataView<? extends Data, ? extends Shape>, ImageView> localization) {
        var image = toolBox.getData().getSelectedImage();
        if (image != null) {
            // If needed, show comment dialog
            String comment = addComment.get() ? showCommentDialog().orElse(null) :
                    null;
            if (localizeExistingAnnotation.get()) {
                var annos = new ArrayList<>(toolBox.getUIToolBox()
                        .getData()
                        .getSelectedAnnotations());
                if (annos.size() == 1) {
                    // Add localization to selected annotation.
                    var annotation = annos.get(0);
                    addToExistingAnnotation(annotation, localization, image.getImageReferenceUuid(), comment);
                } else {
                    // If no annotation is selected, or more than one is
                    // fire a new RemoveLocalizationEvent to trash it.
                    toolBox.getEventBus().publish(new RemoveLocalizationEvent(localization));
                    // TODO show warning dialog to let user know to select one annotation
                }
            } else {
                // Create new annotation and association
                createNewAnnotation(localization, image.getImageReferenceUuid(), comment, image.toVideoIndex());
            }
        }
    }

    private Optional<String> showCommentDialog() {
        var i18n = toolBox.getUIToolBox().getI18nBundle();
        var dialog = new TextInputDialog();
        dialog.setTitle(i18n.getString("ifx.comment.dialog.title"));
        dialog.setHeaderText("ifx.comment.dialog.header");
        dialog.setContentText("ifx.comment.dialog.content");
        return dialog.showAndWait();
    }

    private void showNoAnnotationSelectedDialog() {

    }

    private void addToExistingAnnotation(Annotation annotation,
                                         Localization<? extends DataView<? extends Data, ? extends Shape>, ImageView> localization,
                                         UUID imageReferenceUuid,
                                         String comment) {

        localization.setLabel(annotation.getConcept());
        var association = fromLocalization(localization, imageReferenceUuid, comment);
        if (association != null) {
            var command = new CreateAssociationsCmd(association, List.of(annotation));
            toolBox.getUIToolBox().getEventBus().send(command);
        }

    }

    private void createNewAnnotation(
            Localization<? extends DataView<? extends Data, ? extends Shape>, ImageView> localization,
            UUID imageReferenceUuid,
            String comment,
            VideoIndex videoIndex) {

        var association = fromLocalization(localization, imageReferenceUuid, comment);
        if (association != null) {
            var command = new CreateAnnotationAtIndexWithAssociationCmd(videoIndex,
                    localization.getLabel(),
                    association);
            toolBox.getUIToolBox().getEventBus().send(command);
        }

    }

    private Association fromLocalization(Localization<? extends DataView<? extends Data, ? extends Shape>, ImageView> localization,
                                         UUID imageReferenceUuid,
                                         String comment) {

        var dataView = localization.getDataView();

        if (dataView instanceof MarkerView) {
            var loc = (Localization<MarkerView, ImageView>) localization;
            return roiMarker.fromLocalization(loc, imageReferenceUuid, comment);
        }
        else if (dataView instanceof LineView) {
            var loc = (Localization<LineView, ImageView>) localization;
            return roiLine.fromLocalization(loc, imageReferenceUuid, comment);
        }
        else if (dataView  instanceof RectangleView) {
            var loc = (Localization<RectangleView, ImageView>) localization;
            return roiBoundingBox.fromLocalization(loc, imageReferenceUuid, comment);
        }
        else if (dataView instanceof PolygonView) {
            var loc = (Localization<PolygonView, ImageView>) localization;
            return roiPolygon.fromLocalization(loc, imageReferenceUuid, comment);
        }
        return null;

    }

    public boolean isLocalizeExistingAnnotation() {
        return localizeExistingAnnotation.get();
    }

    public BooleanProperty localizeExistingAnnotationProperty() {
        return localizeExistingAnnotation;
    }

    public void setLocalizeExistingAnnotation(boolean localizeExistingAnnotation) {
        this.localizeExistingAnnotation.set(localizeExistingAnnotation);
    }

    public boolean isAddComment() {
        return addComment.get();
    }

    public BooleanProperty addCommentProperty() {
        return addComment;
    }

    public void setAddComment(boolean addComment) {
        this.addComment.set(addComment);
    }
}


text:
require 'rails_helper'

RSpec.describe "group_pieces/create.html.erb", :type => :view do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
package app;

/**
 * Created by pablo on 4/20/2017.
 */

public class Config {

    // global topic to receive app wide push notifications
    public static final String TOPIC_GLOBAL = "global";

    // broadcast receiver intent filters
    public static final String REGISTRATION_COMPLETE = "registrationComplete";
    public static final String PUSH_NOTIFICATION = "pushNotification";

    // id to handle the notification in the notification tray
    public static final int NOTIFICATION_ID = 100;
    public static final int NOTIFICATION_ID_BIG_IMAGE = 101;

    public static final String SHARED_PREF = "ah_firebase";
}