text:
<!-- IBM_PROLOG_BEGIN_TAG                                                   -->
<!-- This is an automatically generated prolog.                             -->
<!--                                                                        -->
<!-- $Source: src/import/chips/p10/procedures/xml/error_info/p10_sbe_common_errors.xml $ -->
<!--                                                                        -->
<!-- OpenPOWER HostBoot Project                                             -->
<!--                                                                        -->
<!-- Contributors Listed Below - COPYRIGHT 2015,2022                        -->
<!-- [+] International Business Machines Corp.                              -->
<!--                                                                        -->
<!--                                                                        -->
<!-- Licensed under the Apache License, Version 2.0 (the "License");        -->
<!-- you may not use this file except in compliance with the License.       -->
<!-- You may obtain a copy of the License at                                -->
<!--                                                                        -->
<!--     http://www.apache.org/licenses/LICENSE-2.0                         -->
<!--                                                                        -->
<!-- Unless required by applicable law or agreed to in writing, software    -->
<!-- distributed under the License is distributed on an "AS IS" BASIS,      -->
<!-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        -->
<!-- implied. See the License for the specific language governing           -->
<!-- permissions and limitations under the License.                         -->
<!--                                                                        -->
<!-- IBM_PROLOG_END_TAG                                                     -->
<!-- This is an automatically generated file. -->
<!-- File: p10_sbe_common_errors.xml. -->
<!-- Halt codes for p10_sbe_common -->
<hwpErrors>
   <!-- ******************************************************************** -->
    <registerFfdc>
       <id>CBS_STATUS_REGISTERS</id>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_CS_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_TR_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_EL_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_ENVSTAT_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_TR_HIST_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_EL_HIST_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_SB_CS_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_SB_MSG_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_STAT_FSI</cfamRegister>
    </registerFfdc>
    <registerFfdc>
       <id>CBS_STATUS_REGISTERS_SCOM</id>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_CS</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_TR_RO</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_EL</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_ENVSTAT_RO</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_TR_HIST</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_EL_HIST</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_SB_CS</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_SB_MSG</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_CBS_STAT_RO</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>ROOT_CTRL_REGISTERS_CFAM</id>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL0_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL1_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL2_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL3_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL4_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL5_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL6_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL7_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL8_FSI</cfamRegister>
    </registerFfdc>
    <registerFfdc>
       <id>ROOT_CTRL_REGISTERS_SCOM</id>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL0_RW</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL1_RW</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL2_RW</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL3_RW</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL4_RW</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL5_RW</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL6_RW</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL7_RW</scomRegister>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_ROOT_CTRL8_RW</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>PERV_CTRL_REGISTERS_CFAM</id>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_PERV_CTRL0_FSI</cfamRegister>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_PERV_CTRL1_FSI</cfamRegister>
    </registerFfdc>
    <registerFfdc>
       <id>FSI2PIB_STATUS</id>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_FSI2PIB_STATUS_FSI</cfamRegister>
    </registerFfdc>
    <registerFfdc>
       <id>OSC_SWITCH_SENSE_REGISTER_CFAM</id>
       <cfamRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_SNS1LTH_FSI</cfamRegister>
    </registerFfdc>
    <registerFfdc>
       <id>OSC_SWITCH_SENSE_REGISTER</id>
       <scomRegister>scomt::proc::TP_TPVSB_FSI_W_MAILBOX_FSXCOMP_FSXLOG_SNS1LTH_RO</scomRegister>
    </registerFfdc>
    <!--
    <registerFfdc>
       <id>OSC_ERROR_HOLD</id>
       <scomRegister>PERV_TP_OSCERR_HOLD</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>ROOT_CTRL_REGISTERS</id>
       <scomRegister>PERV_ROOT_CTRL0_SCOM</scomRegister>
       <scomRegister>PERV_ROOT_CTRL1_SCOM</scomRegister>
       <scomRegister>PERV_ROOT_CTRL2_SCOM</scomRegister>
       <scomRegister>PERV_ROOT_CTRL3_SCOM</scomRegister>
       <scomRegister>PERV_ROOT_CTRL4_SCOM</scomRegister>
       <scomRegister>PERV_ROOT_CTRL5_SCOM</scomRegister>
       <scomRegister>PERV_ROOT_CTRL6_SCOM</scomRegister>
       <scomRegister>PERV_ROOT_CTRL7_SCOM</scomRegister>
       <scomRegister>PERV_ROOT_CTRL8_SCOM</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>PERV_CTRL_REGISTERS</id>
       <scomRegister>PERV_PERV_CTRL0_SCOM</scomRegister>
       <scomRegister>PERV_PERV_CTRL1_SCOM</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>NET_CTRL_REGISTERS</id>
       <scomRegister>PERV_NET_CTRL0</scomRegister>
       <scomRegister>PERV_NET_CTRL1</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>CPLT_CTRL_REGISTERS</id>
       <scomRegister>PERV_CPLT_CTRL0</scomRegister>
       <scomRegister>PERV_CPLT_CTRL1</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>CPLT_CONFIG_REGISTERS</id>
       <scomRegister>PERV_CPLT_CONF0</scomRegister>
       <scomRegister>PERV_CPLT_CONF1</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>OTHER_CPLT_REGISTERS</id>
       <scomRegister>PERV_CPLT_STAT0</scomRegister>
       <scomRegister>PERV_CPLT_MASK0</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>PLL_LOCK_REG</id>
       <scomRegister>PERV_PLL_LOCK_REG</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>I2C_REGISTERS</id>
       <scomRegister>PU_CONTROL_REGISTER_B</scomRegister>
       <scomRegister>PU_STATUS_REGISTER_B</scomRegister>
       <scomRegister>PU_COMMAND_REGISTER_B</scomRegister>
       <scomRegister>PU_MODE_REGISTER_B</scomRegister>
       <scomRegister>PU_WATER_MARK_REGISTER_B</scomRegister>
       <scomRegister>PU_INTERRUPT_MASK_REGISTER_READ_B</scomRegister>
       <scomRegister>PU_INTERRUPT_COND_B</scomRegister>
       <scomRegister>PU_INTERRUPTS_B</scomRegister>
       <scomRegister>PU_STATUS_REGISTER_ENGINE_B</scomRegister>
       <scomRegister>PU_EXTENDED_STATUS_B</scomRegister>
       <scomRegister>PU_RESIDUAL_FRONT_END_BACK_END_LENGTH_B</scomRegister>
       <scomRegister>PU_I2C_BUSY_REGISTER_B</scomRegister>
    </registerFfdc>
    -->
    <registerFfdc>
       <id>PIBMEM_REGISTERS</id>
       <scomRegister>scomt::perv::OTPC_M_STATUS_REGISTER</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>I2C_REGISTERS</id>
       <scomRegister>scomt::perv::OTPC_M_STATUS_REGISTER</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>OTPROM_STATUS</id>
       <scomRegister>scomt::perv::OTPC_M_STATUS_REGISTER</scomRegister>
    </registerFfdc>
    <!--
    <registerFfdc>
       <id>OPCG_CTRL_REGISTERS</id>
       <scomRegister>PERV_OPCG_ALIGN</scomRegister>
       <scomRegister>PERV_OPCG_REG0</scomRegister>
       <scomRegister>PERV_OPCG_REG1</scomRegister>
       <scomRegister>PERV_OPCG_REG2</scomRegister>
    </registerFfdc>
    <registerFfdc>
       <id>CC_STATUS_REGISTERS</id>
       <scomRegister>PERV_SCAN_REGION_TYPE</scomRegister>
       <scomRegister>PERV_CLK_REGION</scomRegister>
       <scomRegister>PERV_CLOCK_STAT_SL</scomRegister>
       <scomRegister>PERV_CLOCK_STAT_NSL</scomRegister>
       <scomRegister>PERV_CLOCK_STAT_ARY</scomRegister>
       <scomRegister>PERV_BIST</scomRegister>
    </registerFfdc>
    <registerFfdc>
        <id>ERROR_STATUS_OF_CC</id>
        <scomRegister>PERV_ERROR_STATUS</scomRegister>
    </registerFfdc>
    <registerFfdc>
        <id>CC_REGISTERS</id>
        <scomRegister>PERV_XSTOP1</scomRegister>
        <scomRegister>PERV_XSTOP2</scomRegister>
        <scomRegister>PERV_XSTOP3</scomRegister>
        <scomRegister>PERV_OPCG_CAPT1</scomRegister>
        <scomRegister>PERV_OPCG_CAPT2</scomRegister>
        <scomRegister>PERV_OPCG_CAPT3</scomRegister>
        <scomRegister>PERV_DBG_CBS_CC</scomRegister>
     </registerFfdc>
     -->
     <registerFfdc>
        <id>SBE_EXTERNAL_SCOMMABLE_REGISTERS</id>
        <scomRegister>scomt::proc::TP_TPCHIP_PIB_SBE_SBEPM_SBEPPE_PPE_XIDBGPRO</scomRegister>
        <scomRegister>scomt::proc::TP_TPCHIP_PIB_SBE_SBEPM_SBEPPE_PPE_XIRAMEDR</scomRegister>
        <scomRegister>scomt::proc::TP_TPCHIP_PIB_SBE_SBEPM_SBEPPE_PPE_XIRAMDBG</scomRegister>
     </registerFfdc>
     <registerFfdc>
        <id>MIB_EXTERNAL_SCOMMABLE_REGISTERS</id>
        <scomRegister>scomt::proc::TP_TPCHIP_PIB_SBE_SBEPM_MIB_XISIB</scomRegister>
        <scomRegister>scomt::proc::TP_TPCHIP_PIB_SBE_SBEPM_SBEPPE_MIB_XIMEM</scomRegister>
        <scomRegister>scomt::proc::TP_TPCHIP_PIB_SBE_SBEPM_SBEPPE_MIB_XISGB</scomRegister>
        <scomRegister>scomt::proc::TP_TPCHIP_PIB_SBE_SBEPM_SBEPPE_MIB_XIICAC</scomRegister>
    </registerFfdc>
    <registerFfdc>
        <id>SBE_IPL_SCRATCH_REGISTERS</id>
        <cfamRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_1_FSI</cfamRegister>
        <cfamRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_2_FSI</cfamRegister>
        <cfamRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_FSI</cfamRegister>
        <cfamRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_4_FSI</cfamRegister>
        <cfamRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_5_FSI</cfamRegister>
        <cfamRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_6_FSI</cfamRegister>
        <cfamRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_7_FSI</cfamRegister>
        <cfamRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_FSI</cfamRegister>
    </registerFfdc>
    <registerFfdc>
        <id>SBE_IPL_SCRATCH_REGISTERS_SCOM</id>
        <scomRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_1_RW</scomRegister>
        <scomRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_2_RW</scomRegister>
        <scomRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_RW</scomRegister>
        <scomRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_4_RW</scomRegister>
        <scomRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_5_RW</scomRegister>
        <scomRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_6_RW</scomRegister>
        <scomRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_7_RW</scomRegister>
        <scomRegister> scomt::perv::FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_RW</scomRegister>
    </registerFfdc>
   <!-- ******************************************************************** -->
    <hwpError>
      <sbeError/>
      <rc>RC_INVALID_SBE_FFDC_PACKET</rc>
      <description>Invalid data detected in the SBE FFDC buffer</description>
      <buffer>FFDC_BUFFER</buffer>
      <ffdc>INVALID_ERRVAL</ffdc>
    </hwpError>
   <!-- ******************************************************************** -->
</hwpErrors>


text:
package eu.ydp.empiria.player.client.controller.data;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window.Navigator;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import eu.ydp.empiria.player.client.controller.ContentPreloader;
import eu.ydp.empiria.player.client.controller.communication.*;
import eu.ydp.empiria.player.client.controller.data.events.AssessmentDataLoaderEventListener;
import eu.ydp.empiria.player.client.controller.data.events.DataLoaderEventListener;
import eu.ydp.empiria.player.client.controller.data.events.ItemDataCollectionLoaderEventListener;
import eu.ydp.empiria.player.client.controller.data.library.LibraryExtension;
import eu.ydp.empiria.player.client.controller.data.library.LibraryLoader;
import eu.ydp.empiria.player.client.controller.data.library.LibraryLoaderListener;
import eu.ydp.empiria.player.client.module.item.ProgressToStringRangeMap;
import eu.ydp.empiria.player.client.style.StyleDocument;
import eu.ydp.empiria.player.client.util.file.DocumentLoadCallback;
import eu.ydp.empiria.player.client.util.file.xml.XmlData;
import eu.ydp.empiria.player.client.util.file.xml.XmlDocument;
import eu.ydp.gwtutil.client.PathUtil;

import java.util.ArrayList;
import java.util.List;

@Singleton
public class DataSourceManager implements AssessmentDataLoaderEventListener, ItemDataCollectionLoaderEventListener, DataSourceDataSupplier,
        LibraryLoaderListener {

    private StyleDataSourceManager styleDataSourceManager;

    private int styleLoadCounter;

    private final AssessmentDataSourceManager assessmentDataManager;
    private final ContentPreloader contentPreloader;
    private final ItemDataSourceCollectionManager itemDataCollectionManager;
    private final LibraryLoader libraryLoader;
    private DataSourceManagerMode mode;
    private DataLoaderEventListener listener;
    private XmlData assesmentXML;
    private final StyleDataSourceLoader styleDataSourceLoader;

    @Inject
    public DataSourceManager(AssessmentDataSourceManager assessmentDataManager, ItemDataSourceCollectionManager itemDataCollectionManager,
                             StyleDataSourceLoader styleDataSourceLoader, ContentPreloader contentPreloader) {
        this.assessmentDataManager = assessmentDataManager;
        this.assessmentDataManager.setSkinListener(this);
        this.itemDataCollectionManager = itemDataCollectionManager;
        this.styleDataSourceLoader = styleDataSourceLoader;
        this.contentPreloader = contentPreloader;

        mode = DataSourceManagerMode.NONE;
        itemDataCollectionManager.setLoaderEventListener(this);
        libraryLoader = new LibraryLoader(this);
    }

    public InitialData getInitialData() {
        InitialData initialData = new InitialData(itemDataCollectionManager.getItemsCount());
        for (int i = 0; i < itemDataCollectionManager.getItemsCount(); i++) {
            initialData.addItemInitialData(itemDataCollectionManager.getItemInitialData(i));
        }
        return initialData;
    }

    public AssessmentData getAssessmentData() {
        return assessmentDataManager.getAssessmentData();
    }

    public ItemData getItemData(int index) {
        return itemDataCollectionManager.getItemData(index);
    }

    @Override
    public int getItemsCount() {
        return assessmentDataManager.getItemsCount();
    }

    /**
     * Zwraca wezel assessmentItemRef o wskazanym id
     *
     * @param index index wezla
     * @return Element lub null gdy element o podanym indeksie nie istnieje
     */
    @Override
    public Element getItem(int itemIndex) {
        return assessmentDataManager.getItem(itemIndex);
    }

    public void loadMainDocument(String url) {
        if (mode == DataSourceManagerMode.LOADING_ASSESSMENT || mode == DataSourceManagerMode.LOADING_ITEMS || "".equals(url)) {
            return;
        }

        mode = DataSourceManagerMode.LOADING_ASSESSMENT;

        String resolvedURL;

        resolvedURL = PathUtil.resolvePath(url, GWT.getHostPageBaseURL());

        new eu.ydp.empiria.player.client.util.file.xml.XmlDocument(resolvedURL, new DocumentLoadCallback<Document>() {

            @Override
            public void finishedLoading(Document document, String baseURL) {
                assesmentXML = new XmlData(document, baseURL);
                assessmentDataManager.initializeAssessmentData(assesmentXML);
            }

            @Override
            public void loadingError(String error) {
                assessmentDataManager.setAssessmentLoadingError(error);
                onLoadFinished();
            }
        });
    }

    private void loadExtensionsLibrary() {
        String libraryUrl = assessmentDataManager.getLibraryLink();

        new XmlDocument(libraryUrl, new DocumentLoadCallback<Document>() {

            @Override
            public void finishedLoading(Document document, String baseURL) {
                libraryLoader.load(new XmlData(document, baseURL));
            }

            @Override
            public void loadingError(String error) {
                onExtensionsLoadFinished();
            }
        });

    }

    @Override
    public void onExtensionsLoadFinished() {
        loadItems();
    }

    private void loadItems() {
        loadItems(assessmentDataManager.getItemUrls());
    }

    private void loadItems(String[] urls) {

        mode = DataSourceManagerMode.LOADING_ITEMS;

        itemDataCollectionManager.initItemDataCollection(urls.length);

        if (urls.length == 0) {
            onItemCollectionLoaded();
        }

        for (int i = 0; i < urls.length; i++) {
            final int ii = i;

            new XmlDocument(urls[ii], new DocumentLoadCallback<Document>() {

                @Override
                public void finishedLoading(Document document, String baseURL) {
                    itemDataCollectionManager.setItemData(ii, new XmlData(document, baseURL));
                }

                @Override
                public void loadingError(String error) {
                    itemDataCollectionManager.setItemData(ii, error);
                }
            });
        }

    }

    private void loadSingleItemData(XmlData itemData) {
        itemDataCollectionManager.setItemDataCollection(new XmlData[]{itemData});
    }

    public void loadData(XmlData ad, XmlData[] ids) {
        assessmentDataManager.setAssessmentData(ad);
        itemDataCollectionManager.setItemDataCollection(ids);
    }

    public PageData generatePageData(PageReference ref) {
        PageData pd;

        if (assessmentDataManager.isError()) {
            pd = new PageDataError(assessmentDataManager.getErrorMessage());
            return pd;
        }

        if (ref.type == PageType.TOC) {
            pd = new PageDataToC(itemDataCollectionManager.getTitlesList());
        } else if (ref.type == PageType.SUMMARY) {
            pd = new PageDataSummary(itemDataCollectionManager.getTitlesList());
        } else {
            ItemData[] ids = new ItemData[ref.pageIndices.length];

            for (int i = 0; i < ref.pageIndices.length; i++) {
                ids[i] = itemDataCollectionManager.getItemData(ref.pageIndices[i]);
            }

            pd = new PageDataTest(ids, ref.flowOptions, ref.displayOptions);
        }

        return pd;
    }

    public List<String> getAssessmentStyleLinksForUserAgent(String userAgent) {
        return assessmentDataManager.getStyleLinksForUserAgent(userAgent);
    }

    public List<String> getPageStyleLinksForUserAgent(PageReference ref, String userAgent) {
        if (ref.pageIndices.length == 0) {
            return new ArrayList<>();
        }

        return itemDataCollectionManager.getStyleLinksForUserAgent(ref.pageIndices[0], userAgent);
    }

    @Override
    public void onAssessmentDataLoaded() {
        if (assessmentDataManager.isDefaultData()) {
            loadSingleItemData(assesmentXML);
        } else {
            if (assessmentDataManager.hasLibrary()) {
                loadExtensionsLibrary();
            } else {
                loadItems();
            }
        }

        listener.onAssessmentLoaded();
        mode = DataSourceManagerMode.SERVING;
    }

    @Override
    public void onItemCollectionLoaded() {
        // load item styles
        loadStyles();
    }

    private void loadStyles() {
        mode = DataSourceManagerMode.LOADING_STYLES;
        String userAgent = Navigator.getUserAgent();
        // load assesment styles
        List<String> aStyles = assessmentDataManager.getStyleLinksForUserAgent(userAgent);
        for (String styleURL : aStyles) {
            styleLoadCounter++;

            styleDataSourceLoader.load(styleURL, new DocumentLoadCallback<StyleDocument>() {

                @Override
                public void finishedLoading(StyleDocument value, String baseUrl) {
                    styleLoadCounter--;
                    styleDataSourceManager.addAssessmentStyle(value);
                    checkLoadFinished();
                }

                @Override
                public void loadingError(String message) {
                    styleLoadCounter--;
                    checkLoadFinished();
                }
            });

        }
        // load item styles
        int itemCount = itemDataCollectionManager.getItemsCount();
        for (int i = itemCount - 1; i >= 0; i--) {
            List<String> iStyles = itemDataCollectionManager.getStyleLinksForUserAgent(i, userAgent);
            for (String styleURL : iStyles) {
                final int ii = i;

                styleLoadCounter++;

                styleDataSourceLoader.load(styleURL, new DocumentLoadCallback<StyleDocument>() {

                    @Override
                    public void finishedLoading(StyleDocument value, String baseUrl) {
                        styleLoadCounter--;
                        styleDataSourceManager.addItemStyle(ii, value);
                        checkLoadFinished();
                    }

                    @Override
                    public void loadingError(String message) {
                        styleLoadCounter--;
                        checkLoadFinished();
                    }
                });

            }
        }

        checkLoadFinished();
    }

    private void checkLoadFinished() {
        if (styleLoadCounter == 0) {
            onLoadFinished();
        }
    }

    private void onLoadFinished() {
        contentPreloader.removePreloader();

        mode = DataSourceManagerMode.SERVING;
        // OperationLogManager.logEvent(OperationLogEvent.LOADING_FINISHED);

        listener.onDataReady();
    }

    public DataSourceManagerMode getMode() {
        return mode;
    }

    @Override
    public String getAssessmentTitle() {
        return assessmentDataManager.getAssessmentTitle();
    }

    @Override
    public String getItemTitle(int index) {
        return itemDataCollectionManager.getTitlesList()[index];
    }

    @Override
    public ProgressToStringRangeMap getItemFeedbacks(int index) {
        return itemDataCollectionManager.getFeedbacks(index);
    }

    @Inject
    public void setStyleDataSourceManager(StyleDataSourceManager styleDataSourceManager) {
        this.styleDataSourceManager = styleDataSourceManager;
    }

    public void setDataLoaderEventListener(DataLoaderEventListener listener) {
        this.listener = listener;
    }

    public List<LibraryExtension> getExtensionCreators() {
        return libraryLoader.getExtensionCreators();
    }

}

redpajama_set_name: RedPajamaGithub


text:
package Builder.Example2.entity;

/**
 * Created by Serhat CAN on 08.11.2015.
 *
 * @Description: This is Builder class
 */
public abstract class Address {

    protected String emailAddress;

    public abstract static class AddressBuilder {
        protected String emailAddress;

        public AddressBuilder emailAddress(String emailAddress) {
            this.emailAddress = emailAddress;
            return this;
        }

        public abstract Address build();

    }

    protected Address(AddressBuilder builder) {
        this.emailAddress = builder.emailAddress;
    }

    public String getEmailAddress() {
        return emailAddress;
    }
}


text:
#ifndef _MACH_MACHINE_THREAD_STATE_H_
#define _MACH_MACHINE_THREAD_STATE_H_

#if defined (__i386__) || defined(__x86_64__)
#include "mach/i386/thread_state.h"
#elif defined (__arm__) || defined (__arm64__)
#include "mach/arm/thread_state.h"
#else
#error architecture not supported
#endif

/* Size of maximum exported thread state in 32-bit words */
#define THREAD_STATE_MAX    1296

#endif /* _MACH_MACHINE_THREAD_STATE_H_ */


text:
using System.Collections.Generic;
using System.Linq;
using System.Data;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models.Agreement;

namespace SFA.DAS.ProviderApprenticeshipsService.Web.Extensions
{
    public static class EnumerableExtensions
    {
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> value)
        {
            return value == null || !value.Any();
        }

        public static DataTable ToDataTable(this IEnumerable<CommitmentAgreement> commitmentAgreements)
        {
            var dataTable = new DataTable("Agreements");

            var dataColumns = new[]
            {
                new DataColumn(nameof(CommitmentAgreement.OrganisationName)),
                new DataColumn(nameof(CommitmentAgreement.AgreementID))
            };

            dataTable.Columns.AddRange(dataColumns);

            foreach (var agreement in commitmentAgreements)
            {
                var row = dataTable.NewRow();
                row[0] = agreement.OrganisationName;
                row[1] = agreement.AgreementID;
                dataTable.Rows.Add(row);
            }

            dataTable.AcceptChanges();

            return dataTable;
        }
    }
}


text:
/**
 * Module Dependencies
 */

var app = require("../app");
var loopback = require('loopback');

var GeoPoint = loopback.GeoPoint;

var geoRest = app.dataSources.geoRest;

/**
 * location Model
 */
var RentalLocation = app.models.Location;

/**
 * inventory Model
 */
var Inventory = app.models.Inventory;

/**
 * Each location has inventory.
 */

RentalLocation.hasMany(Inventory);

/**
 * Find nearby locations.
 */

RentalLocation.nearby = function(here, page, max, fn) {
    if (typeof page === 'function') {
        fn = page;
        page = 0;
        max = 0;
    }

    if (typeof max === 'function') {
        fn = max;
        max = 0;
    }

    var limit = 10;
    page = page || 0;
    max = Number(max || 100000);

    RentalLocation.find({
        // find locations near the provided GeoPoint
        where: {
            geo: {
                near: here,
                maxDistance: max
            }
        },
        // paging
        skip: limit * page,
        limit: limit
    }, fn);
};

/**
 * Expose nearby as a remote method.
 */

loopback.remoteMethod(
    RentalLocation.nearby, {
        description: 'Find nearby locations around the geo point',
        accepts: [{
            arg: 'here',
            type: 'GeoPoint',
            required: true,
            description: 'geo location (lat & lng)'
        }, {
            arg: 'page',
            type: 'Number',
            description: 'number of pages (page size=10)'
        }, {
            arg: 'max',
            type: 'Number',
            description: 'max distance in miles'
        }],
        returns: {
            arg: 'locations',
            root: true
        }
    }
);

/**
 * Build the geo data when saving using the google maps api.
 */
RentalLocation.beforeSave = function(next, loc) {
    // geo code the address
    if (!loc.geo) {
        geoRest.geocode(loc.street, loc.city, loc.state, function(err, result, res) {
            if (result && result[0]) {
                loc.geo = result[0].lng + ',' + result[0].lat;
                next();
            } else {
                next(new Error('could not find location'));
            }
        });
    } else {
        next();
    }
};


text:
$:.unshift(File.dirname(File.expand_path(__FILE__)))
Dir.glob(File.join(File.dirname(__FILE__), 'classification/*_classifier.rb')).each {|f| require f }
$:.shift

module ActiveMailbox

  # Classification of IMAP server types.

  module Classification

    # Classify an IMAP server.

    class ImapClassifier

      include HostClassifier
      include ResponseClassifier
      include CapabilityClassifier

      # Directory that contains the classification config files.

      CLASSIFICATION_DIR  = "config/classification/"

      # Config file for server capabilities (should be in YAML format).

      CONFIG_CAPABILITIES = "capabilities.yml"

      # Config file for known hosts (should be in YAML format).

      CONFIG_HOSTS        = "hosts.yml"

      # Config file for known vendors (should be in YAML format).

      CONFIG_VENDORS      = "vendors.yml"

      # List of hosts that crash the protocol when an attempt is made to logout without being logged in.

      LOGOUT_NOT_ALLOWED  = %w(imap.laposte.net)

      attr_reader :host, :capabilities, :greeting_response, :bye_response

      class << self

        # Load information needed for the classification from config files.

        def load_config!
          @@hosts ||= begin
            YAML.load(File.open(CLASSIFICATION_DIR + CONFIG_HOSTS))
          rescue Errno::ENOENT
            Hash.new
          end
          @@capabilities ||= begin
            YAML.load(File.open(CLASSIFICATION_DIR + CONFIG_CAPABILITIES))
          rescue Errno::ENOENT
            Hash.new
          end
          @@vendors ||= begin
            YAML.load(File.open(CLASSIFICATION_DIR + CONFIG_VENDORS))
          rescue Errno::ENOENT
            Hash.new
          end
        end

        # Retrieve known vendors.

        def vendors
          if @@vendors
            @@vendors.keys
          else
            []
          end
        end

        # Retrieve fingerprints associated with a specific IMAP server.

        def fingerprints(key)
          unless @@vendors[key].nil? || (capability_lists = @@vendors[key][:capabilities]).nil?
            capability_lists.collect { |capability_ids|
              # get real names of capabilities and create ImapCapabilityArray
              Base::ImapCapabilityArray.new(capability_ids.collect { |id| @@capabilities[id] })
            }
          else
            []
          end
        end

        # Retrieve all hosts associated with a specific IMAP server.

        def hosts(key)
          unless @@vendors[key].nil?
            @@vendors[key][:hosts].collect { |id| @@hosts[id] }
          else
            []
          end
        end

      end

      # Creates a new ImapClassifier from given ImapConfig object.

      def initialize(config)
        @host   = config.host
        use_ssl = config.use_ssl
        port    = config.port
        certs   = config.certs
        verify  = config.verify

        connection = Net::IMAP.new(@host, port, use_ssl, certs, verify)

        @greeting_response = connection.greeting_response
        @capabilities = Base::ImapCapabilityArray.new(connection.capabilities)

        unless (LOGOUT_NOT_ALLOWED.include?(@host))
          connection.logout
          @bye_response = connection.bye_response
        end

        connection.disconnect
      end

      # Actual classification; returns name of adapter.

      def classify
        name = nil
        method = "Default Adapter"

        if classify_by_known_hosts?
          method = "Known Hosts"
          name = host_lookup
        end

        if name.nil?
          if classify_by_server_responses?
            method = "Greeting Response"
            name = greeting_lookup

            if name.nil?
              method = "Bye Response"
              name = bye_lookup
            end
          end
        end

        if name.nil?
          if classify_by_server_capabilities?
            method = "Capability Values"
            name = capability_lookup
          end
        end

        if !name.nil? && GlobalConfig.verbose
          puts "DEBUG: <#{name}> classified by <#{method}>"
        end

        return name
      end

      private

      def config
        GlobalConfig.classification
      end

      def classify_by_known_hosts?
        config.methods.known_hosts
      end

      def classify_by_server_responses?
        config.methods.server_responses
      end

      def classify_by_server_capabilities?
        config.methods.server_capabilities
      end

      def host_lookup
        begin
          classify_by_host_address(@host)
        rescue Errors::ClassificationFailed
          nil
        end
      end

      def greeting_lookup
        begin
          classify_by_server_response(@greeting_response)
        rescue Errors::ClassificationFailed
          nil
        end
      end

      def bye_lookup
        begin
          classify_by_server_response(@bye_response)
        rescue Errors::ClassificationFailed
          nil
        end
      end

      def capability_lookup
        begin
          classify_by_capabilities(@capabilities)
        rescue Errors::ClassificationFailed
          nil
        end
      end

    end

  end

end

ActiveMailbox::Classification::ImapClassifier.load_config!


text:
package com.cooldatasoft.jpa.data;

import static javax.persistence.CascadeType.MERGE;
import static javax.persistence.CascadeType.PERSIST;
import static javax.persistence.FetchType.LAZY;
import static javax.persistence.TemporalType.TIMESTAMP;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.springframework.data.jpa.domain.AbstractPersistable;
/**
 *
 * @author Fatih Mehmet UCAR
 *
 */
@Data
@Entity
@NoArgsConstructor
@Table(name = "customer_list_phone")
@EqualsAndHashCode(callSuper = false)
@JsonIgnoreProperties(value= {"new"})
public class CustomerListPhone extends AbstractPersistable<Long> {
	private static final long serialVersionUID = 1L;

	@NotNull
	@Column(name = "created_date", nullable = false, length = 19)
	@Temporal(TIMESTAMP)
	private Date createdDate;

	@Digits(integer = 10, fraction = 0)
	@NotNull
	@Column(name = "status", nullable = false, precision = 10)
	private Integer status;

	// -----------------------------------------------------------------
	// Many to One support
	// -----------------------------------------------------------------

	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	// many-to-one: CustomerListPhone.person ==> Person.id
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	@NotNull
	@JoinColumn(name = "person_id", nullable = false)
	@ManyToOne(cascade = { PERSIST, MERGE }, fetch = LAZY)
	private Person person;

	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	// many-to-one: CustomerListPhone.customerList ==> CustomerList.id
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	@NotNull
	@JoinColumn(name = "customer_list_id", nullable = false)
	@ManyToOne(cascade = { PERSIST, MERGE }, fetch = LAZY)
	private CustomerList customerList;

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="us.iturtleman.pingphone" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="com.microsoft.band.service.access.BIND_BAND_SERVICE" />

    <application android:icon="@drawable/app_icon" android:label="@string/app_name">
    <activity android:name=".MainActivity"
             android:label="@string/app_name"
             android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  </application>

</manifest>


text:
<?php

namespace Sabre\VObject;

use
    DateTime,
    DateTimeZone;

class RecurrenceIteratorMissingOverriddenTest extends \PHPUnit_Framework_TestCase {

    function testExpand() {

        $input = <<<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:foo
DTSTART:20130727T120000Z
DURATION:PT1H
RRULE:FREQ=DAILY;COUNT=2
SUMMARY:A
END:VEVENT
BEGIN:VEVENT
RECURRENCE-ID:20130728T120000Z
UID:foo
DTSTART:20140101T120000Z
DURATION:PT1H
SUMMARY:B
END:VEVENT
END:VCALENDAR
ICS;

        $vcal = Reader::read($input);
        $this->assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal);

        $vcal->expand(new DateTime('2011-01-01'), new DateTime('2015-01-01'));

        $result = $vcal->serialize();

        $output = <<<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:foo
DTSTART:20130727T120000Z
DURATION:PT1H
SUMMARY:A
RECURRENCE-ID:20130727T120000Z
END:VEVENT
BEGIN:VEVENT
RECURRENCE-ID:20130728T120000Z
UID:foo
DTSTART:20140101T120000Z
DURATION:PT1H
SUMMARY:B
END:VEVENT
END:VCALENDAR

ICS;
        $this->assertEquals($output, str_replace("\r","",$result));

    }

}


text:
describe("Exploration area", function() {
  var ExplorationArea = require("../src/modules/exploration_area");
  var areaSizeMock = { xAxis: 5, yAxis: 3 };
  var area;

  beforeEach(function() {
    area = new ExplorationArea(areaSizeMock);
  });

  it("creates an area object with an x axis", function() {
    expect(area.xAxis).toEqual(5);
  });

  it("reveals out of bounds coordinates", function() {
    expect(area.isOutOfBound(6, 1)).toBeTruthy();
  });

  it("reveals fatal coordinates", function() {
    area.markAsFatal(4, 3, "N");
    area.markAsFatal(4, 3, "N");
    expect(area.moveIsFatal(4, 3, "N")).toBeTruthy();
  });
});


text:
<html>
<head>
</head>
<body>
  <script src="jsdatasourcebin-debug.js"></script>
  <script src="chos_background-debug.js"></script>
</body>
</html>


text:
namespace blink {

class Body::ReadableStreamSource : public GarbageCollectedFinalized<Body::ReadableStreamSource>, public UnderlyingSource, public WebDataConsumerHandle::Client, public BodyStreamBuffer::DrainingStreamNotificationClient {
    USING_GARBAGE_COLLECTED_MIXIN(ReadableStreamSource);
public:
    ReadableStreamSource(ExecutionContext* executionContext, BodyStreamBuffer* buffer)
        : m_bodyStreamBuffer(buffer)
        , m_streamNeedsMore(false)
#if ENABLE(ASSERT)
        , m_drained(false)
        , m_isCloseCalled(false)
        , m_isErrorCalled(false)
#endif
    {
        if (m_bodyStreamBuffer)
            obtainReader();
    }

    ~ReadableStreamSource() override { }

    void startStream(ReadableByteStream* stream)
    {
        m_stream = stream;
        stream->didSourceStart();
        if (!m_bodyStreamBuffer)
            close();
    }
    // Creates a new BodyStreamBuffer to drain the data.
    PassOwnPtr<DrainingBodyStreamBuffer> createDrainingStream()
    {
        if (!m_bodyStreamBuffer)
            return nullptr;

#if ENABLE(ASSERT)
        ASSERT(!m_drained);
        m_drained = true;
        ASSERT(!(m_stream->stateInternal() == ReadableByteStream::Closed && !m_isCloseCalled));
        ASSERT(!(m_stream->stateInternal() == ReadableByteStream::Errored && !m_isErrorCalled));
#endif

        m_reader.clear();
        return DrainingBodyStreamBuffer::create(m_bodyStreamBuffer, this);
    }

    DEFINE_INLINE_VIRTUAL_TRACE()
    {
        visitor->trace(m_bodyStreamBuffer);
        visitor->trace(m_stream);
        UnderlyingSource::trace(visitor);
        DrainingStreamNotificationClient::trace(visitor);
    }

    void close()
    {
        m_reader.clear();
        m_stream->close();
        if (m_bodyStreamBuffer)
            m_bodyStreamBuffer = BodyStreamBuffer::createEmpty();
#if ENABLE(ASSERT)
        m_isCloseCalled = true;
#endif
    }

    void error()
    {
        m_reader.clear();
        m_stream->error(DOMException::create(NetworkError, "network error"));
        if (m_bodyStreamBuffer)
            m_bodyStreamBuffer = BodyStreamBuffer::create(createFetchDataConsumerHandleFromWebHandle(createUnexpectedErrorDataConsumerHandle()));
#if ENABLE(ASSERT)
        m_isErrorCalled = true;
#endif
    }

private:
    void obtainReader()
    {
        m_reader = m_bodyStreamBuffer->handle()->obtainReader(this);
    }

    void didFetchDataLoadFinishedFromDrainingStream() override
    {
        ASSERT(m_bodyStreamBuffer);
        ASSERT(m_drained);

#if ENABLE(ASSERT)
        m_drained = false;
#endif
        obtainReader();
        // We have to call didGetReadable() now to call close()/error() if
        // necessary.
        // didGetReadable() would be called asynchronously, but it is too late.
        didGetReadable();
    }

    void didGetReadable() override
    {
        if (!m_streamNeedsMore) {
            // Perform zero-length read to call close()/error() early.
            size_t readSize;
            WebDataConsumerHandle::Result result = m_reader->read(nullptr, 0, WebDataConsumerHandle::FlagNone, &readSize);
            switch (result) {
            case WebDataConsumerHandle::Ok:
            case WebDataConsumerHandle::ShouldWait:
                return;
            case WebDataConsumerHandle::Done:
                close();
                return;
            case WebDataConsumerHandle::Busy:
            case WebDataConsumerHandle::ResourceExhausted:
            case WebDataConsumerHandle::UnexpectedError:
                error();
                return;
            }
        }

        processData();
    }

    // UnderlyingSource functions.
    void pullSource() override
    {
        ASSERT(!m_streamNeedsMore);
        m_streamNeedsMore = true;

        ASSERT(!m_drained);

        processData();
    }

    ScriptPromise cancelSource(ScriptState* scriptState, ScriptValue reason) override
    {
        close();
        return ScriptPromise::cast(scriptState, v8::Undefined(scriptState->isolate()));
    }

    // Reads data and writes the data to |m_stream|, as long as data are
    // available and the stream has pending reads.
    void processData()
    {
        ASSERT(m_reader);
        while (m_streamNeedsMore) {
            const void* buffer;
            size_t available;
            WebDataConsumerHandle::Result result = m_reader->beginRead(&buffer, WebDataConsumerHandle::FlagNone, &available);
            switch (result) {
            case WebDataConsumerHandle::Ok:
                m_streamNeedsMore = m_stream->enqueue(DOMUint8Array::create(static_cast<const unsigned char*>(buffer), available));
                m_reader->endRead(available);
                break;

            case WebDataConsumerHandle::Done:
                close();
                return;

            case WebDataConsumerHandle::ShouldWait:
                return;

            case WebDataConsumerHandle::Busy:
            case WebDataConsumerHandle::ResourceExhausted:
            case WebDataConsumerHandle::UnexpectedError:
                error();
                return;
            }
        }
    }

    // Source of data.
    Member<BodyStreamBuffer> m_bodyStreamBuffer;
    OwnPtr<FetchDataConsumerHandle::Reader> m_reader;

    Member<ReadableByteStream> m_stream;
    bool m_streamNeedsMore;
#if ENABLE(ASSERT)
    bool m_drained;
    bool m_isCloseCalled;
    bool m_isErrorCalled;
#endif
};

ScriptPromise Body::readAsync(ScriptState* scriptState, ResponseType type)
{
    if (bodyUsed())
        return ScriptPromise::reject(scriptState, V8ThrowException::createTypeError(scriptState->isolate(), "Already read"));

    // When the main thread sends a V8::TerminateExecution() signal to a worker
    // thread, any V8 API on the worker thread starts returning an empty
    // handle. This can happen in Body::readAsync. To avoid the situation, we
    // first check the ExecutionContext and return immediately if it's already
    // gone (which means that the V8::TerminateExecution() signal has been sent
    // to this worker thread).
    ExecutionContext* executionContext = scriptState->executionContext();
    if (!executionContext)
        return ScriptPromise();

    lockBody();
    m_responseType = type;

    ASSERT(!m_resolver);
    m_resolver = ScriptPromiseResolver::create(scriptState);
    ScriptPromise promise = m_resolver->promise();

    if (m_stream->stateInternal() == ReadableStream::Closed) {
        resolveWithEmptyDataSynchronously();
    } else if (m_stream->stateInternal() == ReadableStream::Errored) {
        m_resolver->reject(m_stream->storedException());
        m_resolver.clear();
    } else {
        readAsyncFromDrainingBodyStreamBuffer(createDrainingStream(), mimeType());
    }
    return promise;
}

void Body::resolveWithEmptyDataSynchronously()
{
    // We resolve the resolver manually in order not to use member
    // variables.
    switch (m_responseType) {
    case ResponseAsArrayBuffer:
        m_resolver->resolve(DOMArrayBuffer::create(nullptr, 0));
        break;
    case ResponseAsBlob: {
        OwnPtr<BlobData> blobData = BlobData::create();
        blobData->setContentType(mimeType());
        m_resolver->resolve(Blob::create(BlobDataHandle::create(blobData.release(), 0)));
        break;
    }
    case ResponseAsText:
        m_resolver->resolve(String());
        break;
    case ResponseAsFormData:
        // TODO(yhirano): Implement this.
        ASSERT_NOT_REACHED();
        break;
    case ResponseAsJSON: {
        ScriptState::Scope scope(m_resolver->scriptState());
        m_resolver->reject(V8ThrowException::createSyntaxError(m_resolver->scriptState()->isolate(), "Unexpected end of input"));
        break;
    }
    case ResponseUnknown:
        ASSERT_NOT_REACHED();
        break;
    }
    m_resolver.clear();
}

void Body::readAsyncFromDrainingBodyStreamBuffer(PassOwnPtr<DrainingBodyStreamBuffer> buffer, const String& mimeType)
{
    if (!buffer) {
        resolveWithEmptyDataSynchronously();
        m_streamSource->close();
        return;
    }

    FetchDataLoader* fetchDataLoader = nullptr;

    switch (m_responseType) {
    case ResponseAsArrayBuffer:
        fetchDataLoader = FetchDataLoader::createLoaderAsArrayBuffer();
        break;

    case ResponseAsJSON:
    case ResponseAsText:
        fetchDataLoader = FetchDataLoader::createLoaderAsString();
        break;

    case ResponseAsBlob:
        fetchDataLoader = FetchDataLoader::createLoaderAsBlobHandle(mimeType);
        break;

    case ResponseAsFormData:
        // FIXME: Implement this.
        ASSERT_NOT_REACHED();
        return;

    default:
        ASSERT_NOT_REACHED();
        return;
    }

    buffer->startLoading(executionContext(), fetchDataLoader, this);
}

ScriptPromise Body::arrayBuffer(ScriptState* scriptState)
{
    return readAsync(scriptState, ResponseAsArrayBuffer);
}

ScriptPromise Body::blob(ScriptState* scriptState)
{
    return readAsync(scriptState, ResponseAsBlob);
}

ScriptPromise Body::formData(ScriptState* scriptState)
{
    return readAsync(scriptState, ResponseAsFormData);
}

ScriptPromise Body::json(ScriptState* scriptState)
{
    return readAsync(scriptState, ResponseAsJSON);
}

ScriptPromise Body::text(ScriptState* scriptState)
{
    return readAsync(scriptState, ResponseAsText);
}

ReadableByteStream* Body::body()
{
    UseCounter::count(executionContext(), UseCounter::FetchBodyStream);
    return m_stream;
}

bool Body::bodyUsed() const
{
    return m_bodyUsed || m_stream->isLocked();
}

void Body::lockBody(LockBodyOption option)
{
    ASSERT(!bodyUsed());
    if (option == PassBody)
        m_bodyUsed = true;
    ASSERT(!m_stream->isLocked());
    TrackExceptionState exceptionState;
    m_stream->getBytesReader(executionContext(), exceptionState);
    ASSERT(!exceptionState.hadException());
}

void Body::setBody(BodyStreamBuffer* buffer)
{
    m_streamSource = new ReadableStreamSource(executionContext(), buffer);
    m_stream = new ReadableByteStream(m_streamSource, new ReadableByteStream::StrictStrategy);
    m_streamSource->startStream(m_stream);
}

PassOwnPtr<DrainingBodyStreamBuffer> Body::createDrainingStream()
{
    return m_streamSource->createDrainingStream();
}

bool Body::hasPendingActivity() const
{
    if (executionContext()->activeDOMObjectsAreStopped())
        return false;
    if (m_resolver)
        return true;
    if (m_stream->isLocked())
        return true;
    return false;
}

DEFINE_TRACE(Body)
{
    visitor->trace(m_resolver);
    visitor->trace(m_stream);
    visitor->trace(m_streamSource);
    ActiveDOMObject::trace(visitor);
    FetchDataLoader::Client::trace(visitor);
}

Body::Body(ExecutionContext* context)
    : ActiveDOMObject(context)
    , m_bodyUsed(false)
    , m_responseType(ResponseType::ResponseUnknown)
    , m_streamSource(new ReadableStreamSource(context, nullptr))
    , m_stream(new ReadableByteStream(m_streamSource, new ReadableByteStream::StrictStrategy))
{
    m_streamSource->startStream(m_stream);
}

void Body::resolveJSON(const String& string)
{
    ASSERT(m_responseType == ResponseAsJSON);
    ScriptState::Scope scope(m_resolver->scriptState());
    v8::Isolate* isolate = m_resolver->scriptState()->isolate();
    v8::Local<v8::String> inputString = v8String(isolate, string);
    v8::TryCatch trycatch;
    v8::Local<v8::Value> parsed;
    if (v8Call(v8::JSON::Parse(isolate, inputString), parsed, trycatch))
        m_resolver->resolve(parsed);
    else
        m_resolver->reject(trycatch.Exception());
}

// FetchDataLoader::Client functions.
void Body::didFetchDataLoadFailed()
{
    if (!executionContext() || executionContext()->activeDOMObjectsAreStopped())
        return;

    if (m_resolver) {
        if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped()) {
            m_resolver.clear();
            return;
        }
        ScriptState* state = m_resolver->scriptState();
        ScriptState::Scope scope(state);
        m_resolver->reject(V8ThrowException::createTypeError(state->isolate(), "Failed to fetch"));
        m_resolver.clear();
    }
}

void Body::didFetchDataLoadedBlobHandle(PassRefPtr<BlobDataHandle> blobDataHandle)
{
    if (!executionContext() || executionContext()->activeDOMObjectsAreStopped())
        return;

    ASSERT(m_responseType == ResponseAsBlob);
    m_resolver->resolve(Blob::create(blobDataHandle));
    m_resolver.clear();
}

void Body::didFetchDataLoadedArrayBuffer(PassRefPtr<DOMArrayBuffer> arrayBuffer)
{
    if (!executionContext() || executionContext()->activeDOMObjectsAreStopped())
        return;

    ASSERT(m_responseType == ResponseAsArrayBuffer);
    m_resolver->resolve(arrayBuffer);
    m_resolver.clear();
}

void Body::didFetchDataLoadedString(const String& str)
{
    if (!executionContext() || executionContext()->activeDOMObjectsAreStopped())
        return;

    switch (m_responseType) {
    case ResponseAsJSON:
        resolveJSON(str);
        break;
    case ResponseAsText:
        m_resolver->resolve(str);
        break;
    default:
        ASSERT_NOT_REACHED();
    }

    m_resolver.clear();
}

} // namespace blink


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class AddComposerDevOption extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::table('projects', function (Blueprint $table) {
            $table->boolean('include_dev')->default(true);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::table('projects', function (Blueprint $table) {
            $table->dropColumn('include_dev');
        });
    }
}


text:
var crypto = require('crypto')
  , utils = require('utilities')
  , Responder = require('./responder').Responder
  , Negotiator = require('./responder/negotiator').Negotiator
  , errors = require('../response/errors')
  , response = require('../response')
  , mime = require('mime')
  , Templater = require('../template').Templater
  , _contentCache = {};

/**
  @name controller
  @namespace controller
*/
var controller = {};

/**
  @name controller.BaseController
  @constructor
*/
controller.BaseController = function () {
  /**
    @name controller.BaseController#responder
    @public
    @type controller.Responder
    @description Provides strategies for responding based on desired
    format
   */
  this.responder = new Responder();
  /**
    @name controller.BaseController#negotiator
    @public
    @type controller.Negotiator
    @description Handles content-negotiation for the response
   */
  this.negotiator = new Negotiator();
  /**
    @name controller.BaseController#request
    @public
    @type http.ServerRequest
    @description The raw http.ServerRequest object for this request/response
    cycle.
   */
  this.request = null;
  /**
    @name controller.BaseController#response
    @public
    @type http.ServerResponse
    @description The raw http.ServerResponse object for this request/response
    cycle.
   */
  this.response = null;
  /**
    @name controller.BaseController#params
    @public
    @type Object
    @description The parsed params for the request. Also passed as an arg
    to the action, added as an instance field for convenience.
   */
  this.params = null;
  /**
    @name controller.BaseController#cookies
    @public
    @type Object
    @description Cookies collection for the request
   */
  this.cookies = null;
  /**
    @name controller.BaseController#name
    @public
    @type String
    @description The name of the controller constructor function,
    in CamelCase with uppercase initial letter.
   */
  this.name = null;
  /**
    @name controller.BaseController#formats
    @public
    @type Array
    @description Content-type the controller can format the response in.
    @default ['txt']
   */
  this.formats = ['txt'];
  /**
    @name controller.BaseController#format
    @public
    @type {String}
    @description Determined by what format the client requests, and if the
    controller/action supports it. Built-in formats can be found in the enum
    controller.formats
   */
  this.completed = false;
  // The template root to look in for partials when rendering templates
  // Gets created programmatically based on controller name -- see renderTemplate
  this.template = null;
  // The template layout directory to look in when rendering templates
  // Gets created programmatically based on controller name -- see renderTemplate
  this.layout = null;
  // Time accessed
  this.accessTime = null;
  // Anti-CSRF token for PUT/POST/DELETE
  this.sameOriginToken = null;
  // The list of filters to perform before running the action
  this._beforeFilters = [];
  // The list of filters to perform before finishing the response
  this._afterFilters = [];
  // The list of actions whose responses may be cached
  this._cacheableActions = [];
};

controller.BaseController.prototype = new (function () {
  var _addFilter
    , _execFilters
    , _negotiateContent
    , _generateSameOriginToken
    , _protectFromForgery
    , _isActionCacheable
    , _isActionCached;

  /*
   *
   * Private utility methods
   *
  */
  _addFilter = function (phase, filter, opts) {
    var obj = {def: filter};

    obj.except = opts.except;
    obj.only = opts.only;
    obj.async = opts.async;

    this['_' + phase + 'Filters'].push(obj);
  };

  _execFilters = function (action, phase, callback) {
    var self = this
      , connectCompat = geddy.config.connectCompatibility
      , filters = this['_' + phase + 'Filters']
      , list = []
      , applyFilter = true // Default
      , filter
      , func
      , asyncArgs
        createAsyncWrappedFilter = function (def) {
          return function () {
            var args = Array.prototype.slice.call(arguments)
            // Pull off the continuation and run it separately
              , next = args.pop();
            def.apply(self, args);
            next();
          };
        };

    if (!filters) {
      callback();
    }

    // Execute the filters in the order they're defined
    for (var i = 0, ii = filters.length; i < ii; i++) {
      filter = filters[i];

      // See if the filter should run or not
      // NOTE: 'except' runs second, so it will win in the case where
      // an action is in both 'only' and 'except'
      applyFilter = true;
      if (filter.only) {
        if (typeof filter.only === 'string' && action !== filter.only) {
          applyFilter = false;
        }
        if (filter.only instanceof Array && filter.only.indexOf(action) === -1) {
          applyFilter = false;
        }
      }
      if (filter.except) {
        if (typeof filter.except === 'string' && action === filter.except) {
          applyFilter = false;
        }
        if (filter.except instanceof Array && filter.except.indexOf(action) > -1) {
          applyFilter = false;
        }
      }

      if (applyFilter) {
        // TODO: Wrap filters to prevent further execution when
        // a req/resp cycle is already completed (e.g., with a
        // redirect

        // Create an async wrapper for sync filters
        // Connect middleware is async by definition
        asyncArgs = connectCompat ?
            [this.request, this.response] : [];
        if (!filter.async) {
          func = createAsyncWrappedFilter(filter.def);
        }
        else {
          func = filter.def;
        }

        list.push({
            func: func
          , args: asyncArgs
          , callback: null
          , context: this
        });
      }
    }
    var chain = new utils.async.AsyncChain(list);

    chain.last = callback;
    chain.run();
  };

  _generateSameOriginToken = function () {
    var sha = crypto.createHash('sha1');

    sha.update(geddy.config.secret);
    sha.update(this.session.id);

    return sha.digest('hex');
  };

  _protectFromForgery = function (complete) {
    var methods = {PUT: true, POST: true, DELETE: true}
      , params = this.params
      , token = params.same_origin_token || params.sameOriginToken
      , forbidden = false;

    if (methods[this.method]) {
      if (!token) {
        forbidden = true;
      }
      else {
        if (_generateSameOriginToken.call(this) != token) {
          forbidden = true;
        }
      }
    }

    if (forbidden) {
      throw new errors.ForbiddenError(
          'Cross-site request not allowed.');
    }
    else {
      complete();
    }
  };

  _isActionCacheable = function (method, action) {
    return (this._cacheableActions.some(function (act) {
      return act == action;
    })) && method.toLowerCase() == 'get';
  };

  _getResponseCacheKey = function () {
    var params = this.params
      , cacheKey = params.controller + '/' + params.action + '/' + params.method;
    return cacheKey;
  };

  _setCachedResponse = function (statusCode, headers, content) {
    var cacheKey = _getResponseCacheKey.call(this);
    _contentCache[cacheKey] = {
      statusCode: statusCode
    , headers: headers
    , content: content
    };
  };

  _getCachedResponse = function () {
    var cacheKey = _getResponseCacheKey.call(this);
    return _contentCache[cacheKey];
  };

  /*
   *
   * Pseudo-private, non-API
   *
  */
  // Primary entry point for calling the action on a controller
  // Wraps the action so before and after filters can be run
  this._handleAction = function (action) {
    var self = this
      , callback
      , cachedResponse;

    // Wrap the actual action handling in a callback to use as the last
    // - method in the async chain of before filters
    callback = function () {
      if (!self.completed) {
        // Serve from cache if appropriate
        if (_isActionCacheable.apply(self, [self.params.method, action])
            && (cachedResponse = _getCachedResponse.call(self))) {
          self.output(cachedResponse.statusCode, cachedResponse.headers,
              cachedResponse.content);
        }
        // Otherwise run the action
        else {
          self[action].apply(self, [self.request, self.response, self.params]);
        }
      }
    };

    // Generate an anti-CSRF token
    if (geddy.config.secret && this.session) {
      this.sameOriginToken = _generateSameOriginToken.call(this);
    }

    if (this._beforeFilters.length) {
      _execFilters.apply(this, [action, 'before', callback]);
    }
    else {
      callback();
    }
  };

  this._doContentNegotiation = function (formatOverride, options) {
    var opts = options || {};
    var supportedFormats = opts.supportedFormats ||
            this.respondsWith || this.formats;

    this.negotiator.init(this.request.headers.accept, supportedFormats,
        this.params.format);
    return this.negotiator.negotiate(formatOverride) || {};
  };

  this._handleWithResponder = function (content, options) {
    var responder = this.responder
      , opts = options || {};

    if (typeof responder == 'function') {
      responder(this, content, opts);
    }
    else {
      responder.respond(this, content, opts);
    }
  };

  /*
   *
   * Public methods
   *
  */

  this.canRespondTo = function (formats) {
    this.formats = [].concat(formats); // Accept string or array param
  };

  this.cacheResponse = function (actions) {
    // Accept string or array param
    this._cacheableActions = this._cacheableActions.concat(actions);
  };

  /*
    @name controller.BaseController#before
    @public
    @function
    @description Adds an action to the beforeFilters list.
    @param {Function} filter Action to add to the beforeFilter list of
    actions to be performed before a response is rendered.
    @param {Object} [opts]
      @param {Array} [opts.except=null] List of actions where the
      before-filter should not be performed.
      @param {Array} [opts.only=null] This list of actions are the
      only actions where this before-filter should be performed
  */
  this.before = function (filter, options) {
    var opts = options || {};
    _addFilter.apply(this, ['before', filter, opts]);
  };

  /*
    @name controller.BaseController#after
    @public
    @function
    @description Adds an action to the afterFilters list of actions
      to be performed after a response is rendered.
    @param {Function} filter Action to add to the afterFilter list.
    @param {Object} [opts]
      @param {Array} [opts.except=null] List of actions where the
      after-filter should not be performed.
      @param {Array} [opts.only=null] This list of actions are the
      only actions where this after-filter should be performed.
  */
  this.after = function (filter, options) {
    var opts = options || {};
    _addFilter.apply(this, ['after', filter, opts]);
  };

  this.protectFromForgery = function (options) {
    var opts = options || {};

    if (!geddy.config.secret) {
      geddy.log.error('protectFromForgery requires an app-secret. ' +
          'Run `geddy secret` in your app.');
    }
    if (!geddy.config.sessions) {
      geddy.log.error('protectFromForgery requires sessions.');
    }
    if (typeof opts.async != 'undefined' && !opts.async) {
      geddy.log.error('protectFromForgery requires the async flag set to true.');
    }

    opts.async = true;
    // Add a before filter
    this.before(_protectFromForgery, opts);
  };

  /*
    @name controller.BaseController#output
    @public
    @function
    @description Lowest-level response function, actually outputs the response
    @param {Number} statusCode Either an URL, or an object literal containing
      controller/action/format attributes to base the redirect on.
    @param {Object} headers HTTP headers to include in the response
    @param {String} content The response-body
  */
  this.output = function (statusCode, headers, content) {
    // No repeatsies
    if (this.completed) {
      return;
    }

    this.completed = true;

    var self = this
      , r = this.response
      , action = this.params.action
      , callback;

    callback = function () {
      // Set status and headers, can be overridded with after filters
      if (self.cookies) {
        headers['Set-Cookie'] = self.cookies.toArray();
      }
      r.setHeaders(statusCode, headers);

      // Run after filters, then finish out the response
      _execFilters.apply(self, [action, 'after', function () {
        if (self.method == 'HEAD' || self.method == 'OPTIONS') {
          r.finish();
        }
        else {
          r.finalize(content);
        }
      }]);
    };

    if (this.session) {
      // Save access time into session for expiry and
      // - verifying sameOriginToken
      this.session.set('accessTime', this.accessTime);
      this.session.close(callback);
    }
    else {
      callback();
    }
  };

  /*
    @name controller.BaseController#redirect
    @public
    @function
    @description Sends a 302 redirect to the client, based on either a
      simple string-URL, or a controller/action/format combination.
    @param {String|Object} target Either an URL, or an object literal containing
      controller/action/format attributes to base the redirect on.
    @param {Object} [options] Options.
      @param {Number} [options.statusCode] The HTTP status-code to use for the
        redirect.
  */
  this.redirect = function (target, options) {
    var url
      , opts = options || {}
      , statusCode = opts.statusCode || 302;

    // Make sure it's a 3xx
    if (String(statusCode).indexOf('3') != 0) {
      throw new Error('Redirect status must be 3xx');
    }

    if (typeof target == 'string') {
      url = target
    }
    else if (typeof this.app.router.url == 'function') {
      if (this.name && !target.controller) {
        target.controller = this.name;
      }
      if (this.params.format && !target.format) {
        target.format = this.params.format;
      }
      url = this.app.router.url(target);
    }

    if (!url) {
      var contr = target.controller || this.name
        , act = target.action
        , ext = target.format || this.params.format
        , id = target.id;

      contr = utils.string.decamelize(contr);
      url = '/' + contr;
      url += act ? '/' + act : '';
      url += id ? '/' + id : '';
      if (ext) {
        url += '.' + ext;
      }
    }

    this.output(statusCode, { 'Location': url }, '');
  };

  this.error = function (err) {
    /*
      @name controller.BaseController#error
      @public
      @function
      @description Respond to a request with an appropriate HTTP error-code.
        If a status-code is set on the error object, uses that as the error's
        status-code. Otherwise, responds with a 500 for the status-code.
      @param {Object} err The error to use as the basis for the response. (May
        have an optional statusCode property added.)
    */
    this.completed = true;
    errors.respond(err, this.response);
  };

  this.transfer = function (action) {
    /*
      @name controller.BaseController#transfer
      @public
      @function
      @description Transfer a request from its original action to a new one. The
        entire request cycle is repeated, including before-filters.
      @param {Object} action The new action designated to handle the request.
    */
    this.params.action = action;
    this._handleAction(action);
  };

  /*
    @name controller.BaseController#respond
    @public
    @function
    @description Performs content-negotiation, and renders a response.
    @param {Object|String} content The content to use in the response.
    @param {Object} [opts] Options.
      @param {String} [options.format] The desired format for the response.
      @param {String} [options.template] The path (without file extensions)
        to the template to use to render this response.
      @param {String} [options.layout] The path (without file extensions)
        to the layout to use to render the template for this response.
      @param {Number} [options.statusCode] The HTTP status-code to use
        for the response.
  */
  this.respond = function (content, options) {
    var self = this
      , opts = options || {}
      , negotiated
      , cb = function (formattedContent) {
          var headers = {'Content-Type': opts.contentType}
            , statusCode = opts.statusCode || 200
            , params = self.params;;
          utils.mixin(headers, opts.headers);

          if (_isActionCacheable.apply(self, [params.method, params.action])) {
            _setCachedResponse.apply(self, [statusCode, headers, formattedContent]);
          }

          self.output(statusCode,  headers, formattedContent);
        }
      , cached
      , formatted;

    if (!(opts.format && opts.contentType)) {
      negotiated = this._doContentNegotiation(opts.format);
      if (Object.keys(negotiated).length) {
        utils.mixin(opts, negotiated);
      }
      else {
        throw new errors.UnsupportedMediaTypeError(
            'This format is not supported.');
      }
    }
    // Error during content negotiation may result in an error response, so
    // - don't continue
    // FIXME: Should the domain catch this now?
    if (this.completed) {
      return;
    }

    // HTML is special case, needs opts, is async
    if (opts.format == 'html') {
      this.setTemplateAndLayout(opts);
      this.renderTemplate(content, cb)
    }
    else {
      formatted = response.formatContent(this, content, opts);
      cb(formatted);
    }
  };

  /**
    @name controller.BaseController#respondWith
    @public
    @description Responds with a model or collection
    @param {Object} content - The model, collection, or hash of values
    @param {Object} [opts] Options.
  */
  this.respondWith = function (content, options) {
    var opts = options || {}
      , negotiated = this._doContentNegotiation(opts.format);
    utils.mixin(opts, negotiated);
    this._handleWithResponder(content, opts);
  };

  /**
    @name controller.BaseController#respondTo
    @public
    @description Delegates respond tasks to user-defined strategy functions
    @param {Object} [strategies] - The strategies to use.
      Will be run in the Responder context
      e.g { json: function () { // Do stuff here } }
  */
  this.respondTo = function (strategies, options) {
    var opts = options || {}
      , negotiated = this._doContentNegotiation(opts.format, {
          supportedFormats: Object.keys(strategies)
        });
    utils.mixin(opts, negotiated);
    opts.strategies = strategies;
    this._handleWithResponder(null, opts);
  };

  this.renderTemplate = function (d, callback) {
    var self = this
      , data = utils.mixin({}, d) // Prevent mixin-polution
      , templater
      , content = '';

    // Mix in controller instance-vars (props only, no methods)
    // Don't overwrite existing same-name properties
    for (var p in this) {
      if (!(data[p] || typeof this[p] == 'function')) {
        data[p] = this[p];
      }
    };

    templater = new Templater(this.layout, this.template, data);
    templater.render(callback);
  };

  this.setTemplateAndLayout = function (opts) {
      var controllerFilename =
              utils.string.getInflection(this.name, 'filename', 'plural')
        , actionFilename = utils.string.snakeize(this.params.action);

    // Set template and layout paths
    if (opts.template) {
      // If template includes full views path just use it
      if (opts.template.match('app/views/')) {
        this.template = opts.template;
      }
      else if (opts.template.match('/')) {
        // If it includes a '/' and it isn't the full path
        // Assume they are using the `controller/action` style
        // and prepend views dir
        this.template = 'app/views/' + opts.template;
      }
      // Assume they only included the action, so add the controller path
      else {
        this.template = 'app/views/' + controllerFilename + '/' + opts.template;
      }
    }
    else {
      this.template = 'app/views/' + controllerFilename + '/' + actionFilename;
    }

    if (opts.layout) {
      // If layout includes `app/views` just return it
      if (opts.layout.match('app/views')) {
        this.layout = opts.layout;
      }
      // If it includes a '/' and it isn't the full path
      // Assume they are using the `controller/action` style
      // and prepend views dir
      else if (opts.layout.match('/')) {
        this.layout = 'app/views/' + opts.layout;
      }
      // Assume they only included the controller, so append it to
      // the layouts path
      else {
        this.layout = 'app/views/layouts/' + opts.layout;
      }
    }
    else {
      // If options.layout is explicitly set to false, use custom
      // Geddy empty template in `lib/template/templates`
      if (opts.layout === false) {
        this.layout = 'geddy/empty';
      }
      else {
        this.layout = 'app/views/layouts/' + controllerFilename;
      }
    }

  };

})();

exports.BaseController = controller.BaseController;


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Codeer.Friendly;
using Codeer.Friendly.Dynamic;
using Codeer.Friendly.Windows;
using Codeer.Friendly.Windows.Grasp;
using Friendly.InputMan.Win;
using System.Diagnostics;
using Codeer.Friendly.Windows.NativeStandardControls;

namespace Test
{
    [TestClass]
    public class GcComboBoxTest
    {
        WindowsAppFriend _app;
        WindowControl _main;
        GcComboBoxDriver _comboBox;
        GcComboBoxDriver _comboBoxShiftJIS;

        [TestInitialize]
        public void TestInitialize()
        {
            _app = new WindowsAppFriend(Process.Start(Target.Path));
            _main = WindowControl.FromZTop(_app);
            _comboBox = new GcComboBoxDriver(_main.Dynamic()._comboBox);
            _comboBoxShiftJIS = new GcComboBoxDriver(_main.Dynamic()._comboBox_ShiftJIS);
        }

        [TestCleanup]
        public void TestCleanup()
        {
            Process.GetProcessById(_app.ProcessId).Kill();
        }

        [TestMethod]
        public void TestEmulateChangeText()
        {
            _comboBox.EmulateChangeText("abc");
            _comboBox.Text.Is("abc");
        }

        [TestMethod]
        public void TestEmulateChangeTextAsync()
        {
            _main.Dynamic().ConnectComboBoxTextChanged();
            _comboBox.EmulateChangeText("abc", new Async());
            new NativeMessageBox(_main.WaitForNextModal()).EmulateButtonClick("OK");
            _comboBox.Text.Is("abc");
        }

        [TestMethod]
        public void TestEmulateChangeSelect()
        {
            _comboBox.EmulateChangeSelect(1);
            _comboBox.SelectedItemIndex.Is(1);
            _comboBox.Text.Is("b");
        }

        [TestMethod]
        public void TestEmulateChangeSelectAsync()
        {
            _main.Dynamic().ConnectComboBoxTextChanged();
            _comboBox.EmulateChangeSelect(1, new Async());
            new NativeMessageBox(_main.WaitForNextModal()).EmulateButtonClick("OK");
            _comboBox.SelectedItemIndex.Is(1);
        }
        [TestMethod]
        public void TestEmulateChangeComboboxMaxLength()
        {
            string source = "012345678901234567890123456789012345678901234567890123456789";
            string destination = "01234567890123456789012345678901234567890123456789";

            _comboBox.EmulateChangeMaxLength(50);
            _comboBox.EmulateChangeText(source);
            _comboBox.Text.Is(destination);
        }

        [TestMethod]
        public void TestEmulateChangeComboboxMaxLengthAsync()
        {
            string source = "012345678901234567890123456789012345678901234567890123456789";
            string destination = "01234567890123456789012345678901234567890123456789";

            _main.Dynamic().ConnectComboBoxTextMaxLengthChanged();
            _comboBox.EmulateChangeMaxLength(50, new Async());
            _main.Dynamic().ConnectTextBoxTextChanged();
            _comboBox.EmulateChangeText(source, new Async());
            new NativeMessageBox(_main.WaitForNextModal()).EmulateButtonClick("OK");
            _comboBox.Text.Is(destination);
        }
        [TestMethod]
        public void TestEmulateChangeShiftJISComboBoxMaxLength()
        {
            string source = "0123456789あいうえお亜意宇絵尾";
            string destination = "0123456789あいうえお";

            _comboBoxShiftJIS.EmulateChangeText(source);
            _comboBoxShiftJIS.Text.Is(destination);
        }

        [TestMethod]
        public void TestEmulateChangeShiftJISComboBoxMaxLengthAsync()
        {
            string source = "0123456789あいうえお亜意宇絵尾";
            string destination = "0123456789あいうえお";

            _main.Dynamic().ConnectSJISComboBoxTextChanged();
            _comboBoxShiftJIS.EmulateChangeText(source, new Async());
            new NativeMessageBox(_main.WaitForNextModal()).EmulateButtonClick("OK");
            _comboBoxShiftJIS.Text.Is(destination);
        }
    }
}


text:
from twisted.enterprise import adbapi
from twisted.internet import defer
from twisted.python import log
import MySQLdb, uuid, time

class ReconnectingConnectionPool(adbapi.ConnectionPool):
    """Reconnecting adbapi connection pool for MySQL.

    This class improves on the solution posted at
    http://www.gelens.org/2008/09/12/reinitializing-twisted-connectionpool/
    by checking exceptions by error code and only disconnecting the current
    connection instead of all of them.

    Also see:
    http://twistedmatrix.com/pipermail/twisted-python/2009-July/020007.html

    """
    def _runInteraction(self, interaction, *args, **kw):
        try:
            return adbapi.ConnectionPool._runInteraction(
                self, interaction, *args, **kw)
        except MySQLdb.OperationalError, e:
            if e[0] not in (2006, 2013):
                raise
            log.msg("RCP: got error %s, retrying operation" %(e))
            conn = self.connections.get(self.threadID())
            self.disconnect(conn)
            # try the interaction again
            return adbapi.ConnectionPool._runInteraction(
                self, interaction, *args, **kw)

class DBLogger():
    def start(self, cfg):
        if cfg.has_option('database_mysql', 'port'):
            port = int(cfg.get('database_mysql', 'port'))
        else:
            port = 3306
        return ReconnectingConnectionPool('MySQLdb',
            host = cfg.get('database_mysql', 'host'),
            db = cfg.get('database_mysql', 'database'),
            user = cfg.get('database_mysql', 'username'),
            passwd = cfg.get('database_mysql', 'password'),
            port = port,
            cp_min = 1,
            cp_max = 1)

    def setClient(self, dblog, cfg):
        self.db = dblog
        self.cfg = cfg

    def sqlerror(self, error):
        print 'SQL Error:', error.value

    def simpleQuery(self, sql, args):
        """ Just run a deferred sql query, only care about errors """
        d = self.db.runQuery(sql, args)
        d.addErrback(self.sqlerror)

    def createSession(self, sid, peerIP, peerPort, hostIP, hostPort):
        self.createSessionWhenever(sid, peerIP, peerPort, hostIP, hostPort)

    # This is separate since we can't return with a value
    @defer.inlineCallbacks
    def createSessionWhenever(self, sid, peerIP, peerPort, hostIP, hostPort):
        sensorname = self.cfg.get('honeypot','sensor_name')
        r = yield self.db.runQuery('SELECT `id` FROM `sensors` WHERE `ip` = %s AND `name` = %s AND `port` = %s', (hostIP, sensorname, hostPort))
        if r:
            id = r[0][0]
        else:
            yield self.db.runQuery('INSERT INTO `sensors` (`ip`, `name`, `port`) VALUES (%s, %s, %s)', (hostIP, sensorname, hostPort))
            r = yield self.db.runQuery('SELECT LAST_INSERT_ID()')
            id = int(r[0][0])
        # now that we have a sensorID, continue creating the session
        self.simpleQuery('INSERT INTO `sessions` (`id`, `starttime`, `sensor`, `ip`, `port`) VALUES (%s, FROM_UNIXTIME(%s), %s, %s, %s)', (sid, self.nowUnix(), id, peerIP, peerPort))

    def nowUnix(self):
        """return the current UTC time as an UNIX timestamp"""
        return int(time.mktime(time.gmtime()[:-1] + (-1,)))

    def handleConnectionLost(self, sid):
        self.simpleQuery('UPDATE `sessions` SET `endtime` = FROM_UNIXTIME(%s) WHERE `id` = %s', (self.nowUnix(), sid))

    def handleLoginFailed(self, username, password):
        self.simpleQuery('INSERT INTO `auth` (`success`, `username`, `password`, `timestamp`) VALUES (%s, %s, %s, FROM_UNIXTIME(%s))', (0, username, password, self.nowUnix()))

    def handleLoginSucceeded(self, username, password):
        self.simpleQuery('INSERT INTO `auth` (`success`, `username`, `password`, `timestamp`) VALUES (%s, %s, %s, FROM_UNIXTIME(%s))', ( 1, username, password, self.nowUnix()))

    def channelOpened(self, sessionID, uuid, channelName):
        self.simpleQuery('INSERT INTO `channels` (`id`, `type`, `starttime`, `sessionid`) VALUES (%s, %s, FROM_UNIXTIME(%s), %s)', (uuid, channelName, self.nowUnix(), sessionID))

    def channelClosed(self, uuid, ttylog=None):
        self.simpleQuery('UPDATE `channels` SET `endtime` = FROM_UNIXTIME(%s) WHERE `id` = %s', (self.nowUnix(), uuid))
        if ttylog != None:
            fp = open(ttylog, 'rb')
            ttydata = fp.read()
            fp.close()
            self.simpleQuery('INSERT INTO `ttylog` (`channelid`, `ttylog`) VALUES (%s, %s)', (uuid, ttydata))

    def handleCommand(self, uuid, theCommand):
        self.simpleQuery('INSERT INTO `commands` (`timestamp`, `channelid`, `command`) VALUES (FROM_UNIXTIME(%s), %s, %s)', (self.nowUnix(), uuid, theCommand))

    @defer.inlineCallbacks
    def handleClientVersion(self, session, version):
        r = yield self.db.runQuery('SELECT `id` FROM `clients` WHERE `version` = %s', (version))
        if r:
            id = int(r[0][0])
        else:
            yield self.db.runQuery('INSERT INTO `clients` (`version`) VALUES (%s)', (version))
            r = yield self.db.runQuery('SELECT LAST_INSERT_ID()')
            id = int(r[0][0])
        self.simpleQuery('UPDATE `sessions` SET `client` = %s WHERE `id` = %s', (id, session))

    def handleFileDownload(self, uuid, url, outfile):
        self.simpleQuery('INSERT INTO `downloads` (`channelid`, `timestamp`, `url`, `outfile`) VALUES (%s, FROM_UNIXTIME(%s), %s, %s)', (uuid, self.nowUnix(), url, outfile))


text:
(
    cd android/PhysicalWeb/
    # This will run our linters etc.
    # NOTE: check depends on assembleDebug
    ./gradlew check
    ./gradlew test
)

# Test the Physical Web java libraries
(
    cd java/libs
    ./gradlew check
    ./gradlew test
)


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //设置缓存
    NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 *1024 diskCapacity:20 *1024 *1024 diskPath:nil];
    [NSURLCache setSharedURLCache:cache];
    //设置网络指示器
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    return YES;
}

@end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xinfan.wxshop.business.dao.WalletMapper" >
  <resultMap id="BaseResultMap" type="com.xinfan.wxshop.business.entity.Wallet" >
    <id column="wallet_id" property="walletId" jdbcType="INTEGER" />
    <result column="customer_id" property="customerId" jdbcType="INTEGER" />
    <result column="balance" property="balance" jdbcType="REAL" />
    <result column="distr_balance" property="distrBalance" jdbcType="REAL" />
    <result column="distr_count" property="distrCount" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    wallet_id, customer_id, balance, distr_balance, distr_count
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.xinfan.wxshop.business.entity.WalletExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from t_wallet
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select
    <include refid="Base_Column_List" />
    from t_wallet
    where wallet_id = #{walletId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_wallet
    where wallet_id = #{walletId,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.xinfan.wxshop.business.entity.WalletExample" >
    delete from t_wallet
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.xinfan.wxshop.business.entity.Wallet" >
    insert into t_wallet (wallet_id, customer_id, balance,
      distr_balance, distr_count)
    values (#{walletId,jdbcType=INTEGER}, #{customerId,jdbcType=INTEGER}, #{balance,jdbcType=REAL},
      #{distrBalance,jdbcType=REAL}, #{distrCount,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.xinfan.wxshop.business.entity.Wallet" >
    insert into t_wallet
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="walletId != null" >
        wallet_id,
      </if>
      <if test="customerId != null" >
        customer_id,
      </if>
      <if test="balance != null" >
        balance,
      </if>
      <if test="distrBalance != null" >
        distr_balance,
      </if>
      <if test="distrCount != null" >
        distr_count,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="walletId != null" >
        #{walletId,jdbcType=INTEGER},
      </if>
      <if test="customerId != null" >
        #{customerId,jdbcType=INTEGER},
      </if>
      <if test="balance != null" >
        #{balance,jdbcType=REAL},
      </if>
      <if test="distrBalance != null" >
        #{distrBalance,jdbcType=REAL},
      </if>
      <if test="distrCount != null" >
        #{distrCount,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.xinfan.wxshop.business.entity.WalletExample" resultType="java.lang.Integer" >
    select count(*) from t_wallet
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update t_wallet
    <set >
      <if test="record.walletId != null" >
        wallet_id = #{record.walletId,jdbcType=INTEGER},
      </if>
      <if test="record.customerId != null" >
        customer_id = #{record.customerId,jdbcType=INTEGER},
      </if>
      <if test="record.balance != null" >
        balance = #{record.balance,jdbcType=REAL},
      </if>
      <if test="record.distrBalance != null" >
        distr_balance = #{record.distrBalance,jdbcType=REAL},
      </if>
      <if test="record.distrCount != null" >
        distr_count = #{record.distrCount,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update t_wallet
    set wallet_id = #{record.walletId,jdbcType=INTEGER},
      customer_id = #{record.customerId,jdbcType=INTEGER},
      balance = #{record.balance,jdbcType=REAL},
      distr_balance = #{record.distrBalance,jdbcType=REAL},
      distr_count = #{record.distrCount,jdbcType=INTEGER}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.xinfan.wxshop.business.entity.Wallet" >
    update t_wallet
    <set >
      <if test="customerId != null" >
        customer_id = #{customerId,jdbcType=INTEGER},
      </if>
      <if test="balance != null" >
        balance = #{balance,jdbcType=REAL},
      </if>
      <if test="distrBalance != null" >
        distr_balance = #{distrBalance,jdbcType=REAL},
      </if>
      <if test="distrCount != null" >
        distr_count = #{distrCount,jdbcType=INTEGER},
      </if>
    </set>
    where wallet_id = #{walletId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.xinfan.wxshop.business.entity.Wallet" >
    update t_wallet
    set customer_id = #{customerId,jdbcType=INTEGER},
      balance = #{balance,jdbcType=REAL},
      distr_balance = #{distrBalance,jdbcType=REAL},
      distr_count = #{distrCount,jdbcType=INTEGER}
    where wallet_id = #{walletId,jdbcType=INTEGER}
  </update>
</mapper>


text:
package me.carbou.mathieu.tictactoe.db;

import java.time.Clock;

/**
 * @author Mathieu Carbou (mathieu.carbou@gmail.com)
 */
public final class DB {

    public static final int NO_LIMIT = 0;

    final com.mongodb.DB mongoDB;
    final Clock clock;

    public final DBCollection users;
    public final DBCollection games;

    public DB(com.mongodb.DB mongoDB, Clock clock) {
        this.mongoDB = mongoDB;
        this.clock = clock;
        this.users = new DBCollection(this, "users");
        this.games = new DBCollection(this, "games");
    }

    public void close() {
        mongoDB.getMongo().close();
    }

}


text:
=========
killproc
=========

Introduction
============
*killproc* is a command-line utility to terminate or killl Unix processes by name. The standard Unix
*kill* command identifies processes by process id, rather than by process name. For example, to terminate instances of the django-admin.py script, one might use the following sequence::

  $  ps -ef | grep django-admin.py | grep -v grep
  501 20060     1   0   0:00.11 ttys001    0:00.38 python django-admin.py runserver 0.0.0.0:8002
  501 20063 20060   0   0:00.35 ttys001    0:01.07 python django-admin.py runserver 0.0.0.0:8002
  $ kill -TERM 20060 20063
  $ ps -ef | grep django-admin.py | grep -v grep

Running the extra *ps* command and picking out process ids from its output can get rather
tedious.

*killproc* automates this sequence: you provide part of a process name and it executes *ps*, filtering
the results by matching the process name fragment with the CMD column of the *ps* output. For each
match, the user is prompted whether they wish to terminate the process (the prompting can be turned
off via a command line option). Accomplishing the above task with *killproc* might look as follows::

  killproc django-admin.py
  python django-admin.py runserver 0.0.0.0:8002
  Kill process 20106? [y] y
  Sending signal SIGTERM to process 20106
  python django-admin.py runserver 0.0.0.0:8002
  Kill process 20109? [y] y
  Sending signal SIGTERM to process 20109
  Sent signal SIGTERM to 2 processes

Supported Platforms
===================
*killproc* has been tested on Mac OSX and Ubuntu Linux. It is expected to work on most Linux and BSD variants.

Installation
============
*killproc* is written in Python and packaged using `setuptools <http://pypi.python.org/pypi/setuptools>`_. It has been registered
on `PyPi <http://pipi.python.org/pypi>`_ under *killproc*. Thus, if you have Python and setuptools installed on your machine,
you can run install it via easy_install::

  easy_install killproc

or pip::

  pip killproc

Either command will place the Python package in your Python environment and create the *killproc* script in your Python's binary
directory (thus making it available in your PATH).

The file killproc.py can function as a standalone command line utility. Thus, as an alternative installation approach, you can grab the
killproc.py file out of the source distribution, place it in a directory on your executable path, rename it to killproc, and add execute
permissions.

Usage
=====
The command line format for killproc is::

  killproc [options] process_name

The available options are::

   -h, --help            show help message and exit
   -k, --with-extreme-prejudice
                          If specified, use SIGKILL (default is SIGTERM)
   -s SIGNAL_NO, --signal=SIGNAL_NO
                          Use the specified signal. Defaults to 15 (SIGTERM)
   -n, --non-interactive
                          If specified, don't ask user for confirmation

Caveats, Limitations and Future Enhancements
============================================
Matching processes are not filtered by user. If the processes of other users match the process name fragment, the *killproc*
user will be prompted for those users as well, and the termination of those processes will fail. As a future enhancement,
*killproc* should return only matching processes of the current user by default, with a command line option to return
matches for all users (useful when running as root or sudo).

It would be nice to interpret the process name fragment as a regular expression to be matched against running commands.
However, this should not be the default behavior.


text:
Public Class StringForm

    ' Executes the editor.
    Public Shared Function GetString(ByVal value As String) As String
        Dim instance As New StringForm()
        instance.TextBox1.Text = value
        If instance.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Return instance.TextBox1.Text
        Else
            Return value
        End If
    End Function

End Class