text:
#include "SelectionScreen.h"
#include "../FileFunctions.h"
#include "../Game.h"
#include "../globals.h"
#include "../MouseHelper.h"
#include "../KeyboardHelper.h"
#include "../ResourceLoader.h"
#include "../Utils.h"
#include "../XmlReader.h"
#include "../CaseInformation/Case.h"
#include "../CaseInformation/CommonCaseResources.h"

#include <stdlib.h>
#include <algorithm>

MLIFont *SelectionScreen::pLargeFont = NULL;
MLIFont *SelectionScreen::pMediumFont = NULL;
MLIFont *SelectionScreen::pSmallFont = NULL;

const int FadeFromBlackDurationMs = 300;
const int SelectorWidth = 248;

SelectionScreen::SelectionScreen(SelectionScreenType type)
{
    pFadeSprite = NULL;

    fadeOpacity = 0;
    pFadeInEase = new LinearEase(1, 0, FadeFromBlackDurationMs);
    pFadeOutEase = new LinearEase(0, 1, FadeFromBlackDurationMs);

    pBackgroundVideo = NULL;

    pSelector = new Selector(193, 76, SelectorWidth, 377);

    pScreenshotBorderSprite = NULL;
    pScreenshotSprite = NULL;
    pScreenshotFullSizeSprite = NULL;

    fullSizeScreenshotFadeOpacity = 0;
    pFullSizeScreenshotFadeInEase = new LinearEase(0, 1, FadeFromBlackDurationMs);
    pFullSizeScreenshotFadeOutEase = new LinearEase(1, 0, FadeFromBlackDurationMs);

    lastCaseTitle = "";
    lastCaseUuid = "";

    selectionVersionIsCompatible = true;
    selectionRequiredVersion = Version(0, 0, 0);
    selectionLanguageIsCompatible = true;
    selectionSupportedLanguages = list<string>();

    caseTitle = "";
    pDividerSprite = NULL;

    pStartCaseButton = NULL;
    pSelectCaseButton = NULL;
    pSaveButton = NULL;
    pLoadButton = NULL;
    pDeleteButton = NULL;
    pBackButton = NULL;

    this->type = type;

    finishedLoadingAnimations = false;
    caseSelected = false;
    canDelete = false;

    pDeleteConfirmOverlay = NULL;
    pEnterSaveNameOverlay = NULL;
    pIncompatibleCaseNotificationOverlay = NULL;

    pDescriptionWidget = NULL;

    EventProviders::GetTextButtonEventProvider()->ClearListener(this);
    EventProviders::GetPromptOverlayEventProvider()->ClearListener(this);
    EventProviders::GetSelectorEventProvider()->ClearListener(this);
    EventProviders::GetTextButtonEventProvider()->RegisterListener(this);
    EventProviders::GetPromptOverlayEventProvider()->RegisterListener(this);
    EventProviders::GetSelectorEventProvider()->RegisterListener(this);
}

SelectionScreen::~SelectionScreen()
{
    delete pFadeSprite;
    pFadeSprite = NULL;

    delete pFadeInEase;
    pFadeInEase = NULL;
    delete pFadeOutEase;
    pFadeOutEase = NULL;

    delete pBackgroundVideo;
    pBackgroundVideo = NULL;

    delete pSelector;
    pSelector = NULL;

    delete pFullSizeScreenshotFadeInEase;
    pFullSizeScreenshotFadeInEase = NULL;
    delete pFullSizeScreenshotFadeOutEase;
    pFullSizeScreenshotFadeOutEase = NULL;

    delete pScreenshotBorderSprite;
    pScreenshotBorderSprite = NULL;
    delete pDividerSprite;
    pDividerSprite = NULL;

    delete pStartCaseButton;
    pStartCaseButton = NULL;
    delete pSelectCaseButton;
    pSelectCaseButton = NULL;
    delete pSaveButton;
    pSaveButton = NULL;
    delete pLoadButton;
    pLoadButton = NULL;
    delete pDeleteButton;
    pDeleteButton = NULL;
    delete pBackButton;
    pBackButton = NULL;

    delete pDeleteConfirmOverlay;
    pDeleteConfirmOverlay = NULL;
    delete pEnterSaveNameOverlay;
    pEnterSaveNameOverlay = NULL;
    delete pIncompatibleCaseNotificationOverlay;
    pIncompatibleCaseNotificationOverlay = NULL;

    delete pDescriptionWidget;
    pDescriptionWidget = NULL;

    EventProviders::GetTextButtonEventProvider()->ClearListener(this);
    EventProviders::GetPromptOverlayEventProvider()->ClearListener(this);
    EventProviders::GetSelectorEventProvider()->ClearListener(this);
}

void SelectionScreen::LoadResources()
{
    EnsureFonts();

    MLIFont *pTitleScreenFont = CommonCaseResources::GetInstance()->GetFontManager()->GetFontFromId("MenuFont");
    MLIFont *pStartFont = CommonCaseResources::GetInstance()->GetFontManager()->GetFontFromId("SelectionScreen/StartFont");

    finishedLoadingAnimations = false;

    delete pFadeSprite;
    pFadeSprite = ResourceLoader::GetInstance()->LoadImage("image/TitleScreen/FadeInBackground.png");

    delete pBackgroundVideo;
    pBackgroundVideo = new Video(true /* shouldLoop */);
    pBackgroundVideo->SetVideoAttributes("video/CaseSelectionBackground.mov", 4, 167, 960, 540);
    pBackgroundVideo->LoadFile();

    delete pScreenshotBorderSprite;
    pScreenshotBorderSprite = ResourceLoader::GetInstance()->LoadImage("image/CaseSelectionScreen/ScreenshotBorder.png");

    delete pDividerSprite;
    pDividerSprite = ResourceLoader::GetInstance()->LoadImage("image/CaseSelectionScreen/RightDivider.png");

    delete pStartCaseButton;
    pStartCaseButton = new TextButton("SelectionScreen/StartCaseText", pStartFont);
    pStartCaseButton->SetX(656, HAlignmentCenter);
    pStartCaseButton->SetY(426);

    delete pSelectCaseButton;
    pSelectCaseButton = new TextButton("SelectionScreen/SelectCaseText", pStartFont);
    pSelectCaseButton->SetX(659, HAlignmentCenter);
    pSelectCaseButton->SetY(426);
    pSelectCaseButton->SetClickSoundEffect("ButtonClick3");

    delete pSaveButton;
    pSaveButton = new TextButton("SelectionScreen/SaveGameText", pStartFont);
    pSaveButton->SetX(660, HAlignmentCenter);
    pSaveButton->SetY(426);

    delete pLoadButton;
    pLoadButton = new TextButton("SelectionScreen/LoadGameText", pStartFont);
    pLoadButton->SetX(660, HAlignmentCenter);
    pLoadButton->SetY(426);

    delete pDeleteButton;
    pDeleteButton = new TextButton("SelectionScreen/DeleteGameText", pStartFont);
    pDeleteButton->SetX(644, HAlignmentCenter);
    pDeleteButton->SetY(365);

    delete pBackButton;
    pBackButton = new TextButton("SelectionScreen/BackText", pTitleScreenFont);
    pBackButton->SetX(932, HAlignmentRight);
    pBackButton->SetY(488);
    pBackButton->SetClickSoundEffect("ButtonClick4");

    delete pDeleteConfirmOverlay;
    pDeleteConfirmOverlay = new PromptOverlay("SelectionScreen/DeleteConfirmationText", false /* allowsTextEntry */);
    pDeleteConfirmOverlay->AddButton("SelectionScreen/YesText");
    pDeleteConfirmOverlay->AddButton("SelectionScreen/NoText");
    pDeleteConfirmOverlay->FinalizeButtons();

    delete pEnterSaveNameOverlay;
    pEnterSaveNameOverlay = new PromptOverlay("SelectionScreen/SaveNamePromptText", true /* allowsTextEntry */);
    pEnterSaveNameOverlay->SetMaxPixelWidth(SelectorWidth, CommonCaseResources::GetInstance()->GetFontManager()->GetFontFromId("HandwritingLargeFont"));

    delete pIncompatibleCaseNotificationOverlay;
    pIncompatibleCaseNotificationOverlay = new PromptOverlay("", false /* allowsTextEntry */);
    pIncompatibleCaseNotificationOverlay->AddButton("SelectionScreen/OKText");
    pIncompatibleCaseNotificationOverlay->FinalizeButtons();

    delete pDescriptionWidget;
    pDescriptionWidget = new TextWidget("", pSmallFont, Color(1.0, 0.0, 0.0, 0.0), HAlignmentCenter, VAlignmentTop);
    pDescriptionWidget->SetX(649);
    pDescriptionWidget->SetY(274);
    pDescriptionWidget->SetWidth(248);

    finishedLoadingAnimations = true;
}

void SelectionScreen::UnloadResources()
{
    finishedLoadingAnimations = false;

    delete pFadeSprite;
    pFadeSprite = NULL;

    delete pBackgroundVideo;
    pBackgroundVideo = NULL;

    delete pScreenshotBorderSprite;
    pScreenshotBorderSprite = NULL;
    delete pDividerSprite;
    pDividerSprite = NULL;

    delete pStartCaseButton;
    pStartCaseButton = NULL;
    delete pSelectCaseButton;
    pSelectCaseButton = NULL;
    delete pSaveButton;
    pSaveButton = NULL;
    delete pLoadButton;
    pLoadButton = NULL;
    delete pDeleteButton;
    pDeleteButton = NULL;
    delete pBackButton;
    pBackButton = NULL;

    delete pDescriptionWidget;
    pDescriptionWidget = NULL;
}

void SelectionScreen::Init()
{
    MLIScreen::Init();

    fadeOpacity = 1;
    pFadeInEase->Begin();
    pFadeOutEase->Reset();

    while (!finishedLoadingAnimations)
    {
        SDL_Delay(1);
    }

    pBackgroundVideo->Begin();
    pDeleteConfirmOverlay->Reset();
    pEnterSaveNameOverlay->Reset();
    pIncompatibleCaseNotificationOverlay->Reset();

    caseSelected = false;
    canDelete = false;

    // If we're loading or selecting a case, we'll allow the player to select whichever case they want.
    // On the other hand, if we're saving, then we'll just skip straight to creating a save file -
    // it makes no sense to have the player select a case in this situation.
    if (type == SelectionScreenTypeSaveGame)
    {
        lastCaseUuid = Case::GetInstance()->GetUuid();
        gCaseFilePath = Case::GetInstance()->GetFilePath();
        selectionVersionIsCompatible = true;
        selectionRequiredVersion = Version(0, 0, 0);
        selectionLanguageIsCompatible = true;
        selectionSupportedLanguages = list<string>();
        OnButtonClicked(pSelectCaseButton);
    }
    else
    {
        pSelector->PopulateWithCases(type == SelectionScreenTypeLoadGame /* requireSaveFilesExist */);
    }
}

void SelectionScreen::Update(int delta)
{
    if (!finishedLoadingAnimations)
    {
        return;
    }

    if (!pFadeSprite->IsReady() ||
        !pBackgroundVideo->IsReady() ||
        !pDividerSprite->IsReady() ||
        !pStartCaseButton->IsReady() ||
        !pSelectCaseButton->IsReady() ||
        !pSaveButton->IsReady() ||
        !pLoadButton->IsReady() ||
        !pDeleteButton->IsReady() ||
        !pBackButton->IsReady())
    {
        return;
    }

    if (!pFadeInEase->GetIsFinished())
    {
        pFadeInEase->Update(delta);
        fadeOpacity = pFadeInEase->GetCurrentValue();
    }
    else if (!pFadeOutEase->GetIsFinished())
    {
        pFadeOutEase->Update(delta);
        fadeOpacity = pFadeOutEase->GetCurrentValue();
    }

    if (pFadeOutEase->GetIsFinished())
    {
        if (nextScreenId == GAME_SCREEN_ID)
        {
            Game::GetInstance()->PrepareGameMode();
        }

        isFinished = true;
        return;
    }

    pBackgroundVideo->Update(delta);

    if (pFadeOutEase->GetIsStarted())
    {
        return;
    }

    pSelector->UpdateAnimation(delta);

    if (pFullSizeScreenshotFadeInEase->GetIsStarted())
    {
        pFullSizeScreenshotFadeInEase->Update(delta);
        fullSizeScreenshotFadeOpacity = pFullSizeScreenshotFadeInEase->GetCurrentValue();

        if (pFullSizeScreenshotFadeInEase->GetIsFinished())
        {
            pFullSizeScreenshotFadeInEase->Reset();
        }
    }
    else if (pFullSizeScreenshotFadeOutEase->GetIsStarted())
    {
        pFullSizeScreenshotFadeOutEase->Update(delta);
        fullSizeScreenshotFadeOpacity = pFullSizeScreenshotFadeOutEase->GetCurrentValue();

        if (pFullSizeScreenshotFadeOutEase->GetIsFinished())
        {
            pFullSizeScreenshotFadeOutEase->Reset();
        }
    }

    if (pDeleteConfirmOverlay->GetIsShowing())
    {
        pDeleteConfirmOverlay->Update(delta);
        return;
    }
    else if (pEnterSaveNameOverlay->GetIsShowing())
    {
        pEnterSaveNameOverlay->Update(delta);
        return;
    }
    else if (pIncompatibleCaseNotificationOverlay->GetIsShowing())
    {
        pIncompatibleCaseNotificationOverlay->Update(delta);
        return;
    }

    if (fullSizeScreenshotFadeOpacity == 1)
    {
        MouseHelper::SetCursorType(CursorTypeLook);

        if (MouseHelper::ClickedAnywhere() || KeyboardHelper::ClickPressed())
        {
            pFullSizeScreenshotFadeOutEase->Begin();
            playSound("ButtonClick4");
            MouseHelper::HandleClick();
            return;
        }

        return;
    }
    else if (fullSizeScreenshotFadeOpacity == 0 && pScreenshotFullSizeSprite != NULL)
    {
        RectangleWH screenshotRect = RectangleWH(526, 77, pScreenshotSprite->width, pScreenshotSprite->height);

        if (MouseHelper::MouseOverRect(screenshotRect) ||
            MouseHelper::MouseDownOnRect(screenshotRect) ||
            MouseHelper::ClickedOnRect(screenshotRect))
        {
            MouseHelper::SetCursorType(CursorTypeLook);
        }

        if (MouseHelper::ClickedOnRect(screenshotRect))
        {
            pFullSizeScreenshotFadeInEase->Begin();
            playSound("ButtonClick1");
            MouseHelper::HandleClick();
            return;
        }
    }
    else if (fullSizeScreenshotFadeOpacity > 0 && fullSizeScreenshotFadeOpacity < 1)
    {
        MouseHelper::SetCursorType(CursorTypeLook);
        return;
    }

    pSelector->UpdateState();

    if (!caseSelected)
    {
        if (type == SelectionScreenTypeCaseSelection)
        {
            pStartCaseButton->Update(delta);
        }
        else
        {
            pSelectCaseButton->Update(delta);
        }
    }
    else if (type == SelectionScreenTypeSaveGame)
    {
        pSaveButton->Update(delta);
    }
    else if (type == SelectionScreenTypeLoadGame && pSelector->GetSection(0)->GetCount() > 0)
    {
        pLoadButton->Update(delta);
    }

    if (canDelete)
    {
        pDeleteButton->Update(delta);
    }

    pBackButton->Update(delta);
}

void SelectionScreen::Draw()
{
    if (!finishedLoadingAnimations)
    {
        return;
    }

    if (!pFadeSprite->IsReady() ||
        !pDividerSprite->IsReady() ||
        !pStartCaseButton->IsReady() ||
        !pSelectCaseButton->IsReady() ||
        !pSaveButton->IsReady() ||
        !pLoadButton->IsReady() ||
        !pDeleteButton->IsReady() ||
        !pBackButton->IsReady())
    {
        return;
    }

    EnsureFonts();

    pBackgroundVideo->Draw(Vector2(0, 0));
    pSelector->Draw();

    pScreenshotBorderSprite->Draw(Vector2(525, 76));
    pScreenshotSprite->Draw(Vector2(526, 77));
    pMediumFont->Draw(caseTitle, Vector2(649 - pMediumFont->GetWidth(caseTitle) / 2, 229), Color(1.0, 0.0, 0.0, 0.0));
    pDividerSprite->Draw(Vector2(576, 265));

    pDescriptionWidget->Draw();

    if (!caseSelected)
    {
        if (type == SelectionScreenTypeCaseSelection)
        {
            pStartCaseButton->Draw();
        }
        else
        {
            pSelectCaseButton->Draw();
        }
    }
    else if (type == SelectionScreenTypeSaveGame)
    {
        pSaveButton->Draw();
    }
    else if (type == SelectionScreenTypeLoadGame && pSelector->GetSection(0)->GetCount() > 0)
    {
        pLoadButton->Draw();
    }

    if (canDelete)
    {
        pDeleteButton->Draw();
    }

    pBackButton->Draw();

    if (pScreenshotFullSizeSprite != NULL && fullSizeScreenshotFadeOpacity > 0)
    {
        pScreenshotFullSizeSprite->Draw(Vector2(0, 0), Color(fullSizeScreenshotFadeOpacity, 1, 1, 1));
    }

    if (pDeleteConfirmOverlay->GetIsShowing())
    {
        pDeleteConfirmOverlay->Draw();
    }
    else if (pEnterSaveNameOverlay->GetIsShowing())
    {
        pEnterSaveNameOverlay->Draw();
    }
    else if (pIncompatibleCaseNotificationOverlay->GetIsShowing())
    {
        pIncompatibleCaseNotificationOverlay->Draw();
    }

    pFadeSprite->Draw(Vector2(0, 0), Color(fadeOpacity, 1, 1, 1));
}

void SelectionScreen::OnSelectorSelectionChanged(Selector *pSender, SelectorItem *pSelectedItem)
{
    canDelete = false;
    selectionVersionIsCompatible = true;
    selectionRequiredVersion = Version(0, 0, 0);
    selectionLanguageIsCompatible = true;
    selectionSupportedLanguages = list<string>();

    if (pSender == pSelector)
    {
        CaseSelectorItem *pCaseSelectorItem = dynamic_cast<CaseSelectorItem *>(pSelectedItem);
        SaveLoadSelectorItem *pSaveLoadSelectorItem = dynamic_cast<SaveLoadSelectorItem *>(pSelectedItem);

        if (pCaseSelectorItem != NULL || pSaveLoadSelectorItem != NULL)
        {
            Image *pItemScreenshotSprite = NULL;
            Image *pItemFullScreenScreenshotSprite = NULL;
            string itemDescription = "";
            string itemFilePath = "";
            string itemSaveName = "";

            if (pCaseSelectorItem != NULL)
            {
                pItemScreenshotSprite = pCaseSelectorItem->GetScreenshotSprite();
                pItemFullScreenScreenshotSprite = pCaseSelectorItem->GetScreenshotFullSizeSprite();
                itemDescription = pCaseSelectorItem->GetCaseDescription();
                itemFilePath = pCaseSelectorItem->GetCaseFilePath();

                gCaseFilePath = itemFilePath;
                caseTitle = pCaseSelectorItem->GetCaseTitle();

                lastCaseTitle = pCaseSelectorItem->GetCaseTitle();
                lastCaseUuid = pCaseSelectorItem->GetCaseUuid();

                selectionVersionIsCompatible = pCaseSelectorItem->GetIsVersionCompatible();
                selectionRequiredVersion = pCaseSelectorItem->GetRequiredVersion();
                selectionLanguageIsCompatible = pCaseSelectorItem->GetIsLanguageCompatible();
                selectionSupportedLanguages = pCaseSelectorItem->GetSupportedLanguages();
            }
            else if (pSaveLoadSelectorItem != NULL)
            {
                pItemScreenshotSprite = pSaveLoadSelectorItem->GetScreenshotSprite();
                pItemFullScreenScreenshotSprite = NULL;
                itemDescription = pSaveLoadSelectorItem->GetDescription();
                itemFilePath = pSaveLoadSelectorItem->GetFilePath();
                itemSaveName = pSaveLoadSelectorItem->GetSaveName();
                canDelete = !IsAutosave(itemFilePath);
            }

            EnsureFonts();

            pScreenshotSprite = pItemScreenshotSprite;
            pScreenshotFullSizeSprite = pItemFullScreenScreenshotSprite;

            if (pScreenshotFullSizeSprite == NULL)
            {
                fullSizeScreenshotFadeOpacity = 0;
                pFullSizeScreenshotFadeInEase->Reset();
                pFullSizeScreenshotFadeOutEase->Reset();
            }

            pDescriptionWidget->SetText(itemDescription);
            pDescriptionWidget->WrapText();

            saveName = itemSaveName;
            filePath = itemFilePath;
            fileExtension = "";
        }
        else
        {
            NewSaveSelectorItem *pNewSaveSelectorItem = dynamic_cast<NewSaveSelectorItem *>(pSelectedItem);

            if (pNewSaveSelectorItem != NULL)
            {
                pScreenshotSprite = pNewSaveSelectorItem->GetScreenshot();
                pScreenshotFullSizeSprite = pNewSaveSelectorItem->GetScreenshotFullSize();

                if (pScreenshotFullSizeSprite == NULL)
                {
                    fullSizeScreenshotFadeOpacity = 0;
                    pFullSizeScreenshotFadeInEase->Reset();
                    pFullSizeScreenshotFadeOutEase->Reset();
                }

                caseTitle = lastCaseTitle;

                pDescriptionWidget->SetTextId("SelectionScreen/NewSaveFileText");

                string fileName = GetSaveFolderPathForCase(lastCaseUuid);

                char buf[256] = { '\0' };
                snprintf(buf, 256, gpLocalizableContent->GetText("SelectionScreen/DefaultNewSaveNameText").c_str(), pSender->GetSection(0)->GetCount());

                saveName = string(buf);
                filePath = fileName;
                fileExtension = ".sav";
            }
        }
    }
}

void SelectionScreen::OnButtonClicked(TextButton *pSender)
{
    if (pSender == pStartCaseButton)
    {
        if (SelectedCaseIsCompatible())
        {
            gCaseFilePath = filePath;
            nextScreenId = GAME_SCREEN_ID;
            CommonCaseResources::GetInstance()->GetAudioManager()->StopCurrentBgm(false /* isInstant */);
            pFadeOutEase->Begin();
        }
        else
        {
            DisplayIncompatibilityMessage();
        }
    }
    else if (pSender == pSelectCaseButton)
    {
        if (SelectedCaseIsCompatible())
        {
            caseSelected = true;
            vector<string> filePaths = GetSaveFilePathsForCase(lastCaseUuid);

            pSelector->Reset();
            SelectorSection *pSection = new SelectorSection("SelectionScreen/SaveFilesText");

            if (type == SelectionScreenTypeSaveGame && ResourceLoader::GetInstance()->LoadTemporaryCase(gCaseFilePath))
            {
                Image *pImageSprite = NULL;
                Image *pImageFullSizeSprite = NULL;

                XmlReader reader("caseMetadata.xml");

                reader.StartElement("CaseMetadata");
                lastCaseTitle = reader.ReadTextElement("Title");
                pImageSprite = IsCaseCompleted(lastCaseUuid) ? reader.ReadPngElement("ImageAfterCompletion") : reader.ReadPngElement("ImageBeforeCompletion");

                if (!IsCaseCompleted(lastCaseUuid) && reader.ElementExists("ImageBeforeCompletionFullSize"))
                {
                    pImageFullSizeSprite = reader.ReadPngElement("ImageBeforeCompletionFullSize");
                }
                else if (IsCaseCompleted(lastCaseUuid) && reader.ElementExists("ImageAfterCompletionFullSize"))
                {
                    pImageFullSizeSprite = reader.ReadPngElement("ImageAfterCompletionFullSize");
                }

                reader.EndElement();

                ResourceLoader::GetInstance()->UnloadTemporaryCase();

                pSection->AddItem(new NewSaveSelectorItem(pImageSprite, pImageFullSizeSprite));
            }

            vector<SaveLoadSelectorItem *> selectorItemList;

            for (unsigned int i = 0; i < filePaths.size(); i++)
            {
                string filePath = filePaths[i];

                // If we're saving, then we should not allow the player to save to the autosave slot.
                if (type == SelectionScreenTypeSaveGame && IsAutosave(filePath))
                {
                    continue;
                }

                XmlReader reader(filePath.c_str());

                reader.StartElement("CaseMetadata");

                // If this is the autosave file, then we'll return the localized version of "Autosave" as its name
                // instead of the save name in the file.
                string saveName = IsAutosave(filePath) ? gpLocalizableContent->GetText("SelectionScreen/AutosaveText") : reader.ReadTextElement("SaveName");

                time_t timestamp = (time_t)reader.ReadIntElement("Timestamp");
                struct tm * timeinfo;

                timeinfo = localtime(&timestamp);

                char buf[256];
                strftime(buf, sizeof(buf), gpLocalizableContent->GetText("SelectionScreen/SaveFileDateTimeDisplayFormattingText").c_str(), timeinfo);

                string description = string(buf);

                Image *pSprite = reader.ReadPngElement("Screenshot");

                reader.EndElement();

                selectorItemList.push_back(
                    new SaveLoadSelectorItem(
                        saveName,
                        pSprite,
                        timestamp,
                        description,
                        filePath));
            }

            sort(selectorItemList.begin(), selectorItemList.end(), SaveLoadSelectorItem::CompareByTimestampDescending);

            for (unsigned int i = 0; i < selectorItemList.size(); i++)
            {
                pSection->AddItem(selectorItemList[i]);
            }

            pSelector->AddSection(pSection);
            pSelector->Init();
        }
        else
        {
            DisplayIncompatibilityMessage();
        }
    }
    else if (pSender == pSaveButton)
    {
        pEnterSaveNameOverlay->Begin(saveName);
    }
    else if (pSender == pLoadButton)
    {
        if (Case::GetInstance()->IsReady())
        {
            if (Case::GetInstance()->GetUuid() == lastCaseUuid)
            {
                Case::GetInstance()->LoadFromSaveFile(filePath);
                gCaseFilePath = "";
            }
            else
            {
                Case::GetInstance()->SetIsFinished(true);
                gSaveFilePath = filePath;
            }
        }
        else
        {
            gSaveFilePath = filePath;
            nextScreenId = GAME_SCREEN_ID;
        }

        pFadeOutEase->Begin();
    }
    else if (pSender == pDeleteButton)
    {
        pDeleteConfirmOverlay->Begin();
    }
    else if (pSender == pBackButton)
    {
        // We don't allow the selection of a case when saving, so we'll want to immediately exit in that case.
        if (caseSelected && type != SelectionScreenTypeSaveGame)
        {
            caseSelected = false;
            pSelector->PopulateWithCases(true /* requireSaveFilesExist */);
        }
        else
        {
            nextScreenId = TITLE_SCREEN_ID;
            gCaseFilePath = "";
            pFadeOutEase->Begin();
        }
    }
}

void SelectionScreen::OnPromptOverlayValueReturned(PromptOverlay *pSender, const string &value)
{
    if (pSender == pDeleteConfirmOverlay && value == gpLocalizableContent->GetText("SelectionScreen/YesText"))
    {
        remove(filePath.c_str());
        pSelector->DeleteCurrentItem();

        if (pSelector->GetSectionCount() == 0)
        {
            // If we just deleted the last save file,
            // then we should exit out of the save file selection screen.
            OnButtonClicked(pBackButton);
        }
    }
    else if (pSender == pEnterSaveNameOverlay && value.length() > 0)
    {
        Case::GetInstance()->SaveToSaveFile(filePath, fileExtension, value);
        pFadeOutEase->Begin();
        gCaseFilePath = "";
        pEnterSaveNameOverlay->KeepOpen();
    }
}

void SelectionScreen::EnsureFonts()
{
    if (pLargeFont == NULL)
    {
        pLargeFont = CommonCaseResources::GetInstance()->GetFontManager()->GetFontFromId("HandwritingLargeFont");
    }

    if (pMediumFont == NULL)
    {
        pMediumFont = CommonCaseResources::GetInstance()->GetFontManager()->GetFontFromId("HandwritingMediumFont");
    }

    if (pSmallFont == NULL)
    {
        pSmallFont = CommonCaseResources::GetInstance()->GetFontManager()->GetFontFromId("HandwritingSmallFont");
    }
}

bool SelectionScreen::SelectedCaseIsCompatible()
{
    return selectionVersionIsCompatible && selectionLanguageIsCompatible;
}

void SelectionScreen::DisplayIncompatibilityMessage()
{
    if (!selectionVersionIsCompatible)
    {
        char promptOverlayText[1024];
        snprintf(promptOverlayText, 1024, gpLocalizableContent->GetText("SelectionScreen/CaseVersionIncompatibleText").c_str(), ((string)gVersion).c_str(), ((string)selectionRequiredVersion).c_str());

        pIncompatibleCaseNotificationOverlay->SetHeaderText(promptOverlayText);
        pIncompatibleCaseNotificationOverlay->Begin();
    }
    else if (!selectionLanguageIsCompatible)
    {
        string supportedLanguages;

        for (string languageId : selectionSupportedLanguages)
        {
            supportedLanguages += languageId + " ";
        }

        // Remove the last space.
        supportedLanguages = supportedLanguages.substr(0, supportedLanguages.length() - 1);

        char promptOverlayText[1024];
        snprintf(promptOverlayText, 1024, gpLocalizableContent->GetText("SelectionScreen/CaseLanguageIncompatibleText").c_str(), ResourceLoader::GetInstance()->GetSelectedLanguage().c_str(), supportedLanguages.c_str());

        pIncompatibleCaseNotificationOverlay->SetHeaderText(promptOverlayText);
        pIncompatibleCaseNotificationOverlay->Begin();
    }
    else
    {
        ThrowException("Unknown reason for the case not being compatible.");
    }
}


text:
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname(dirname($vendorDir));

return array(
    'yii\\swiftmailer\\' => array($vendorDir . '/yiisoft/yii2-swiftmailer'),
    'yii\\jui\\' => array($vendorDir . '/yiisoft/yii2-jui'),
    'yii\\imagine\\' => array($vendorDir . '/yiisoft/yii2-imagine'),
    'yii\\gii\\' => array($vendorDir . '/yiisoft/yii2-gii'),
    'yii\\faker\\' => array($vendorDir . '/yiisoft/yii2-faker'),
    'yii\\debug\\' => array($vendorDir . '/yiisoft/yii2-debug'),
    'yii\\composer\\' => array($vendorDir . '/yiisoft/yii2-composer'),
    'yii\\codeception\\' => array($vendorDir . '/yiisoft/yii2-codeception'),
    'yii\\bootstrap\\' => array($vendorDir . '/yiisoft/yii2-bootstrap'),
    'yii\\' => array($vendorDir . '/yiisoft/yii2'),
    'rmrevin\\yii\\fontawesome\\' => array($vendorDir . '/rmrevin/yii2-fontawesome'),
    'nenad\\passwordStrength\\' => array($vendorDir . '/nenad/yii2-password-strength'),
    'nenad\\' => array($vendorDir . '/nenad/yii2-widgets-base', $vendorDir . '/nenad/yii2-strength-meter'),
    'mihaildev\\ckeditor\\' => array($vendorDir . '/mihaildev/yii2-ckeditor'),
    'kartik\\tree\\' => array($vendorDir . '/kartik-v/yii2-tree-manager'),
    'kartik\\sortable\\' => array($vendorDir . '/kartik-v/yii2-sortable'),
    'kartik\\slider\\' => array($vendorDir . '/kartik-v/yii2-slider'),
    'kartik\\rating\\' => array($vendorDir . '/kartik-v/yii2-widget-rating'),
    'kartik\\plugins\\fileinput\\' => array($vendorDir . '/kartik-v/bootstrap-fileinput'),
    'kartik\\form\\' => array($vendorDir . '/kartik-v/yii2-widget-activeform'),
    'kartik\\file\\' => array($vendorDir . '/kartik-v/yii2-widget-fileinput'),
    'kartik\\base\\' => array($vendorDir . '/kartik-v/yii2-krajee-base'),
    'dosamigos\\ckeditor\\' => array($vendorDir . '/2amigos/yii2-ckeditor-widget/src'),
    'dmstr\\' => array($vendorDir . '/dmstr/yii2-adminlte-asset'),
    'creocoder\\nestedsets\\' => array($vendorDir . '/creocoder/yii2-nested-sets/src'),
    'cebe\\markdown\\' => array($vendorDir . '/cebe/markdown'),
    'Tinify\\' => array($vendorDir . '/tinify/tinify/lib/Tinify'),
    'Faker\\' => array($vendorDir . '/fzaninotto/faker/src/Faker'),
    'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'),
);

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.2"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Hardware Abstraction Layer (HAL)</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Hardware Abstraction Layer (HAL)

GPIO
CAT1 (PSoC™ 6) Implementation Specific

Interrupt Priorities

In CAT1 & CAT2 (PSoC™ 6/4), each GPIO port has a single IRQ line. Hence, there can only be a single interrupt handler and priority set at the hardware level. The HAL tracks any interrupt handler that is registered through cyhal_gpio_register_callback separately so it can run the appropriate pin specific callback anyway. However, the HAL will take over the interrupt for the port. Additionally, it cannot do anything about the priority and all pins on the port will share the last priority set via cyhal_gpio_enable_event. for a specific pin on a port will apply to the all the pins in that pin's port. If multiple pins on the same port are set at different priorities, the priority that the last pin is set to will be applied to all pins used on that port.

Interconnect

In CAT1 & CAT2 (PSoC™ 6/4) only a subset of pins available on a board are connected to input triggers. Another subset is connected to output triggers. Check the appropriate file for your board in pin_packages/ to determine what pins can be used. A particular pin can have 0 or 1 input triggers and 0 or 1 output triggers. Input triggers to a pin are used to clear/set the GPIO pins output. An output trigger on a pin is activated when the pins GPIO input is set.


text:
/// <reference path="../_references.ts"/>

module powerbi.visuals.sampleDataViews {
    import DataViewTransform = powerbi.data.DataViewTransform;

    export class SalesByDayOfWeekData extends SampleDataViews implements ISampleDataViewsMethods {

        public name: string = "SalesByDayOfWeekData";
        public displayName: string = "Sales by day of week";

        public visuals: string[] = ['comboChart',
            'dataDotClusteredColumnComboChart',
            'dataDotStackedColumnComboChart',
            'lineStackedColumnComboChart',
            'lineClusteredColumnComboChart',
            'asterPlot',
            'aquarium',
            'asterPlot',
            'radarChart'
        ];

        private sampleData1 = [
            [742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34, 570921.34],
            [123455.43, 40566.43, 200457.78, 5000.49, 320000.57, 450000.34, 140832.67]
        ];

        private sampleMin1: number = 30000;
        private sampleMax1: number = 1000000;

        private sampleData2 = [
            [31, 17, 24, 30, 37, 40, 12],
            [30, 35, 20, 25, 32, 35, 15]
        ];

        private sampleMin2: number = 10;
        private sampleMax2: number = 45;

        public getDataViews(): DataView[] {
            //first dataView - Sales by day of week
            var fieldExpr = powerbi.data.SQExprBuilder.fieldExpr({ column: { schema: 's', entity: "table1", name: "day of week" } });

            var categoryValues = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
            var categoryIdentities = categoryValues.map(function (value) {
                var expr = powerbi.data.SQExprBuilder.equal(fieldExpr, powerbi.data.SQExprBuilder.text(value));
                return powerbi.data.createDataViewScopeIdentity(expr);
            });

            // Metadata, describes the data columns, and provides the visual with hints
            // so it can decide how to best represent the data
            var dataViewMetadata: powerbi.DataViewMetadata = {
                columns: [
                    {
                        displayName: 'Day',
                        queryName: 'Day',
                        type: powerbi.ValueType.fromDescriptor({ text: true })
                    },
                    {
                        displayName: 'Previous week sales',
                        isMeasure: true,
                        format: "$0,000.00",
                        queryName: 'sales1',
                        type: powerbi.ValueType.fromDescriptor({ numeric: true }),
                        objects: { dataPoint: { fill: { solid: { color: 'purple' } } } },
                    },
                    {
                        displayName: 'This week sales',
                        isMeasure: true,
                        format: "$0,000.00",
                        queryName: 'sales2',
                        type: powerbi.ValueType.fromDescriptor({ numeric: true })
                    }
                ]
            };

            var columns = [
                {
                    source: dataViewMetadata.columns[1],
                    // Sales Amount for 2014
                    values: this.sampleData1[0],
                },
                {
                    source: dataViewMetadata.columns[2],
                    // Sales Amount for 2015
                    values: this.sampleData1[1],
                }
            ];

            var dataValues: DataViewValueColumns = DataViewTransform.createValueColumns(columns);
            var tableDataValues = categoryValues.map(function (dayName, idx) {
                return [dayName, columns[0].values[idx], columns[1].values[idx]];
            });
            //first dataView - Sales by day of week END

            //second dataView - Temperature by day of week
            var fieldExprTemp = powerbi.data.SQExprBuilder.fieldExpr({ column: { schema: 's', entity: "table2", name: "day of week" } });

            var categoryValuesTemp = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
            var categoryIdentitiesTemp = categoryValuesTemp.map(function (value) {
                var exprTemp = powerbi.data.SQExprBuilder.equal(fieldExprTemp, powerbi.data.SQExprBuilder.text(value));
                return powerbi.data.createDataViewScopeIdentity(exprTemp);
            });

            // Metadata, describes the data columns, and provides the visual with hints
            // so it can decide how to best represent the data
            var dataViewMetadataTemp: powerbi.DataViewMetadata = {
                columns: [
                    {
                        displayName: 'Day',
                        queryName: 'Day',
                        type: powerbi.ValueType.fromDescriptor({ text: true })
                    },
                    {
                        displayName: 'Previous week temperature',
                        isMeasure: true,
                        queryName: 'temp1',
                        type: powerbi.ValueType.fromDescriptor({ numeric: true }),
                        //objects: { dataPoint: { fill: { solid: { color: 'purple' } } } },
                    },
                    {
                        displayName: 'This week temperature',
                        isMeasure: true,
                        queryName: 'temp2',
                        type: powerbi.ValueType.fromDescriptor({ numeric: true })
                    }
                ]
            };

            var columnsTemp = [
                {
                    source: dataViewMetadataTemp.columns[1],
                    // temperature prev week
                    values: this.sampleData2[0],
                },
                {
                    source: dataViewMetadataTemp.columns[2],
                    // temperature this week
                    values: this.sampleData2[1],
                }
            ];

            var dataValuesTemp: DataViewValueColumns = DataViewTransform.createValueColumns(columnsTemp);
            var tableDataValuesTemp = categoryValuesTemp.map(function (dayName, idx) {
                return [dayName, columnsTemp[0].values[idx], columnsTemp[1].values[idx]];
            });
            //first dataView - Sales by day of week END
            return [{
                metadata: dataViewMetadata,
                categorical: {
                    categories: [{
                        source: dataViewMetadata.columns[0],
                        values: categoryValues,
                        identity: categoryIdentities,
                    }],
                    values: dataValues
                },
                table: {
                    rows: tableDataValues,
                    columns: dataViewMetadata.columns,
                }
            },
            {
                metadata: dataViewMetadataTemp,
                categorical: {
                    categories: [{
                        source: dataViewMetadataTemp.columns[0],
                        values: categoryValuesTemp,
                        identity: categoryIdentitiesTemp,
                    }],
                    values: dataValuesTemp
                },
                table: {
                    rows: tableDataValuesTemp,
                    columns: dataViewMetadataTemp.columns,
                }
            }];
        }

        public randomize(): void {

            this.sampleData1 = this.sampleData1.map((item) => {
                return item.map(() => this.getRandomValue(this.sampleMin1, this.sampleMax1));
            });

            this.sampleData2 = this.sampleData2.map((item) => {
                return item.map(() => this.getRandomValue(this.sampleMin2, this.sampleMax2));
            });
        }

    }
}


text:
module Mutant
  # Class to create diffs from source code
  class Diff
    include Adamantium::Flat, Concord.new(:old, :new)

    ADDITION = '+'.freeze
    DELETION = '-'.freeze
    NEWLINE  = "\n".freeze

    # Unified source diff between old and new
    #
    # @return [String]
    #   if there is exactly one diff
    #
    # @return [nil]
    #   otherwise
    #
    # @api private
    def diff
      return if diffs.empty?

      minimized_hunks.map do |hunk|
        hunk.diff(:unified) << NEWLINE
      end.join
    end
    memoize :diff

    # Colorized unified source diff between old and new
    #
    # @return [String]
    #   if there is a diff
    #
    # @return [nil]
    #   otherwise
    #
    # @api private
    def colorized_diff
      return unless diff
      diff.lines.map(&self.class.method(:colorize_line)).join
    end
    memoize :colorized_diff

    # Build new object from source strings
    #
    # @param [String] old
    # @param [String] new
    #
    # @return [Diff]
    #
    # @api private
    def self.build(old, new)
      new(lines(old), lines(new))
    end

    # Break up source into lines
    #
    # @param [String] source
    #
    # @return [Array<String>]
    #
    # @api private
    def self.lines(source)
      source.lines.map(&:chomp)
    end
    private_class_method :lines

  private

    # Diffs between old and new
    #
    # @return [Array<Array>]
    #
    # @api private
    def diffs
      ::Diff::LCS.diff(old, new)
    end

    # Raw diff-lcs hunks
    #
    # @return [Array<Diff::LCS::Hunk>]
    #
    # @api private
    def hunks
      diffs.map do |diff|
        ::Diff::LCS::Hunk.new(old, new, diff, max_length, 0)
      end
    end

    # Minimized hunks
    #
    # @return [Array<Diff::LCS::Hunk>]
    #
    # @api private
    def minimized_hunks
      head, *tail = hunks

      tail.each_with_object([head]) do |right, aggregate|
        left = aggregate.last
        if right.overlaps?(left)
          right.merge(left)
          aggregate.pop
        end
        aggregate << right
      end
    end

    # Max length of source line in new and old
    #
    # @return [Fixnum]
    #
    # @api private
    def max_length
      [old, new].map(&:length).max
    end

    # Colorized a unified diff line
    #
    # @param [String] line
    #
    # @return [String]
    #
    # @api private
    def self.colorize_line(line)
      case line[0]
      when ADDITION
        Color::GREEN
      when DELETION
        Color::RED
      else
        Color::NONE
      end.format(line)
    end
    private_class_method :colorize_line

  end # Diff
end # Mutant


text:
package ccare.domain;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * User: carecx Date: 13-Oct-2010 Time: 12:16:29
 */

@XmlRootElement
public class Observable implements Serializable {

	private Object currentValue;

	private String definition;

	@XmlElement
	private Collection<Observable> dependees = new HashSet<Observable>();

	@XmlElement
	private Collection<Observable> dependents = new HashSet<Observable>();

	public Object getCurrentValue() {
		return currentValue;
	}

	@XmlElement
	public String getDefinition() {
		return definition;
	}

	public Collection<Observable> getDependees() {
		return dependees;
	}

	public Collection<Observable> getDependents() {
		return dependents;
	}

	public void setCurrentValue(Object o) {
		currentValue = o;
	}

	public void setDefinition(String definition) {
		this.definition = definition;
		this.currentValue = "eval(" + definition + ")";
	}
}


text:
Vertex::Vertex(){
  //inVertexes = NULL;
  //outVertexes = NULL;
  visited = false;
}
Vertex::Vertex(uphiLong* invertexes,uphiLong* outvertexes,phiLong indegree,phiLong outdegree){
  inVertexes = invertexes;
  outVertexes = outvertexes;
  inDegree = indegree;
  outDegree = outdegree;
  visited = false;
};
uphiLong* Vertex::getInVertexes () {
  return inVertexes;
}
uphiLong* Vertex::getOutVertexes () {
  return outVertexes;
}
uphiLong Vertex::getInVertexes(uphiLong j) {
  return inVertexes[j];
}
uphiLong Vertex::getOutVertexes(uphiLong j) {
  return outVertexes[j];
}
uphiLong Vertex::getOutDegree() {
  return outDegree;
}
uphiLong Vertex::getInDegree() {
  return inDegree;
}
void Vertex::setInVertexes(uphiLong* _i) {
  inVertexes = _i;
}
void Vertex::setOutVertexes(uphiLong* _i) {
  outVertexes = _i;
}
void Vertex::setOutDegree(uphiLong _i) {
  outDegree = _i;
}
void Vertex::setInDegree(phiLong _i) {
  inDegree = _i;
}
void Vertex::setOutWeight(phiDouble* _i){
  outWeight = _i;
}
void Vertex::setInWeight(phiDouble* _i){
  inWeight = _i;
}
phiDouble Vertex::getOutWeight(uphiLong j){
  return outWeight[j];
}
phiDouble Vertex::getInWeight(uphiLong j){
  return inWeight[j];
}
void Vertex::setVisited(){
  phiCAS(&visited,false,true);
  //visited = true;
}
bool Vertex::isVisited(){
  return visited;
}
Vertex::~Vertex(){
  // if(NULL != inVertexes)
  //   free(inVertexes);
  // if(NULL != outVertexes)
  //   free(outVertexes);
  #ifdef WEIGHTED
  //free(outWeight);
  #endif
  //printf("delete\n");
}


text:
@implementation AppDelegate (RadiusNetworksProximityKit)

PKManager *pkManager;
NSString *cmdInstanceName = @"proximityPlugin";

- (id) getCommandInstance:(NSString*)className
{
    return [self.viewController getCommandInstance:className];
}

// its dangerous to override a method from within a category.
// Instead we will use method swizzling. we set this up in the load call.
+ (void)load
{
    Method original, swizzled;

    original = class_getInstanceMethod(self, @selector(init));
    swizzled = class_getInstanceMethod(self, @selector(swizzled_init));
    method_exchangeImplementations(original, swizzled);
}

- (AppDelegate *)swizzled_init
{
    pkManager = [PKManager managerWithDelegate:self];
    [pkManager start];

    // This actually calls the original init method over in AppDelegate. Equivilent to calling super
    // on an overrided method, this is not recursive, although it appears that way. neat huh?
    return [self swizzled_init];
}

-(void)proximityKit:(PKManager *)manager didEnter:(PKRegion *)region {
    proximityPlugin *proximityPluginRef = [self getCommandInstance:cmdInstanceName];
    [proximityPluginRef proximityKit:manager didEnter:region];
}

- (void)proximityKit:(PKManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(PKRegion *)region{
    proximityPlugin *proximityPluginRef = [self getCommandInstance:cmdInstanceName];
    [proximityPluginRef proximityKit:manager didRangeBeacons:beacons inRegion:region];
}

- (void)proximityKit:(PKManager *)manager didDetermineState:(PKRegionState)state forRegion:(PKRegion *)region{
    proximityPlugin *proximityPluginRef = [self getCommandInstance:cmdInstanceName];
    [proximityPluginRef proximityKit:manager didDetermineState:state forRegion:region];
}

- (void)proximityKit:(PKManager *)manager didExit:(PKRegion *)region{
    proximityPlugin *proximityPluginRef = [self getCommandInstance:cmdInstanceName];
    [proximityPluginRef proximityKit:manager didExit:region];
}

- (void)proximityKit:(PKManager *)manager didFailWithError:(NSError *)error{
    proximityPlugin *proximityPluginRef = [self getCommandInstance:cmdInstanceName];
    [proximityPluginRef proximityKit:manager didFailWithError:error];
}

@end


text:
Statement is a list of all past transactions.

There are different types of transactions:

* Buy
* Sell
* Deposit
* Withdraw
* More?

Only Buy and Sell have contractId associated with. Thus 'details' can not be seen for the rest.

Current implementation makes Profit Table unnecessary.


text:
package com.github.eirslett.maven.plugins.frontend.lib;

import java.io.File;

public final class FrontendPluginFactory {

    private static final Platform defaultPlatform = Platform.guess();
    private static final String DEFAULT_CACHE_PATH = "cache";

    private final File workingDirectory;
    private final File installDirectory;
    private final CacheResolver cacheResolver;

    public FrontendPluginFactory(File workingDirectory, File installDirectory){
        this(workingDirectory, installDirectory, getDefaultCacheResolver(installDirectory));
    }

    public FrontendPluginFactory(File workingDirectory, File installDirectory, CacheResolver cacheResolver){
        this.workingDirectory = workingDirectory;
        this.installDirectory = installDirectory;
        this.cacheResolver = cacheResolver;
    }

    public NodeInstaller getNodeInstaller(ProxyConfig proxy) {
        return new NodeInstaller(getInstallConfig(), new DefaultArchiveExtractor(), new DefaultFileDownloader(proxy));
    }

    public NPMInstaller getNPMInstaller(ProxyConfig proxy) {
        return new NPMInstaller(getInstallConfig(), new DefaultArchiveExtractor(), new DefaultFileDownloader(proxy));
    }

    public YarnInstaller getYarnInstaller(ProxyConfig proxy) {
        return new YarnInstaller(getInstallConfig(), new DefaultArchiveExtractor(), new DefaultFileDownloader(proxy));
    }

    public NpmRunner getNpmRunner(ProxyConfig proxy, String npmRegistryURL) {
        return new DefaultNpmRunner(getExecutorConfig(), proxy, npmRegistryURL);
    }

    public YarnRunner getYarnRunner(ProxyConfig proxy, String npmRegistryURL) {
        return new DefaultYarnRunner(new InstallYarnExecutorConfig(getInstallConfig()), proxy, npmRegistryURL);
    }

    private NodeExecutorConfig getExecutorConfig() {
        return new InstallNodeExecutorConfig(getInstallConfig());
    }

    private InstallConfig getInstallConfig() {
        return new DefaultInstallConfig(installDirectory, workingDirectory, cacheResolver, defaultPlatform);
    }

    private static final CacheResolver getDefaultCacheResolver(File root) {
        return new DirectoryCacheResolver(new File(root, DEFAULT_CACHE_PATH));
    }
}


text:
module Sweatpants
  class QueuedRequest

    def initialize method, params
      @method = method
      @type = params[:type] || nil
      @index = params[:index] || nil
      @id = params[:id] || nil
      @body = params[:body] || nil
    end

    def to_bulk
      [bulk_header, @body].map(&:to_json).join("\n")
    end

    def bulk_header
      header = { @method.to_sym => { _index: @index, _type: @type } }
      header[:id] = @id if @id
      header
    end
  end
end


text:
$(document).ready(function(){
    $('#dialog').dialog({
    autoOpen: false,
    modal: true,
    dialogClass: 'bulk_dialog',
    buttons: {
        "Volver": function() {
            $(this).dialog('close');
        }
    }
    });
    $("div.bulk_dialog div button:nth-child(1)").addClass("confirm");
    $("div.bulk_dialog div button:nth-child(2)").addClass("go_back");

    $(".clickable").on('click', function(){
        $(".description").html($(this).parent().parent().attr('data-description'));
        $(".code").html($(this).parent().parent().attr('data-code'));
        $(".pvp").html($(this).parent().parent().attr('data-pvp'));
        $(".dc2").html($(this).parent().parent().attr('data-discount-l2'));
        $(".net2").html($(this).parent().parent().attr('data-net-l2'));
        $(".dc4").html($(this).parent().parent().attr('data-discount-l4'));
        $(".net4").html($(this).parent().parent().attr('data-net-l4'));
        $(".of1").html($(this).parent().parent().attr('data-of1'));
        $(".of2").html($(this).parent().parent().attr('data-of2'));
        $(".of3").html($(this).parent().parent().attr('data-of3'));
        $('#dialog').dialog('open');

    })
});


text:
#ifndef GRPC_CORE_LIB_SECURITY_CREDENTIALS_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_CREDENTIALS_H

#include <grpc/support/port_platform.h>

#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include <grpc/support/sync.h>
#include "src/core/lib/transport/metadata_batch.h"

#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/http/httpcli.h"
#include "src/core/lib/http/parser.h"
#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/security/security_connector/security_connector.h"

struct grpc_http_response;

/* --- Constants. --- */

typedef enum {
  GRPC_CREDENTIALS_OK = 0,
  GRPC_CREDENTIALS_ERROR
} grpc_credentials_status;

#define GRPC_FAKE_TRANSPORT_SECURITY_TYPE "fake"

#define GRPC_CHANNEL_CREDENTIALS_TYPE_SSL "Ssl"
#define GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY \
  "FakeTransportSecurity"
#define GRPC_CHANNEL_CREDENTIALS_TYPE_GOOGLE_DEFAULT "GoogleDefault"

#define GRPC_CALL_CREDENTIALS_TYPE_OAUTH2 "Oauth2"
#define GRPC_CALL_CREDENTIALS_TYPE_JWT "Jwt"
#define GRPC_CALL_CREDENTIALS_TYPE_IAM "Iam"
#define GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE "Composite"

#define GRPC_AUTHORIZATION_METADATA_KEY "authorization"
#define GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY \
  "x-goog-iam-authorization-token"
#define GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY "x-goog-iam-authority-selector"

#define GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS 60

#define GRPC_COMPUTE_ENGINE_METADATA_HOST "metadata.google.internal."
#define GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH \
  "/computeMetadata/v1/instance/service-accounts/default/token"

#define GRPC_GOOGLE_OAUTH2_SERVICE_HOST "oauth2.googleapis.com"
#define GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH "/token"

#define GRPC_SERVICE_ACCOUNT_POST_BODY_PREFIX                         \
  "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&" \
  "assertion="

#define GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING \
  "client_id=%s&client_secret=%s&refresh_token=%s&grant_type=refresh_token"

/* --- Google utils --- */

/* It is the caller's responsibility to gpr_free the result if not NULL. */
char* grpc_get_well_known_google_credentials_file_path(void);

/* Implementation function for the different platforms. */
char* grpc_get_well_known_google_credentials_file_path_impl(void);

/* Override for testing only. Not thread-safe */
typedef char* (*grpc_well_known_credentials_path_getter)(void);
void grpc_override_well_known_credentials_path_getter(
    grpc_well_known_credentials_path_getter getter);

/* --- grpc_channel_credentials. --- */

#define GRPC_ARG_CHANNEL_CREDENTIALS "grpc.channel_credentials"

// This type is forward declared as a C struct and we cannot define it as a
// class. Otherwise, compiler will complain about type mismatch due to
// -Wmismatched-tags.
struct grpc_channel_credentials
    : grpc_core::RefCounted<grpc_channel_credentials> {
 public:
  explicit grpc_channel_credentials(const char* type) : type_(type) {}
  virtual ~grpc_channel_credentials() = default;

  // Creates a security connector for the channel. May also create new channel
  // args for the channel to be used in place of the passed in const args if
  // returned non NULL. In that case the caller is responsible for destroying
  // new_args after channel creation.
  virtual grpc_core::RefCountedPtr<grpc_channel_security_connector>
  create_security_connector(
      grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
      const char* target, const grpc_channel_args* args,
      grpc_channel_args** new_args) {
    // Tell clang-tidy that call_creds cannot be passed as const-ref.
    call_creds.reset();
    GRPC_ABSTRACT;
  }

  // Creates a version of the channel credentials without any attached call
  // credentials. This can be used in order to open a channel to a non-trusted
  // gRPC load balancer.
  virtual grpc_core::RefCountedPtr<grpc_channel_credentials>
  duplicate_without_call_credentials() {
    // By default we just increment the refcount.
    return Ref();
  }

  // Allows credentials to optionally modify a parent channel's args.
  // By default, leave channel args as is. The callee takes ownership
  // of the passed-in channel args, and the caller takes ownership
  // of the returned channel args.
  virtual grpc_channel_args* update_arguments(grpc_channel_args* args) {
    return args;
  }

  const char* type() const { return type_; }

  GRPC_ABSTRACT_BASE_CLASS

 private:
  const char* type_;
};

/* Util to encapsulate the channel credentials in a channel arg. */
grpc_arg grpc_channel_credentials_to_arg(grpc_channel_credentials* credentials);

/* Util to get the channel credentials from a channel arg. */
grpc_channel_credentials* grpc_channel_credentials_from_arg(
    const grpc_arg* arg);

/* Util to find the channel credentials from channel args. */
grpc_channel_credentials* grpc_channel_credentials_find_in_args(
    const grpc_channel_args* args);

/* --- grpc_credentials_mdelem_array. --- */

typedef struct {
  grpc_mdelem* md = nullptr;
  size_t size = 0;
} grpc_credentials_mdelem_array;

/// Takes a new ref to \a md.
void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array* list,
                                       grpc_mdelem md);

/// Appends all elements from \a src to \a dst, taking a new ref to each one.
void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array* dst,
                                          grpc_credentials_mdelem_array* src);

void grpc_credentials_mdelem_array_destroy(grpc_credentials_mdelem_array* list);

/* --- grpc_call_credentials. --- */

// This type is forward declared as a C struct and we cannot define it as a
// class. Otherwise, compiler will complain about type mismatch due to
// -Wmismatched-tags.
struct grpc_call_credentials
    : public grpc_core::RefCounted<grpc_call_credentials> {
 public:
  explicit grpc_call_credentials(const char* type) : type_(type) {}
  virtual ~grpc_call_credentials() = default;

  // Returns true if completed synchronously, in which case \a error will
  // be set to indicate the result.  Otherwise, \a on_request_metadata will
  // be invoked asynchronously when complete.  \a md_array will be populated
  // with the resulting metadata once complete.
  virtual bool get_request_metadata(grpc_polling_entity* pollent,
                                    grpc_auth_metadata_context context,
                                    grpc_credentials_mdelem_array* md_array,
                                    grpc_closure* on_request_metadata,
                                    grpc_error** error) GRPC_ABSTRACT;

  // Cancels a pending asynchronous operation started by
  // grpc_call_credentials_get_request_metadata() with the corresponding
  // value of \a md_array.
  virtual void cancel_get_request_metadata(
      grpc_credentials_mdelem_array* md_array, grpc_error* error) GRPC_ABSTRACT;

  const char* type() const { return type_; }

  GRPC_ABSTRACT_BASE_CLASS

 private:
  const char* type_;
};

/* Metadata-only credentials with the specified key and value where
   asynchronicity can be simulated for testing. */
grpc_call_credentials* grpc_md_only_test_credentials_create(
    const char* md_key, const char* md_value, bool is_async);

/* --- grpc_server_credentials. --- */

// This type is forward declared as a C struct and we cannot define it as a
// class. Otherwise, compiler will complain about type mismatch due to
// -Wmismatched-tags.
struct grpc_server_credentials
    : public grpc_core::RefCounted<grpc_server_credentials> {
 public:
  explicit grpc_server_credentials(const char* type) : type_(type) {}

  virtual ~grpc_server_credentials() { DestroyProcessor(); }

  virtual grpc_core::RefCountedPtr<grpc_server_security_connector>
  create_security_connector() GRPC_ABSTRACT;

  const char* type() const { return type_; }

  const grpc_auth_metadata_processor& auth_metadata_processor() const {
    return processor_;
  }
  void set_auth_metadata_processor(
      const grpc_auth_metadata_processor& processor);

  GRPC_ABSTRACT_BASE_CLASS

 private:
  void DestroyProcessor() {
    if (processor_.destroy != nullptr && processor_.state != nullptr) {
      processor_.destroy(processor_.state);
    }
  }

  const char* type_;
  grpc_auth_metadata_processor processor_ =
      grpc_auth_metadata_processor();  // Zero-initialize the C struct.
};

#define GRPC_SERVER_CREDENTIALS_ARG "grpc.server_credentials"

grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials* c);
grpc_server_credentials* grpc_server_credentials_from_arg(const grpc_arg* arg);
grpc_server_credentials* grpc_find_server_credentials_in_args(
    const grpc_channel_args* args);

/* -- Credentials Metadata Request. -- */

struct grpc_credentials_metadata_request {
  explicit grpc_credentials_metadata_request(
      grpc_core::RefCountedPtr<grpc_call_credentials> creds)
      : creds(std::move(creds)) {}
  ~grpc_credentials_metadata_request() {
    grpc_http_response_destroy(&response);
  }

  grpc_core::RefCountedPtr<grpc_call_credentials> creds;
  grpc_http_response response;
};

inline grpc_credentials_metadata_request*
grpc_credentials_metadata_request_create(
    grpc_core::RefCountedPtr<grpc_call_credentials> creds) {
  return grpc_core::New<grpc_credentials_metadata_request>(std::move(creds));
}

inline void grpc_credentials_metadata_request_destroy(
    grpc_credentials_metadata_request* r) {
  grpc_core::Delete(r);
}

#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_CREDENTIALS_H */


text:
from heat.common import exception
from heat.common.i18n import _
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support

class KeystoneRoleAssignment(resource.Resource):
    '''
    Keystone Role assignment class implements role assignments between
    user/groups and project/domain.

    heat_template_version: 2013-05-23

    parameters:
      ... Group or User parameters
      group_role:
        type: string
        description: role
      group_role_domain:
        type: string
        description: group role domain
      group_role_project:
        type: string
        description: group role project

    resources:
      admin_group:
        type: OS::Keystone::Group OR OS::Keystone::User
        properties:
          ... Group or User properties
          roles:
            - role: {get_param: group_role}
              domain: {get_param: group_role_domain}
            - role: {get_param: group_role}
              project: {get_param: group_role_project}
    '''

    support_status = support.SupportStatus(
        version='2015.1',
        message=_('Supported versions: keystone v3'))

    PROPERTIES = (
        ROLES
    ) = (
        'roles'
    )

    _ROLES_MAPPING_PROPERTIES = (
        ROLE, DOMAIN, PROJECT
    ) = (
        'role', 'domain', 'project'
    )

    properties_schema = {
        ROLES: properties.Schema(
            properties.Schema.LIST,
            _('List of role assignments.'),
            schema=properties.Schema(
                properties.Schema.MAP,
                _('Map between role with either project or domain.'),
                schema={
                    ROLE: properties.Schema(
                        properties.Schema.STRING,
                        _('Keystone role'),
                        required=True,
                        constraints=([constraints.
                                     CustomConstraint('keystone.role')])
                    ),
                    PROJECT: properties.Schema(
                        properties.Schema.STRING,
                        _('Keystone project'),
                        constraints=([constraints.
                                     CustomConstraint('keystone.project')])
                    ),
                    DOMAIN: properties.Schema(
                        properties.Schema.STRING,
                        _('Keystone domain'),
                        constraints=([constraints.
                                     CustomConstraint('keystone.domain')])
                    ),
                }
            ),
            update_allowed=True
        )
    }

    def _add_role_assignments_to_group(self, group_id, role_assignments):
        for role_assignment in self._normalize_to_id(role_assignments):
            if role_assignment.get(self.PROJECT) is not None:
                self.keystone().client.roles.grant(
                    role=role_assignment.get(self.ROLE),
                    project=role_assignment.get(self.PROJECT),
                    group=group_id
                )
            elif role_assignment.get(self.DOMAIN) is not None:
                self.keystone().client.roles.grant(
                    role=role_assignment.get(self.ROLE),
                    domain=role_assignment.get(self.DOMAIN),
                    group=group_id
                )

    def _add_role_assignments_to_user(self, user_id, role_assignments):
        for role_assignment in self._normalize_to_id(role_assignments):
            if role_assignment.get(self.PROJECT) is not None:
                self.keystone().client.roles.grant(
                    role=role_assignment.get(self.ROLE),
                    project=role_assignment.get(self.PROJECT),
                    user=user_id
                )
            elif role_assignment.get(self.DOMAIN) is not None:
                self.keystone().client.roles.grant(
                    role=role_assignment.get(self.ROLE),
                    domain=role_assignment.get(self.DOMAIN),
                    user=user_id
                )

    def _remove_role_assignments_from_group(self, group_id, role_assignments):
        for role_assignment in self._normalize_to_id(role_assignments):
            if role_assignment.get(self.PROJECT) is not None:
                self.keystone().client.roles.revoke(
                    role=role_assignment.get(self.ROLE),
                    project=role_assignment.get(self.PROJECT),
                    group=group_id
                )
            elif role_assignment.get(self.DOMAIN) is not None:
                self.keystone().client.roles.revoke(
                    role=role_assignment.get(self.ROLE),
                    domain=role_assignment.get(self.DOMAIN),
                    group=group_id
                )

    def _remove_role_assignments_from_user(self, user_id, role_assignments):
        for role_assignment in self._normalize_to_id(role_assignments):
            if role_assignment.get(self.PROJECT) is not None:
                self.keystone().client.roles.revoke(
                    role=role_assignment.get(self.ROLE),
                    project=role_assignment.get(self.PROJECT),
                    user=user_id
                )
            elif role_assignment.get(self.DOMAIN) is not None:
                self.keystone().client.roles.revoke(
                    role=role_assignment.get(self.ROLE),
                    domain=role_assignment.get(self.DOMAIN),
                    user=user_id
                )

    def _normalize_to_id(self, role_assignment_prps):
        role_assignments = []
        if role_assignment_prps is None:
            return role_assignments

        for role_assignment in role_assignment_prps:
            role = role_assignment.get(self.ROLE)
            project = role_assignment.get(self.PROJECT)
            domain = role_assignment.get(self.DOMAIN)

            role_assignments.append({
                self.ROLE: (self.client_plugin('keystone').
                            get_role_id(role)),
                self.PROJECT: (self.client_plugin('keystone').
                               get_project_id(project)) if project else None,
                self.DOMAIN: (self.client_plugin('keystone').
                              get_domain_id(domain)) if domain else None
            })
        return role_assignments

    @staticmethod
    def _find_diff(updated_prps, stored_prps):
        updated_role_project_assignments = []
        updated_role_domain_assignments = []

        # Split the properties into two set of role assignments
        # (project, domain) from updated properties
        for role_assignment in updated_prps or []:
            if role_assignment.get(KeystoneRoleAssignment.PROJECT) is not None:
                updated_role_project_assignments.append(
                    '%s:%s' % (
                        role_assignment[KeystoneRoleAssignment.ROLE],
                        role_assignment[KeystoneRoleAssignment.PROJECT]))
            elif (role_assignment.get(KeystoneRoleAssignment.DOMAIN)
                  is not None):
                updated_role_domain_assignments.append(
                    '%s:%s' % (role_assignment[KeystoneRoleAssignment.ROLE],
                               role_assignment[KeystoneRoleAssignment.DOMAIN]))

        stored_role_project_assignments = []
        stored_role_domain_assignments = []

        # Split the properties into two set of role assignments
        # (project, domain) from updated properties
        for role_assignment in (stored_prps or []):
            if role_assignment.get(KeystoneRoleAssignment.PROJECT) is not None:
                stored_role_project_assignments.append(
                    '%s:%s' % (
                        role_assignment[KeystoneRoleAssignment.ROLE],
                        role_assignment[KeystoneRoleAssignment.PROJECT]))
            elif (role_assignment.get(KeystoneRoleAssignment.DOMAIN)
                  is not None):
                stored_role_domain_assignments.append(
                    '%s:%s' % (role_assignment[KeystoneRoleAssignment.ROLE],
                               role_assignment[KeystoneRoleAssignment.DOMAIN]))

        new_role_assignments = []
        removed_role_assignments = []
        # NOTE: finding the diff of list of strings is easier by using 'set'
        #       so properties are converted to string in above sections
        # New items
        for item in (set(updated_role_project_assignments) -
                     set(stored_role_project_assignments)):
            new_role_assignments.append(
                {KeystoneRoleAssignment.ROLE: item[:item.find(':')],
                 KeystoneRoleAssignment.PROJECT: item[item.find(':') + 1:]}
            )

        for item in (set(updated_role_domain_assignments) -
                     set(stored_role_domain_assignments)):
            new_role_assignments.append(
                {KeystoneRoleAssignment.ROLE: item[:item.find(':')],
                 KeystoneRoleAssignment.DOMAIN: item[item.find(':') + 1:]}
            )

        # Old items
        for item in (set(stored_role_project_assignments) -
                     set(updated_role_project_assignments)):
            removed_role_assignments.append(
                {KeystoneRoleAssignment.ROLE: item[:item.find(':')],
                 KeystoneRoleAssignment.PROJECT: item[item.find(':') + 1:]}
            )
        for item in (set(stored_role_domain_assignments) -
                     set(updated_role_domain_assignments)):
            removed_role_assignments.append(
                {KeystoneRoleAssignment.ROLE: item[:item.find(':')],
                 KeystoneRoleAssignment.DOMAIN: item[item.find(':') + 1:]}
            )

        return new_role_assignments, removed_role_assignments

    def handle_create(self, user_id=None, group_id=None):
        if self.properties.get(self.ROLES) is not None:
            if user_id is not None:
                self._add_role_assignments_to_user(
                    user_id,
                    self.properties.get(self.ROLES))
            elif group_id is not None:
                self._add_role_assignments_to_group(
                    group_id,
                    self.properties.get(self.ROLES))

    def handle_update(self, user_id=None, group_id=None, prop_diff=None):
        (new_role_assignments,
         removed_role_assignments) = KeystoneRoleAssignment._find_diff(
            prop_diff.get(self.ROLES),
            self._stored_properties_data.get(self.ROLES))

        if len(new_role_assignments) > 0:
            if user_id is not None:
                self._add_role_assignments_to_user(
                    user_id,
                    new_role_assignments)
            elif group_id is not None:
                self._add_role_assignments_to_group(
                    group_id,
                    new_role_assignments)

        if len(removed_role_assignments) > 0:
            if user_id is not None:
                self._remove_role_assignments_from_user(
                    user_id,
                    removed_role_assignments)
            elif group_id is not None:
                self._remove_role_assignments_from_group(
                    group_id,
                    removed_role_assignments)

    def handle_delete(self, user_id=None, group_id=None):
        if self._stored_properties_data.get(self.ROLES) is not None:
            if user_id is not None:
                self._remove_role_assignments_from_user(
                    user_id,
                    (self._stored_properties_data.
                     get(self.ROLES)))
            elif group_id is not None:
                self._remove_role_assignments_from_group(
                    group_id,
                    (self._stored_properties_data.
                     get(self.ROLES)))

    def validate(self):
        super(KeystoneRoleAssignment, self).validate()

        if self.properties.get(self.ROLES) is not None:
            for role_assignment in self.properties.get(self.ROLES):
                project = role_assignment.get(self.PROJECT)
                domain = role_assignment.get(self.DOMAIN)

                if project is not None and domain is not None:
                    raise exception.ResourcePropertyConflict(self.PROJECT,
                                                             self.DOMAIN)

                if project is None and domain is None:
                    msg = _('Either project or domain must be specified for'
                            ' role %s') % role_assignment.get(self.ROLE)
                    raise exception.StackValidationFailed(message=msg)


text:
package org.onosproject.drivers.fujitsu;

import org.onosproject.mastership.MastershipService;
import org.onosproject.net.DeviceId;
import org.onosproject.net.behaviour.VoltPonLinkConfig;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.onosproject.net.driver.DriverHandler;
import org.onosproject.netconf.NetconfController;
import org.slf4j.Logger;

import java.io.IOException;
import java.util.Set;

import com.google.common.collect.ImmutableSet;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onosproject.drivers.fujitsu.FujitsuVoltXmlUtility.*;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Implementation to get and set parameters available in vOLT
 * through the Netconf protocol.
 */
public class FujitsuVoltPonLinkConfig extends AbstractHandlerBehaviour
        implements VoltPonLinkConfig {

    private final Logger log = getLogger(FujitsuVoltPonLinkConfig.class);
    private final Set<String> ponLinkParams = ImmutableSet.of(
            "admin-state", "onu-discovery-mode", "onu-discovery-interval",
            "dba-cycle-time", "mac-age-time", "lof-threshold",
            "los-threshold", "pm-enable");
    private static final String VOLT_PORTS = "volt-ports";
    private static final String GPON_PONLINK_PORTS = "gpon-ponlink-ports";
    private static final String GPON_PONLINK_PORT = "gpon-ponlink-port";
    private int pon;

    @Override
    public String getPonLinks(String target) {
        DriverHandler handler = handler();
        NetconfController controller = handler.get(NetconfController.class);
        MastershipService mastershipService = handler.get(MastershipService.class);
        DeviceId ncDeviceId = handler.data().deviceId();
        checkNotNull(controller, "Netconf controller is null");
        String reply = null;

        if (!mastershipService.isLocalMaster(ncDeviceId)) {
            log.warn("Not master for {} Use {} to execute command",
                     ncDeviceId,
                     mastershipService.getMasterFor(ncDeviceId));
            return reply;
        }

        try {
            StringBuilder request = new StringBuilder();
            request.append(VOLT_NE_OPEN).append(VOLT_NE_NAMESPACE);
            request.append(ANGLE_RIGHT).append(NEW_LINE);
            request.append(buildStartTag(VOLT_PORTS));
            if (target != null) {
                try {
                    pon = Integer.parseInt(target);
                } catch (NumberFormatException e) {
                    log.error("Non-number input");
                    return reply;
                }
                request.append(buildStartTag(GPON_PONLINK_PORTS));
                request.append(buildStartTag(GPON_PONLINK_PORT));
                request.append(buildStartTag(PONLINK_ID, false));
                request.append(target);
                request.append(buildEndTag(PONLINK_ID));

                request.append(buildEndTag(GPON_PONLINK_PORT));
                request.append(buildEndTag(GPON_PONLINK_PORTS));
            } else {
                request.append(buildEmptyTag(GPON_PONLINK_PORTS));
            }
            request.append(buildEndTag(VOLT_PORTS));
            request.append(VOLT_NE_CLOSE);

            reply = controller.
                    getDevicesMap().get(ncDeviceId).getSession().
                    get(request.toString(), REPORT_ALL);
        } catch (IOException e) {
            log.error("Cannot communicate to device {} exception ", ncDeviceId, e);
        }
        return reply;
    }

    @Override
    public void setPonLink(String target) {
        DriverHandler handler = handler();
        NetconfController controller = handler.get(NetconfController.class);
        MastershipService mastershipService = handler.get(MastershipService.class);
        DeviceId ncDeviceId = handler.data().deviceId();
        checkNotNull(controller, "Netconf controller is null");

        if (!mastershipService.isLocalMaster(ncDeviceId)) {
            log.warn("Not master for {} Use {} to execute command",
                     ncDeviceId,
                     mastershipService.getMasterFor(ncDeviceId));
            return;
        }

        String[] data = target.split(COLON);
        if (data.length != 3) {
            log.error("Invalid number of arguments");
            return;
        }

        try {
            pon = Integer.parseInt(data[0]);
        } catch (NumberFormatException e) {
            log.error("Non-number input");
            return;
        }

        if (!ponLinkParams.contains(data[1])) {
            log.error("Unsupported parameter: {} ", data[1]);
            return;
        }

        try {
            StringBuilder request = new StringBuilder();
            request.append(VOLT_NE_OPEN).append(VOLT_NE_NAMESPACE);
            request.append(ANGLE_RIGHT).append(NEW_LINE);
            request.append(buildStartTag(VOLT_PORTS));
            request.append(buildStartTag(GPON_PONLINK_PORTS));
            request.append(buildStartTag(GPON_PONLINK_PORT));
            request.append(buildStartTag(PONLINK_ID, false));
            request.append(data[0]);
            request.append(buildEndTag(PONLINK_ID));

            request.append(buildStartTag(data[1], false));
            request.append(data[2]);
            request.append(buildEndTag(data[1]));

            request.append(buildEndTag(GPON_PONLINK_PORT));
            request.append(buildEndTag(GPON_PONLINK_PORTS));
            request.append(buildEndTag(VOLT_PORTS));
            request.append(VOLT_NE_CLOSE);

            controller.getDevicesMap().get(ncDeviceId).getSession().
                    editConfig(RUNNING, null, request.toString());
        } catch (IOException e) {
            log.error("Cannot communicate to device {} exception ", ncDeviceId, e);
        }
    }

}


text:
<?php

/**
 * @see Zend_Gdata_Gapps_Query
 */
require_once('Zend/Gdata/Gapps/Query.php');

/**
 * Assists in constructing queries for Google Apps member entries.
 * Instances of this class can be provided in many places where a URL is
 * required.
 *
 * For information on submitting queries to a server, see the Google Apps
 * service class, Zend_Gdata_Gapps.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Gapps
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Gapps_MemberQuery extends Zend_Gdata_Gapps_Query
{

    /**
     * If not null, specifies the group id
     *
     * @var string
     */
    protected $_groupId = null;

    /**
     * If not null, specifies the member id of the user who should be
     * retrieved by this query.
     *
     * @var string
     */
    protected $_memberId = null;

    /**
     * Create a new instance.
     *
     * @param string $domain (optional) The Google Apps-hosted domain to use
     *          when constructing query URIs.
     * @param string $groupId (optional) Value for the groupId property.
     * @param string $memberId (optional) Value for the memberId property.
     * @param string $startMemberId (optional) Value for the
     *          startMemberId property.
     */
    public function __construct($domain = null, $groupId = null, $memberId = null,
            $startMemberId = null)
    {
        parent::__construct($domain);
        $this->setGroupId($groupId);
        $this->setMemberId($memberId);
        $this->setStartMemberId($startMemberId);
    }

    /**
     * Set the group id to query for.
     *
     * @see getGroupId
     * @param string $value The group id to filter search results by, or null to
     *              disable.
     */
    public function setGroupId($value)
    {
        $this->_groupId = $value;
    }

    /**
     * Get the group id to query for. If no group id is set, null will be
     * returned.
     *
     * @param string $value The group id to filter search results by, or
     *          null if disabled.
     * @return string The group id
     */
    public function getGroupId()
    {
        return $this->_groupId;
    }

    /**
     * Set the member id to query for. When set, only users with a member id
     * matching this value will be returned in search results. Set to
     * null to disable filtering by member id.
     *
     * @see getMemberId
     * @param string $value The member id to filter search results by, or null to
     *              disable.
     */
    public function setMemberId($value)
    {
        $this->_memberId = $value;
    }

    /**
     * Get the member id to query for. If no member id is set, null will be
     * returned.
     *
     * @param string $value The member id to filter search results by, or
     *          null if disabled.
     * @return The member id
     */
    public function getMemberId()
    {
        return $this->_memberId;
    }

    /**
     * Set the first member id which should be displayed when retrieving
     * a list of members.
     *
     * @param string $value The first member id to be returned, or null to
     *          disable.
     */
    public function setStartMemberId($value)
    {
        if ($value !== null) {
            $this->_params['start'] = $value;
        } else {
            unset($this->_params['start']);
        }
    }

    /**
     * Get the first username which should be displayed when retrieving
     * a list of users.
     *
     * @see setStartUsername
     * @return string The first username to be returned, or null if
     *          disabled.
     */
    public function getStartMemberId()
    {
        if (array_key_exists('start', $this->_params)) {
            return $this->_params['start'];
        } else {
            return null;
        }
    }

    /**
     * Returns the query URL generated by this query instance.
     *
     * @return string The query URL for this instance.
     */
    public function getQueryUrl()
    {

        $uri = Zend_Gdata_Gapps::APPS_BASE_FEED_URI;
        $uri .= Zend_Gdata_Gapps::APPS_GROUP_PATH;
        $uri .= '/' . $this->_domain;
        if ($this->_groupId !== null) {
            $uri .= '/' . $this->_groupId;
        } else {
            require_once 'Zend/Gdata/App/InvalidArgumentException.php';
            throw new Zend_Gdata_App_InvalidArgumentException(
                    'groupId must not be null');
        }

        $uri .= '/member';

        if ($this->_memberId !== null) {
            $uri .= '/' . $this->_memberId;
        }
        $uri .= $this->getQueryString();
        return $uri;
    }

}


text:
@charset "utf-8";@import url('/common/css/base.min.css');@import url('/common/css/lower.min.css');.mabushii #space{position:absolute;left:0;top:0;z-index:-1;overflow:hidden;background:linear-gradient( rgba(60,119,185,0.4),#fff 28%);background-size:100% 100%;}
.mabushii #space .staticWrap01{width:80%;height:100%;margin:auto;display:table;}
.mabushii #space .staticWrap02{display:table-cell;vertical-align:middle;}
.mabushii #space .static{position:relative;}
.mabushii #space .center{position:absolute;left:63%;top:28%;display:none;}
.mabushii .moveLight,.mabushii .flashLight{width:auto;position:absolute;z-index:10;display:none;}
.mabushii .light01{width:10px;}
.mabushii .light02{width:30px;}
.mabushii .light03{width:40px;}
.mabushii .light04{width:80px;}
.mabushii .flash01{width:20%;left:20%;top:37%;}
.mabushii .flash02{width:24%;left:58%;top:3%;}
.mabushii .flash03{width:2%;left:15%;top:40%;}
.mabushii .flash04{width:4%;left:43%;top:68%;}
.mabushii #space.mode01 .flash01{display:block;}
.mabushii #space.mode02 .flash02{display:block;}
.mabushii #space.mode03 .flash03{display:block;}
.mabushii #space.mode04 .flash04{display:block;}