text:
package org.kuali.kra.proposaldevelopment.bo;

import org.apache.struts.upload.FormFile;
import org.kuali.kra.bo.KcAttachment;
import org.kuali.kra.bo.KraPersistableBusinessObjectBase;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.infrastructure.TaskName;
import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument;
import org.kuali.kra.proposaldevelopment.document.authorization.NarrativeTask;
import org.kuali.kra.proposaldevelopment.hierarchy.HierarchyMaintainable;
import org.kuali.kra.proposaldevelopment.web.struts.form.ProposalDevelopmentForm;
import org.kuali.kra.service.KcAttachmentService;
import org.kuali.kra.service.TaskAuthorizationService;
import org.kuali.rice.kns.util.KNSGlobalVariables;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * This class is BO for narrarive
 */
public class Narrative extends KraPersistableBusinessObjectBase implements HierarchyMaintainable, KcAttachment {

    private String proposalNumber;

    private Integer moduleNumber;

    private String comments;

    private String contactName;

    private String emailAddress;

    private Integer moduleSequenceNumber;

    private String moduleStatusCode;

    private String moduleTitle;

    private String narrativeTypeCode;

    private String phoneNumber;

    private NarrativeType narrativeType;

    private NarrativeStatus narrativeStatus;

    private String fileName;

    private String contentType;

    private List<NarrativeUserRights> narrativeUserRights;

    private List<NarrativeAttachment> narrativeAttachmentList;

    private transient FormFile narrativeFile;

    private Timestamp timestampDisplay;

    private String uploadUserDisplay;

    private String uploadUserFullName;

    private String hierarchyProposalNumber;

    private boolean hiddenInHierarchy;

    public Narrative() {
        narrativeAttachmentList = new ArrayList<NarrativeAttachment>(1);
        narrativeUserRights = new ArrayList<NarrativeUserRights>();
    }

    public Integer getModuleNumber() {
        return moduleNumber;
    }

    public void setModuleNumber(Integer moduleNumber) {
        this.moduleNumber = moduleNumber;
    }

    public String getProposalNumber() {
        return proposalNumber;
    }

    public void setProposalNumber(String proposalNumber) {
        this.proposalNumber = proposalNumber;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public Integer getModuleSequenceNumber() {
        return moduleSequenceNumber;
    }

    public void setModuleSequenceNumber(Integer moduleSequenceNumber) {
        this.moduleSequenceNumber = moduleSequenceNumber;
    }

    public String getModuleStatusCode() {
        return moduleStatusCode;
    }

    public void setModuleStatusCode(String moduleStatusCode) {
        this.moduleStatusCode = moduleStatusCode;
    }

    public String getModuleTitle() {
        return moduleTitle;
    }

    public void setModuleTitle(String moduleTitle) {
        this.moduleTitle = moduleTitle;
    }

    public String getNarrativeTypeCode() {
        return narrativeTypeCode;
    }

    public void setNarrativeTypeCode(String narrativeTypeCode) {
        this.narrativeTypeCode = narrativeTypeCode;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public NarrativeType getNarrativeType() {
        return narrativeType;
    }

    public void setNarrativeType(NarrativeType narrativeType) {
        this.narrativeType = narrativeType;
    }

    public List<NarrativeUserRights> getNarrativeUserRights() {
        if (narrativeUserRights != null) {
            Collections.sort(this.narrativeUserRights, new Comparator() {

                public int compare(Object o1, Object o2) {
                    NarrativeUserRights r1 = (NarrativeUserRights) o1;
                    NarrativeUserRights r2 = (NarrativeUserRights) o2;
                    if (r1 == null || r2 == null) return 0;
                    String name1 = r1.getPersonName();
                    String name2 = r2.getPersonName();
                    if (name1 == null || name2 == null) return 0;
                    return name1.compareTo(name2);
                }
            });
        }
        return narrativeUserRights;
    }

    public void setNarrativeUserRights(List<NarrativeUserRights> narrativeUserRights) {
        this.narrativeUserRights = narrativeUserRights;
    }

    /**
     * Gets the narrativeStatus attribute.
     *
     * @return Returns the narrativeStatus.
     */
    public NarrativeStatus getNarrativeStatus() {
        return narrativeStatus;
    }

    /**
     * Sets the narrativeStatus attribute value.
     *
     * @param narrativeStatus The narrativeStatus to set.
     */
    public void setNarrativeStatus(NarrativeStatus narrativeStatus) {
        this.narrativeStatus = narrativeStatus;
    }

    public List<NarrativeAttachment> getNarrativeAttachmentList() {
        return narrativeAttachmentList;
    }

    public void setNarrativeAttachmentList(List<NarrativeAttachment> narrativePdfList) {
        this.narrativeAttachmentList = narrativePdfList;
    }

    public FormFile getNarrativeFile() {
        return narrativeFile;
    }

    public void setNarrativeFile(FormFile narrativeFile) {
        this.narrativeFile = narrativeFile;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    /**
     *
     * This method is to return institutional attachment type.  This column does not exist in table.
     * Basically, it is for narrativetypecode in table.
     * @return
     */
    public String getInstitutionalAttachmentTypeCode() {
        return narrativeTypeCode;
    }

    /**
     *
     * This method set the institutional attachment type.  Since instituteattachmenttypecode is set as 'required' in DD.
     * So, it is set to narrativetypecode, and hence to return narrative type code.
     * @param institutionalAttachmentTypeCode
     */
    public void setInstitutionalAttachmentTypeCode(String institutionalAttachmentTypeCode) {
        //this.institutionalAttachmentTypeCode = institutionalAttachmentTypeCode;
        this.narrativeTypeCode = institutionalAttachmentTypeCode;
    }

    /**
     * Can the current user download (view) the attachment?
     * @param userId
     * @return true if the user can view the attachment; otherwise false
     */
    public boolean getDownloadAttachment(String userId) {
        if (getNarrativeUserRights().isEmpty()) {
            refreshReferenceObject("narrativeUserRights");
        }
        TaskAuthorizationService taskAuthorizationService = KraServiceLocator.getService(TaskAuthorizationService.class);
        return taskAuthorizationService.isAuthorized(userId, new NarrativeTask(TaskName.DOWNLOAD_NARRATIVE, getDocument(), this));
    }

    /**
     * Can the current user replace the attachment?
     * @return true if the user can replace the attachment; otherwise false
     */
    public boolean getReplaceAttachment(String userId) {
        if (getNarrativeUserRights().isEmpty()) {
            refreshReferenceObject("narrativeUserRights");
        }
        TaskAuthorizationService taskAuthorizationService = KraServiceLocator.getService(TaskAuthorizationService.class);
        return taskAuthorizationService.isAuthorized(userId, new NarrativeTask(TaskName.REPLACE_NARRATIVE, getDocument(), this));
    }

    /**
     * Can the current user delete the attachment?
     * @return true if the user can delete the attachment; otherwise false
     */
    public boolean getDeleteAttachment(String userId) {
        if (getNarrativeUserRights().isEmpty()) {
            refreshReferenceObject("narrativeUserRights");
        }
        TaskAuthorizationService taskAuthorizationService = KraServiceLocator.getService(TaskAuthorizationService.class);
        return taskAuthorizationService.isAuthorized(userId, new NarrativeTask(TaskName.DELETE_NARRATIVE, getDocument(), this));
    }

    /**
     * Can the current user change the status of attachment?
     * @return true if the user can modify the status of attachments; otherwise false
     */
    public boolean getModifyAttachmentStatus(String userId) {
        if(getNarrativeUserRights().isEmpty()) {
            refreshReferenceObject("narrativeUserRights");
        }
        TaskAuthorizationService taskAuthorizatioNService = KraServiceLocator.getService(TaskAuthorizationService.class);
        return taskAuthorizatioNService.isAuthorized(userId, new NarrativeTask(TaskName.MODIFY_NARRATIVE_STATUS, getDocument(), this));
    }

    /**
     * Can the current user modify the user rights for the attachment?
     * @return true if the user can modify the user rights; otherwise false
     */
    public boolean getModifyNarrativeRights(String userId) {
        if (getNarrativeUserRights().isEmpty()) {
            refreshReferenceObject("narrativeUserRights");
        }
        TaskAuthorizationService taskAuthorizationService = KraServiceLocator.getService(TaskAuthorizationService.class);
        return taskAuthorizationService.isAuthorized(userId, new NarrativeTask(TaskName.MODIFY_NARRATIVE_RIGHTS, getDocument(), this));
    }

    /**
     * Get the Proposal Development Document for the current session.  The
     * document is within the current form.
     *
     * @return the current document or null if not found
     */
    private ProposalDevelopmentDocument getDocument() {
        ProposalDevelopmentDocument doc = null;
        ProposalDevelopmentForm form = (ProposalDevelopmentForm) KNSGlobalVariables.getKualiForm();
        if (form != null) {
            doc = form.getProposalDevelopmentDocument();
        }
        return doc;
    }

    /**
     *
     * This method used to populate the attachment to narrative object by reading FormFile
     */
    public void populateAttachment() {
        FormFile narrativeFile = getNarrativeFile();
        if (narrativeFile == null) return;
        byte[] narrativeFileData;
        try {
            narrativeFileData = narrativeFile.getFileData();
            if (narrativeFileData.length > 0) {
                NarrativeAttachment narrativeAttachment;
                if (getNarrativeAttachmentList().isEmpty()) {
                    narrativeAttachment = new NarrativeAttachment();
                    getNarrativeAttachmentList().add(narrativeAttachment);
                } else {
                    narrativeAttachment = getNarrativeAttachmentList().get(0);
                    if (narrativeAttachment == null) {
                        narrativeAttachment = new NarrativeAttachment();
                        getNarrativeAttachmentList().set(0, narrativeAttachment);
                    }
                }
                String fileName = narrativeFile.getFileName();
                narrativeAttachment.setFileName(fileName);
                narrativeAttachment.setContentType(narrativeFile.getContentType());
                narrativeAttachment.setNarrativeData(narrativeFile.getFileData());
                narrativeAttachment.setProposalNumber(getProposalNumber());
                narrativeAttachment.setModuleNumber(getModuleNumber());
                setFileName(narrativeAttachment.getFileName());
                setContentType(narrativeAttachment.getContentType());
            } else {
                getNarrativeAttachmentList().clear();
            }
        } catch (FileNotFoundException e) {
            getNarrativeAttachmentList().clear();
        } catch (IOException e) {
            getNarrativeAttachmentList().clear();
        }
    }

    /**
     * Gets index i from the narrativeUserRights list.
     *
     * @param index
     * @return Question at index i
     */
    public NarrativeUserRights getNarrativeUserRight(int index) {
        while (getNarrativeUserRights().size() <= index) {
            getNarrativeUserRights().add(new NarrativeUserRights());
        }
        return (NarrativeUserRights) getNarrativeUserRights().get(index);
    }

    public void clearAttachment() {
        getNarrativeAttachmentList().clear();
    }

    @Override
    public List buildListOfDeletionAwareLists() {
        List managedLists = super.buildListOfDeletionAwareLists();
        managedLists.add(getNarrativeUserRights());
        return managedLists;
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((comments == null) ? 0 : comments.hashCode());
        result = prime * result + ((contactName == null) ? 0 : contactName.hashCode());
        result = prime * result + ((emailAddress == null) ? 0 : emailAddress.hashCode());
        result = prime * result + ((fileName == null) ? 0 : fileName.hashCode());
        result = prime * result + ((moduleNumber == null) ? 0 : moduleNumber.hashCode());
        result = prime * result + ((moduleSequenceNumber == null) ? 0 : moduleSequenceNumber.hashCode());
        result = prime * result + ((moduleStatusCode == null) ? 0 : moduleStatusCode.hashCode());
        result = prime * result + ((moduleTitle == null) ? 0 : moduleTitle.hashCode());
        result = prime * result + ((narrativeStatus == null) ? 0 : narrativeStatus.hashCode());
        result = prime * result + ((narrativeType == null) ? 0 : narrativeType.hashCode());
        result = prime * result + ((narrativeTypeCode == null) ? 0 : narrativeTypeCode.hashCode());
        result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode());
        result = prime * result + ((proposalNumber == null) ? 0 : proposalNumber.hashCode());
        return result;
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        Narrative other = (Narrative) obj;
        if (comments == null) {
            if (other.comments != null) return false;
        } else if (!comments.equals(other.comments)) return false;
        if (contactName == null) {
            if (other.contactName != null) return false;
        } else if (!contactName.equals(other.contactName)) return false;
        if (emailAddress == null) {
            if (other.emailAddress != null) return false;
        } else if (!emailAddress.equals(other.emailAddress)) return false;
        if (fileName == null) {
            if (other.fileName != null) return false;
        } else if (!fileName.equals(other.fileName)) return false;
        if (moduleNumber == null) {
            if (other.moduleNumber != null) return false;
        } else if (!moduleNumber.equals(other.moduleNumber)) return false;
        if (moduleSequenceNumber == null) {
            if (other.moduleSequenceNumber != null) return false;
        } else if (!moduleSequenceNumber.equals(other.moduleSequenceNumber)) return false;
        if (moduleStatusCode == null) {
            if (other.moduleStatusCode != null) return false;
        } else if (!moduleStatusCode.equals(other.moduleStatusCode)) return false;
        if (moduleTitle == null) {
            if (other.moduleTitle != null) return false;
        } else if (!moduleTitle.equals(other.moduleTitle)) return false;
        if (narrativeStatus == null) {
            if (other.narrativeStatus != null) return false;
        } else if (!narrativeStatus.equals(other.narrativeStatus)) return false;
        if (narrativeType == null) {
            if (other.narrativeType != null) return false;
        } else if (!narrativeType.equals(other.narrativeType)) return false;
        if (narrativeTypeCode == null) {
            if (other.narrativeTypeCode != null) return false;
        } else if (!narrativeTypeCode.equals(other.narrativeTypeCode)) return false;
        if (phoneNumber == null) {
            if (other.phoneNumber != null) return false;
        } else if (!phoneNumber.equals(other.phoneNumber)) return false;
        if (proposalNumber == null) {
            if (other.proposalNumber != null) return false;
        } else if (!proposalNumber.equals(other.proposalNumber)) return false;
        return true;
    }

    public int hierarchyHashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((comments == null) ? 0 : comments.hashCode());
        result = prime * result + ((contactName == null) ? 0 : contactName.hashCode());
        result = prime * result + ((emailAddress == null) ? 0 : emailAddress.hashCode());
        result = prime * result + ((fileName == null) ? 0 : fileName.hashCode());
        result = prime * result + ((moduleNumber == null) ? 0 : moduleNumber.hashCode());
        result = prime * result + ((moduleSequenceNumber == null) ? 0 : moduleSequenceNumber.hashCode());
        result = prime * result + ((moduleStatusCode == null) ? 0 : moduleStatusCode.hashCode());
        result = prime * result + ((moduleTitle == null) ? 0 : moduleTitle.hashCode());
        result = prime * result + ((narrativeStatus == null) ? 0 : narrativeStatus.hashCode());
        result = prime * result + ((narrativeType == null) ? 0 : narrativeType.hashCode());
        result = prime * result + ((narrativeTypeCode == null) ? 0 : narrativeTypeCode.hashCode());
        result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode());
        return result;
    }

    public Timestamp getTimestampDisplay() {
        return timestampDisplay;
    }

    public void setTimestampDisplay(Timestamp timestampDisplay) {
        this.timestampDisplay = timestampDisplay;
    }

    public String getUploadUserDisplay() {
        return uploadUserDisplay;
    }

    public void setUploadUserDisplay(String uploadUserDisplay) {
        this.uploadUserDisplay = uploadUserDisplay;
    }

    public String getUploadUserFullName() {
        return uploadUserFullName;
    }

    public void setUploadUserFullName(String uploadUserFullName) {
        this.uploadUserFullName = uploadUserFullName;
    }

    /**
     * Gets the hierarchyProposalNumber attribute.
     * @return Returns the hierarchyProposalNumber.
     */
    public String getHierarchyProposalNumber() {
        return hierarchyProposalNumber;
    }

    /**
     * Sets the hierarchyProposalNumber attribute value.
     * @param hierarchyProposalNumber The hierarchyProposalNumber to set.
     */
    public void setHierarchyProposalNumber(String hierarchyProposalNumber) {
        this.hierarchyProposalNumber = hierarchyProposalNumber;
    }

    /**
     * Gets the hiddenInHierarchy attribute.
     * @return Returns the hiddenInHierarchy.
     */
    public boolean isHiddenInHierarchy() {
        return hiddenInHierarchy;
    }

    /**
     * Sets the hiddenInHierarchy attribute value.
     * @param hiddenInHierarchy The hiddenInHierarchy to set.
     */
    public void setHiddenInHierarchy(boolean hiddenInHierarchy) {
        this.hiddenInHierarchy = hiddenInHierarchy;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public byte[] getData() {
        if (getNarrativeAttachmentList().isEmpty()) {
            return null;
        } else {
            return getNarrativeAttachmentList().get(0).getContent();
        }
    }

    public String getIconPath() {
        return KraServiceLocator.getService(KcAttachmentService.class).getFileTypeIcon(this);
    }

    public String getName() {
        return getFileName();
    }

    public String getType() {
        return getContentType();
    }

}


text:
package org.olat.presentation.course.nodes.projectbroker;

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

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.olat.data.basesecurity.Identity;
import org.olat.data.commons.vfs.VFSLeaf;
import org.olat.data.commons.vfs.olatimpl.OlatRootFolderImpl;
import org.olat.data.course.nodes.projectbroker.CustomField;
import org.olat.data.course.nodes.projectbroker.Project;
import org.olat.data.course.nodes.projectbroker.ProjectEvent;
import org.olat.lms.commons.mediaresource.MediaResource;
import org.olat.lms.commons.mediaresource.NotFoundMediaResource;
import org.olat.lms.commons.mediaresource.VFSMediaResource;
import org.olat.lms.coordinate.LockingService;
import org.olat.lms.course.nodes.CourseNode;
import org.olat.lms.course.nodes.projectbroker.ProjectBrokerManagerFactory;
import org.olat.lms.course.nodes.projectbroker.ProjectBrokerModuleConfiguration;
import org.olat.lms.course.run.environment.CourseEnvironment;
import org.olat.lms.user.UserService;
import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.components.Component;
import org.olat.presentation.framework.core.components.download.DisplayOrDownloadComponent;
import org.olat.presentation.framework.core.components.link.Link;
import org.olat.presentation.framework.core.components.link.LinkFactory;
import org.olat.presentation.framework.core.components.velocity.VelocityContainer;
import org.olat.presentation.framework.core.control.Controller;
import org.olat.presentation.framework.core.control.WindowControl;
import org.olat.presentation.framework.core.control.controller.BasicController;
import org.olat.presentation.framework.core.control.creator.ControllerCreator;
import org.olat.presentation.framework.core.control.generic.modal.DialogBoxController;
import org.olat.presentation.framework.core.control.generic.modal.DialogBoxUIFactory;
import org.olat.presentation.framework.dispatcher.mapper.Mapper;
import org.olat.presentation.framework.layout.fullWebApp.popup.BaseFullWebappPopupLayoutFactory;
import org.olat.presentation.user.UserInfoMainController;
import org.olat.system.commons.StringHelper;
import org.olat.system.commons.resource.OLATResourceable;
import org.olat.system.commons.resource.OresHelper;
import org.olat.system.coordinate.LockResult;
import org.olat.system.event.Event;
import org.olat.system.logging.log4j.LoggerHelper;
import org.olat.system.spring.CoreSpringFactory;

/**
 * @author guretzki
 */
public class ProjectDetailsDisplayController extends BasicController {

    private static final Logger log = LoggerHelper.getLogger();
    private final String CMD_OPEN_PROJECT_LEADER_DETAIL = "cmd_open_projectleader_detail";
    private final VelocityContainer myContent;
    private Link editProjectButton;
    private Link deleteProjectButton;
    private DialogBoxController deleteConfirmController;
    private final List projectLeaderLinkNameList;
    private final Link attachedFileLink;

    private final Project project;
    private final CourseEnvironment courseEnv;
    private final CourseNode courseNode;
    private DialogBoxController deleteGroupConfirmController;
    private Link changeProjectStateToNotAssignButton;
    private Link changeProjectStateToAssignButton;
    private LockResult lock;
    private final TopicChangeConfirmationSender topicChangeConfirmationSender;

    /**
     * @param ureq
     * @param wControl
     * @param hpc
     */
    public ProjectDetailsDisplayController(final UserRequest ureq, final WindowControl wControl, final Project project, final CourseEnvironment courseEnv,
            final CourseNode courseNode, final ProjectBrokerModuleConfiguration projectBrokerModuleConfiguration) {
        super(ureq, wControl);
        this.project = project;
        this.courseEnv = courseEnv;
        this.courseNode = courseNode;
        this.topicChangeConfirmationSender = new TopicChangeConfirmationSenderImpl(ureq.getIdentity(), project, courseEnv, courseNode);
        // use property handler translator for translating of user fields
        setTranslator(getUserService().getUserPropertiesConfig().getTranslator(getTranslator()));
        myContent = createVelocityContainer("projectdetailsdisplay");
        if (projectBrokerModuleConfiguration.isAcceptSelectionManually()) {
            myContent.contextPut("keyMaxLabel", "detailsform.places.candidates.label");
        } else {
            myContent.contextPut("keyMaxLabel", "detailsform.places.label");
        }

        if (ProjectBrokerManagerFactory.getProjectGroupManager().isProjectManagerOrAdministrator(ureq, courseEnv, project)) {
            myContent.contextPut("isProjectManager", true);
            editProjectButton = LinkFactory.createButtonSmall("edit.project.button", myContent, this);
            deleteProjectButton = LinkFactory.createButtonSmall("delete.project.button", myContent, this);
            if (projectBrokerModuleConfiguration.isAcceptSelectionManually()) {
                // ProjectBroker run in accept-manually mode => add button to reset/set project-state
                if (project.getState().equals(Project.STATE_ASSIGNED)) {
                    changeProjectStateToNotAssignButton = LinkFactory.createButtonSmall("change.project.state.not_assign.button", myContent, this);
                } else {
                    changeProjectStateToAssignButton = LinkFactory.createButtonSmall("change.project.state.assign.button", myContent, this);
                }
            }
        } else {
            myContent.contextPut("isProjectManager", false);
        }

        myContent.contextPut("title", project.getTitle());
        // account-Managers
        int i = 0;
        projectLeaderLinkNameList = new ArrayList();
        for (final Iterator iterator = project.getProjectLeaders().iterator(); iterator.hasNext();) {
            final Identity identity = (Identity) iterator.next();
            final String linkName = "projectLeaderLink_" + i;
            final Link projectLeaderLink = LinkFactory.createCustomLink(linkName, CMD_OPEN_PROJECT_LEADER_DETAIL, getUserService()
                    .getFirstAndLastname(identity.getUser()), Link.NONTRANSLATED, myContent, this);
            projectLeaderLink.setUserObject(identity);
            projectLeaderLink.setTarget("_blank");
            projectLeaderLinkNameList.add(linkName);
            i++;
        }
        myContent.contextPut("projectLeaderLinkNameList", projectLeaderLinkNameList);

        myContent.contextPut("description", project.getDescription());
        // Custom-fields
        final List customFieldList = new ArrayList();
        int customFieldIndex = 0;
        for (final Iterator<CustomField> iterator = projectBrokerModuleConfiguration.getCustomFields().iterator(); iterator.hasNext();) {
            final CustomField customField = iterator.next();
            log.debug("customField=" + customField);
            final String name = customField.getName();
            final String value = project.getCustomFieldValue(customFieldIndex++);
            log.debug("customField  name=" + name + "  value=" + value);
            customFieldList.add(new CustomField(name, value));
        }
        myContent.contextPut("customFieldList", customFieldList);

        // events
        final List eventList = new ArrayList();
        for (final Project.EventType eventType : Project.EventType.values()) {
            if (projectBrokerModuleConfiguration.isProjectEventEnabled(eventType)) {
                final ProjectEvent projectEvent = project.getProjectEvent(eventType);
                eventList.add(projectEvent);
                log.debug("eventList add event=" + projectEvent);
            }
        }
        myContent.contextPut("eventList", eventList);

        final String stateValue = getTranslator().translate(
                ProjectBrokerManagerFactory.getProjectBrokerManager().getStateFor(project, ureq.getIdentity(), projectBrokerModuleConfiguration));
        myContent.contextPut("state", stateValue);
        if (project.getMaxMembers() == Project.MAX_MEMBERS_UNLIMITED) {
            myContent.contextPut("projectPlaces", this.getTranslator().translate("detailsform.unlimited.project.members"));
        } else {
            final String placesValue = ProjectBrokerManagerFactory.getProjectBrokerManager().getSelectedPlaces(project) + " "
                    + this.getTranslator().translate("detailsform.places.of") + " " + project.getMaxMembers();
            myContent.contextPut("projectPlaces", placesValue);
        }

        attachedFileLink = LinkFactory.createCustomLink("attachedFileLink", "cmd.donwload.attachment", project.getAttachmentFileName(), Link.NONTRANSLATED, myContent,
                this);
        putInitialPanel(myContent);
    }

    /**
	 */
    @Override
    protected void event(final UserRequest ureq, final Controller source, final Event event) {
        if (source == deleteConfirmController) {
            if (DialogBoxUIFactory.isOkEvent(event)) {
                // ok group should be deleted, ask to delete group too
                String text = translate("delete.group.confirm", StringHelper.escapeHtml(project.getTitle()));
                deleteGroupConfirmController = this.activateYesNoDialog(ureq, null, text, deleteConfirmController);
            }
        } else if (source == deleteGroupConfirmController) {
            boolean deleteGroup;
            if (DialogBoxUIFactory.isOkEvent(event)) {
                deleteGroup = true;
            } else {
                deleteGroup = false;
            }
            this.topicChangeConfirmationSender.sendTopicDeleteConfirmation();
            ProjectBrokerManagerFactory.getProjectBrokerManager().deleteProject(project, deleteGroup, courseEnv, courseNode);
            ProjectBrokerManagerFactory.getProjectGroupManager().sendGroupChangeEvent(project, courseEnv.getCourseResourceableId(), ureq.getIdentity());
            showInfo("project.deleted.msg", project.getTitle());
            fireEvent(ureq, Event.BACK_EVENT);
            getLockingService().releaseLock(lock);
        }

    }

    private LockingService getLockingService() {
        return CoreSpringFactory.getBean(LockingService.class);
    }

    /**
	 */
    @Override
    protected void event(final UserRequest ureq, final Component source, final Event event) {
        if (ProjectBrokerManagerFactory.getProjectBrokerManager().existsProject(project.getKey())) {
            if (source == editProjectButton) {
                fireEvent(ureq, new Event("switchToEditMode"));
            } else if (source == deleteProjectButton) {
                final OLATResourceable projectOres = OresHelper.createOLATResourceableInstance(Project.class, project.getKey());
                this.lock = getLockingService().acquireLock(projectOres, ureq.getIdentity(), null);
                if (lock.isSuccess()) {
                    String text = translate("delete.confirm", StringHelper.escapeHtml(project.getTitle()));
                    deleteConfirmController = activateOkCancelDialog(ureq, null, text, deleteConfirmController);
                } else {
                    this.showInfo("info.project.already.edit", project.getTitle());
                }
                return;
            } else if (event.getCommand().equals(CMD_OPEN_PROJECT_LEADER_DETAIL)) {
                if (source instanceof Link) {
                    final Link projectLeaderLink = (Link) source;
                    final Identity identity = (Identity) projectLeaderLink.getUserObject();
                    final ControllerCreator ctrlCreator = new ControllerCreator() {
                        @Override
                        public Controller createController(final UserRequest lureq, final WindowControl lwControl) {
                            return new UserInfoMainController(lureq, lwControl, identity);
                        }
                    };
                    // wrap the content controller into a full header layout
                    final ControllerCreator layoutCtrlr = BaseFullWebappPopupLayoutFactory.createAuthMinimalPopupLayout(ureq, ctrlCreator);
                    // open in new browser window
                    this.openInNewBrowserWindow(ureq, layoutCtrlr);
                }
            } else if (source == attachedFileLink) {
                doFileDelivery(project, courseEnv, courseNode);
            } else if (source == changeProjectStateToNotAssignButton) {
                ProjectBrokerManagerFactory.getProjectBrokerManager().setProjectState(project, Project.STATE_NOT_ASSIGNED);
                myContent.remove(changeProjectStateToNotAssignButton);
                changeProjectStateToAssignButton = LinkFactory.createButtonSmall("change.project.state.assign.button", myContent, this);
            } else if (source == changeProjectStateToAssignButton) {
                ProjectBrokerManagerFactory.getProjectBrokerManager().setProjectState(project, Project.STATE_ASSIGNED);
                myContent.remove(changeProjectStateToAssignButton);
                changeProjectStateToNotAssignButton = LinkFactory.createButtonSmall("change.project.state.not_assign.button", myContent, this);
            }
        } else {
            this.showInfo("info.project.nolonger.exist", project.getTitle());
        }
    }

    /**
	 */
    @Override
    protected void doDispose() {
        // child controller sposed by basic controller
        if (lock != null) {
            getLockingService().releaseLock(lock);
        }
    }

    private void doFileDelivery(final Project project, final CourseEnvironment courseEnv, final CourseNode cNode) {
        // Create a mapper to deliver the auto-download of the file. We have to
        // create a dedicated mapper here
        // and can not reuse the standard briefcase way of file delivering, some
        // very old fancy code
        // Mapper is cleaned up automatically by basic controller
        final String baseUrl = registerMapper(new Mapper() {
            @Override
            public MediaResource handle(final String relPath, final HttpServletRequest request) {
                final OlatRootFolderImpl rootFolder = new OlatRootFolderImpl(ProjectBrokerManagerFactory.getProjectBrokerManager().getAttamchmentRelativeRootPath(
                        project, courseEnv, cNode), null);
                final VFSLeaf vfsfile = (VFSLeaf) rootFolder.resolve(relPath);
                if (vfsfile == null) {
                    return new NotFoundMediaResource(relPath);
                } else {
                    return new VFSMediaResource(vfsfile);
                }
            }
        });
        // Trigger auto-download
        log.debug("baseUrl=" + baseUrl);
        final DisplayOrDownloadComponent dordc = new DisplayOrDownloadComponent("downloadcomp", baseUrl + "/" + project.getAttachmentFileName());
        myContent.put("autoDownloadComp", dordc);
    }

    private UserService getUserService() {
        return CoreSpringFactory.getBean(UserService.class);
    }

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Linq;
using System.Net;

namespace Stratis.Bitcoin.Features.RPC
{
    public class RPCCredentialString
    {
        public static RPCCredentialString Parse(string str)
        {
            RPCCredentialString r;
            if(!TryParse(str, out r))
                throw new FormatException("Invalid RPC Credential string");
            return r;
        }

        public static bool TryParse(string str, out RPCCredentialString connectionString)
        {
            if(str == null)
                throw new ArgumentNullException(nameof(str));
            str = str.Trim();
            if(str.Equals("default", StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(str))
            {
                connectionString = new RPCCredentialString();
                return true;
            }

            if(str.StartsWith("cookiefile=", StringComparison.OrdinalIgnoreCase))
            {
                string path = str.Substring("cookiefile=".Length);
                connectionString = new RPCCredentialString();
                connectionString.CookieFile = path;
                return true;
            }

            if(str.IndexOf(':') != -1)
            {
                string[] parts = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                if(parts.Length >= 2)
                {
                    parts[1] = string.Join(":", parts.Skip(1).ToArray());
                    connectionString = new RPCCredentialString();
                    connectionString.UserPassword = new NetworkCredential(parts[0], parts[1]);
                    return true;
                }
            }

            connectionString = null;
            return false;
        }

        /// <summary>
        /// Use default connection settings of the chain
        /// </summary>
        public bool UseDefault
        {
            get
            {
                return this.CookieFile == null && this.UserPassword == null;
            }
        }

        /// <summary>
        /// Path to cookie file
        /// </summary>
        public string CookieFile
        {
            get
            {
                return this._CookieFile;
            }
            set
            {
                if(value != null)
                    Reset();
                this._CookieFile = value;
            }
        }

        private void Reset()
        {
            this._CookieFile = null;
            this._UsernamePassword = null;
        }

        private string _CookieFile;

        /// <summary>
        /// Username and password
        /// </summary>
        public NetworkCredential UserPassword
        {
            get
            {
                return this._UsernamePassword;
            }
            set
            {
                if(value != null)
                    Reset();
                this._UsernamePassword = value;
            }
        }

        private NetworkCredential _UsernamePassword;

        public override string ToString()
        {
            return this.UseDefault ? "default" :
                this.CookieFile != null ? ("cookiefile=" + this.CookieFile) :
                this.UserPassword != null ? $"{this.UserPassword.UserName}:{this.UserPassword.Password}" :
                   "default";
        }
    }
}


text:
package com.amazonaws.services.simpleworkflow.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Provides the details of the LambdaFunctionStarted event. It isn't set for other event types.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LambdaFunctionStartedEventAttributes implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The ID of the LambdaFunctionScheduled event that was recorded when this activity task was scheduled.
     * To help diagnose issues, use this information to trace back the chain of events leading up to this event.
     *

     */
    private Long scheduledEventId;

    /**
     *

     * The ID of the LambdaFunctionScheduled event that was recorded when this activity task was scheduled.
     * To help diagnose issues, use this information to trace back the chain of events leading up to this event.
     *

     *
     * @param scheduledEventId
     *        The ID of the LambdaFunctionScheduled event that was recorded when this activity task was
     *        scheduled. To help diagnose issues, use this information to trace back the chain of events leading up to
     *        this event.
     */

    public void setScheduledEventId(Long scheduledEventId) {
        this.scheduledEventId = scheduledEventId;
    }

    /**
     *

     * The ID of the LambdaFunctionScheduled event that was recorded when this activity task was scheduled.
     * To help diagnose issues, use this information to trace back the chain of events leading up to this event.
     *

     *
     * @return The ID of the LambdaFunctionScheduled event that was recorded when this activity task was
     *         scheduled. To help diagnose issues, use this information to trace back the chain of events leading up to
     *         this event.
     */

    public Long getScheduledEventId() {
        return this.scheduledEventId;
    }

    /**
     *

     * The ID of the LambdaFunctionScheduled event that was recorded when this activity task was scheduled.
     * To help diagnose issues, use this information to trace back the chain of events leading up to this event.
     *

     *
     * @param scheduledEventId
     *        The ID of the LambdaFunctionScheduled event that was recorded when this activity task was
     *        scheduled. To help diagnose issues, use this information to trace back the chain of events leading up to
     *        this event.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public LambdaFunctionStartedEventAttributes withScheduledEventId(Long scheduledEventId) {
        setScheduledEventId(scheduledEventId);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getScheduledEventId() != null)
            sb.append("ScheduledEventId: ").append(getScheduledEventId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof LambdaFunctionStartedEventAttributes == false)
            return false;
        LambdaFunctionStartedEventAttributes other = (LambdaFunctionStartedEventAttributes) obj;
        if (other.getScheduledEventId() == null ^ this.getScheduledEventId() == null)
            return false;
        if (other.getScheduledEventId() != null && other.getScheduledEventId().equals(this.getScheduledEventId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getScheduledEventId() == null) ? 0 : getScheduledEventId().hashCode());
        return hashCode;
    }

    @Override
    public LambdaFunctionStartedEventAttributes clone() {
        try {
            return (LambdaFunctionStartedEventAttributes) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.simpleworkflow.model.transform.LambdaFunctionStartedEventAttributesMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
title: String.prototype.valueOf
localeTitle: String.prototype.valueOf
---
## String.prototype.valueOf

这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/string/string-prototype-valueof/index.md) 。

[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。

#### 更多信息:


text:
package reconciler

import (
	context "context"
	"fmt"
	"strings"

	camelv1 "github.com/apache/camel-k/pkg/apis/camel/v1"
	camelclientset "github.com/apache/camel-k/pkg/client/camel/clientset/versioned"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/equality"
	k8serrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	v1alpha1 "knative.dev/eventing-camel/pkg/apis/sources/v1alpha1"
	"knative.dev/eventing-camel/pkg/reconciler/resources"
	"knative.dev/pkg/logging"
	"knative.dev/pkg/reconciler"
	"knative.dev/pkg/resolver"

	camelsource "knative.dev/eventing-camel/pkg/client/injection/reconciler/sources/v1alpha1/camelsource"
)

// newReconciledNormal makes a new reconciler event with event type Normal, and
// reason CamelSourceReconciled.
func newReconciledNormal(namespace, name string) reconciler.Event {
	return reconciler.NewEvent(corev1.EventTypeNormal, "CamelSourceReconciled", "CamelSource reconciled: \"%s/%s\"", namespace, name)
}

// Reconciler implements controller.Reconciler for CamelSource resources.
type Reconciler struct {
	sinkResolver   *resolver.URIResolver
	camelClientSet camelclientset.Interface
}

// Check that our Reconciler implements Interface
var _ camelsource.Interface = (*Reconciler)(nil)

// ReconcileKind implements Interface.ReconcileKind.
func (r *Reconciler) ReconcileKind(ctx context.Context, source *v1alpha1.CamelSource) reconciler.Event {
	source.Status.InitializeConditions()
	source.Status.ObservedGeneration = source.Generation

	if source.Spec.Sink == nil {
		source.Status.MarkNoSink("SinkMissing", "")
		return fmt.Errorf("spec.sink missing")
	}

	dest := source.Spec.Sink.DeepCopy()
	// fill optional data in destination
	if dest.Ref != nil {
		if dest.Ref.Namespace == "" {
			dest.Ref.Namespace = source.GetNamespace()
		}
	} else if dest.DeprecatedName != "" && dest.DeprecatedNamespace == "" {
		dest.DeprecatedNamespace = source.GetNamespace()
	}

	sinkURI, err := r.sinkResolver.URIFromDestination(ctx, *dest, source)
	if err != nil {
		source.Status.MarkNoSink("NotFound", "")
		return err
	}

	if dest.DeprecatedAPIVersion != "" &&
		dest.DeprecatedKind != "" &&
		dest.DeprecatedName != "" {
		source.Status.MarkSinkWarnRefDeprecated(sinkURI)
	} else {
		source.Status.MarkSink(sinkURI)
	}

	// Reconcile and update integration status
	if integration, err := r.reconcileIntegration(ctx, source, sinkURI); err != nil {
		return err
	} else if integration != nil && integration.Status.Phase == camelv1.IntegrationPhaseRunning {
		source.Status.MarkDeployed()
	}

	return newReconciledNormal(source.Namespace, source.Name)
}

func (r *Reconciler) reconcileIntegration(ctx context.Context, source *v1alpha1.CamelSource, sinkURI string) (*camelv1.Integration, reconciler.Event) {
	logger := logging.FromContext(ctx)
	args := &resources.CamelArguments{
		Name:      source.Name,
		Namespace: source.Namespace,
		Source:    source.Spec.Source,
		Owner:     source,
		SinkURL:   sinkURI,
	}
	if source.Spec.CloudEventOverrides != nil {
		args.Overrides = make(map[string]string)
		for k, v := range source.Spec.CloudEventOverrides.Extensions {
			args.Overrides[strings.ToLower(k)] = v
		}
	}

	integration, err := r.getIntegration(ctx, source)
	if err != nil {
		if k8serrors.IsNotFound(err) {
			integration, err = r.createIntegration(ctx, source, args)
			if err != nil {
				return nil, reconciler.NewEvent(corev1.EventTypeWarning, "IntegrationBlocked", "waiting for %v", err)
			}

			// Since the Deployment has just been created, there's nothing more
			// to do until it gets a status. This CamelSource will be reconciled
			// again when the Integration is updated.
			name := integration.Name
			if name == "" {
				name = fmt.Sprintf("%s*", integration.GenerateName)
			}
			source.Status.MarkDeploying("Deploying", "Created integration %s", name)
			return integration, reconciler.NewEvent(corev1.EventTypeNormal, "Deployed", "Created integration %q", name)
		}
		return nil, err
	}

	// Update Integration spec if it's changed
	expected, err := resources.MakeIntegration(args)
	if err != nil {
		return nil, err
	}
	// Since the Integration spec has fields defaulted by the webhook, it won't
	// be equal to expected. Use DeepDerivative to compare only the fields that
	// are set in expected.
	if !equality.Semantic.DeepDerivative(expected.Spec, integration.Spec) {
		logger.Infof("Integration %q in namespace %q has changed and needs to be updated", integration.Name, integration.Namespace)
		integration.Spec = expected.Spec

		_, err := r.updateIntegration(ctx, integration)
		// if no error, update the status.
		name := integration.Name
		if name == "" {
			name = fmt.Sprintf("%s*", integration.GenerateName)
		}
		if err == nil {
			source.Status.MarkDeploying("IntegrationUpdated", "Updated integration %s", name)
			return nil, reconciler.NewEvent(corev1.EventTypeNormal, "IntegrationUpdated", "Updated integration %q", name)
		} else {
			source.Status.MarkDeploying("IntegrationNeedsUpdate", "Attempting to update integration %s", name)
			return nil, reconciler.NewEvent(corev1.EventTypeWarning, "IntegrationNeedsUpdate", "Failed to update integration %q", name)
		}
	}
	return integration, nil
}

func (r *Reconciler) getIntegration(ctx context.Context, source *v1alpha1.CamelSource) (*camelv1.Integration, error) {
	all, err := r.camelClientSet.CamelV1().Integrations(source.Namespace).List(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, err
	}
	for _, a := range all.Items {
		if metav1.IsControlledBy(&a, source) {
			return &a, nil
		}
	}
	return nil, k8serrors.NewNotFound(schema.GroupResource{}, "")
}

func (r *Reconciler) createIntegration(ctx context.Context, source *v1alpha1.CamelSource, args *resources.CamelArguments) (*camelv1.Integration, error) {
	integration, err := resources.MakeIntegration(args)
	if err != nil {
		return nil, err
	}

	return r.camelClientSet.CamelV1().Integrations(source.Namespace).Create(ctx, integration, metav1.CreateOptions{})
}

func (r *Reconciler) updateIntegration(ctx context.Context, integration *camelv1.Integration) (*camelv1.Integration, error) {
	return r.camelClientSet.CamelV1().Integrations(integration.Namespace).Update(ctx, integration, metav1.UpdateOptions{})
}


text: collection utils


text:
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Detects images dragged and dropped on to the window.
 *
 * @author robbyw@google.com (Robby Walker)
 */

goog.provide('goog.ui.DragDropDetector');
goog.provide('goog.ui.DragDropDetector.EventType');
goog.provide('goog.ui.DragDropDetector.ImageDropEvent');
goog.provide('goog.ui.DragDropDetector.LinkDropEvent');

goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.events.Event');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.math.Coordinate');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.userAgent');

/**
 * Creates a new drag and drop detector.
 * @param {string=} opt_filePath The URL of the page to use for the detector.
 *     It should contain the same contents as dragdropdetector_target.html in
 *     the demos directory.
 * @constructor
 * @extends {goog.events.EventTarget}
 * @final
 */
goog.ui.DragDropDetector = function(opt_filePath) {
  goog.base(this);

  var iframe = goog.dom.createDom(goog.dom.TagName.IFRAME, {
    'frameborder': 0
  });
  // In Firefox, we do all drop detection with an IFRAME.  In IE, we only use
  // the IFRAME to capture copied, non-linked images.  (When we don't need it,
  // we put a text INPUT before it and push it off screen.)
  iframe.className = goog.userAgent.IE ?
      goog.getCssName(
          goog.ui.DragDropDetector.BASE_CSS_NAME_, 'ie-editable-iframe') :
      goog.getCssName(
          goog.ui.DragDropDetector.BASE_CSS_NAME_, 'w3c-editable-iframe');
  iframe.src = opt_filePath || goog.ui.DragDropDetector.DEFAULT_FILE_PATH_;

  this.element_ = /** @type {!HTMLIFrameElement} */ (iframe);

  this.handler_ = new goog.events.EventHandler(this);
  this.handler_.listen(iframe, goog.events.EventType.LOAD, this.initIframe_);

  if (goog.userAgent.IE) {
    // In IE, we have to bounce between an INPUT for catching links and an
    // IFRAME for catching images.
    this.textInput_ = goog.dom.createDom(goog.dom.TagName.INPUT, {
      'type': 'text',
      'className': goog.getCssName(
          goog.ui.DragDropDetector.BASE_CSS_NAME_, 'ie-input')
    });

    this.root_ = goog.dom.createDom(goog.dom.TagName.DIV,
        goog.getCssName(goog.ui.DragDropDetector.BASE_CSS_NAME_, 'ie-div'),
        this.textInput_, iframe);
  } else {
    this.root_ = iframe;
  }

  document.body.appendChild(this.root_);
};
goog.inherits(goog.ui.DragDropDetector, goog.events.EventTarget);

/**
 * Drag and drop event types.
 * @enum {string}
 */
goog.ui.DragDropDetector.EventType = {
  IMAGE_DROPPED: 'onimagedrop',
  LINK_DROPPED: 'onlinkdrop'
};

/**
 * Browser specific drop event type.
 * @type {string}
 * @private
 */
goog.ui.DragDropDetector.DROP_EVENT_TYPE_ = goog.userAgent.IE ?
    goog.events.EventType.DROP : 'dragdrop';

/**
 * Initial value for clientX and clientY indicating that the location has
 * never been updated.
 */
goog.ui.DragDropDetector.INIT_POSITION = -10000;

/**
 * Prefix for all CSS names.
 * @type {string}
 * @private
 */
goog.ui.DragDropDetector.BASE_CSS_NAME_ = goog.getCssName('goog-dragdrop');

/**
 * @desc Message shown to users to inform them that they can't drag and drop
 *     local files.
 */
goog.ui.DragDropDetector.MSG_DRAG_DROP_LOCAL_FILE_ERROR = goog.getMsg(
    'It is not possible to drag ' +
    'and drop image files at this time.\nPlease drag an image from your web ' +
    'browser.');

/**
 * @desc Message shown to users trying to drag and drop protected images from
 *     Flickr, etc.
 */
goog.ui.DragDropDetector.MSG_DRAG_DROP_PROTECTED_FILE_ERROR = goog.getMsg(
    'The image you are ' +
    'trying to drag has been blocked by the hosting site.');

/**
 * A map of special case information for URLs that cannot be dropped.  Each
 * entry is of the form:
 *     regex: url regex
 *     message: user visible message about this special case
 * @type {Array<{regex: RegExp, message: string}>}
 * @private
 */
goog.ui.DragDropDetector.SPECIAL_CASE_URLS_ = [
  {
    regex: /^file:\/\/\//,
    message: goog.ui.DragDropDetector.MSG_DRAG_DROP_LOCAL_FILE_ERROR
  },
  {
    regex: /flickr(.*)spaceball.gif$/,
    message: goog.ui.DragDropDetector.MSG_DRAG_DROP_PROTECTED_FILE_ERROR
  }
];

/**
 * Regex that matches anything that looks kind of like a URL.  It matches
 * nonspacechars://nonspacechars
 * @type {RegExp}
 * @private
 */
goog.ui.DragDropDetector.URL_LIKE_REGEX_ = /^\S+:\/\/\S*$/;

/**
 * Path to the dragdrop.html file.
 * @type {string}
 * @private
 */
goog.ui.DragDropDetector.DEFAULT_FILE_PATH_ = 'dragdropdetector_target.html';

/**
 * Our event handler object.
 * @type {goog.events.EventHandler}
 * @private
 */
goog.ui.DragDropDetector.prototype.handler_;

/**
 * The root element (the IFRAME on most browsers, the DIV on IE).
 * @type {Element}
 * @private
 */
goog.ui.DragDropDetector.prototype.root_;

/**
 * The text INPUT element used to detect link drops on IE.  null on Firefox.
 * @type {Element}
 * @private
 */
goog.ui.DragDropDetector.prototype.textInput_;

/**
 * The iframe element.
 * @type {HTMLIFrameElement}
 * @private
 */
goog.ui.DragDropDetector.prototype.element_;

/**
 * The iframe's window, null if the iframe hasn't loaded yet.
 * @type {Window}
 * @private
 */
goog.ui.DragDropDetector.prototype.window_ = null;

/**
 * The iframe's document, null if the iframe hasn't loaded yet.
 * @type {Document}
 * @private
 */
goog.ui.DragDropDetector.prototype.document_ = null;

/**
 * The iframe's body, null if the iframe hasn't loaded yet.
 * @type {HTMLBodyElement}
 * @private
 */
goog.ui.DragDropDetector.prototype.body_ = null;

/**
 * Whether we are in "screen cover" mode in which the iframe or div is
 * covering the entire screen.
 * @type {boolean}
 * @private
 */
goog.ui.DragDropDetector.prototype.isCoveringScreen_ = false;

/**
 * The last position of the mouse while dragging.
 * @type {goog.math.Coordinate}
 * @private
 */
goog.ui.DragDropDetector.prototype.mousePosition_ = null;

/**
 * Initialize the iframe after it has loaded.
 * @private
 */
goog.ui.DragDropDetector.prototype.initIframe_ = function() {
  // Set up a holder for position data.
  this.mousePosition_ = new goog.math.Coordinate(
      goog.ui.DragDropDetector.INIT_POSITION,
      goog.ui.DragDropDetector.INIT_POSITION);

  // Set up pointers to the important parts of the IFrame.
  this.window_ = this.element_.contentWindow;
  this.document_ = this.window_.document;
  this.body_ = this.document_.body;

  if (goog.userAgent.GECKO) {
    this.document_.designMode = 'on';
  } else if (!goog.userAgent.IE) {
    // Bug 1667110
    // In IE, we only set the IFrame body as content-editable when we bring it
    // into view at the top of the page.  Otherwise it may take focus when the
    // page is loaded, scrolling the user far offscreen.
    // Note that this isn't easily unit-testable, since it depends on a
    // browser-specific behavior with content-editable areas.
    this.body_.contentEditable = true;
  }

  this.handler_.listen(document.body, goog.events.EventType.DRAGENTER,
      this.coverScreen_);

  if (goog.userAgent.IE) {
    // IE only events.
    // Set up events on the IFrame.
    this.handler_.
        listen(this.body_,
            [goog.events.EventType.DRAGENTER, goog.events.EventType.DRAGOVER],
            goog.ui.DragDropDetector.enforceCopyEffect_).
        listen(this.body_, goog.events.EventType.MOUSEOUT,
            this.switchToInput_).
        listen(this.body_, goog.events.EventType.DRAGLEAVE,
            this.uncoverScreen_).
        listen(this.body_, goog.ui.DragDropDetector.DROP_EVENT_TYPE_,
            function(e) {
              this.trackMouse_(e);

              // The drop event occurs before the content is added to the
              // iframe.  We setTimeout so that handleNodeInserted_ is called
              //  after the content is in the document.
              goog.global.setTimeout(
                  goog.bind(this.handleNodeInserted_, this, e), 0);
              return true;
            }).

        // Set up events on the DIV.
        listen(this.root_,
            [goog.events.EventType.DRAGENTER, goog.events.EventType.DRAGOVER],
            this.handleNewDrag_).
        listen(this.root_,
            [
              goog.events.EventType.MOUSEMOVE,
              goog.events.EventType.KEYPRESS
            ], this.uncoverScreen_).

        // Set up events on the text INPUT.
        listen(this.textInput_, goog.events.EventType.DRAGOVER,
            goog.events.Event.preventDefault).
        listen(this.textInput_, goog.ui.DragDropDetector.DROP_EVENT_TYPE_,
            this.handleInputDrop_);
  } else {
    // W3C events.
    this.handler_.
        listen(this.body_, goog.ui.DragDropDetector.DROP_EVENT_TYPE_,
            function(e) {
              this.trackMouse_(e);
              this.uncoverScreen_();
            }).
        listen(this.body_,
            [goog.events.EventType.MOUSEMOVE, goog.events.EventType.KEYPRESS],
            this.uncoverScreen_).

        // Detect content insertion.
        listen(this.document_, 'DOMNodeInserted',
            this.handleNodeInserted_);
  }
};

/**
 * Enforce that anything dragged over the IFRAME is copied in to it, rather
 * than making it navigate to a different URL.
 * @param {goog.events.BrowserEvent} e The event to enforce copying on.
 * @private
 */
goog.ui.DragDropDetector.enforceCopyEffect_ = function(e) {
  var event = e.getBrowserEvent();
  // This function is only called on IE.
  if (event.dataTransfer.dropEffect.toLowerCase() != 'copy') {
    event.dataTransfer.dropEffect = 'copy';
  }
};

/**
 * Cover the screen with the iframe.
 * @param {goog.events.BrowserEvent} e The event that caused this function call.
 * @private
 */
goog.ui.DragDropDetector.prototype.coverScreen_ = function(e) {
  // Don't do anything if the drop effect is 'none' and we are in IE.
  // It is set to 'none' in cases like dragging text inside a text area.
  if (goog.userAgent.IE &&
      e.getBrowserEvent().dataTransfer.dropEffect == 'none') {
    return;
  }

  if (!this.isCoveringScreen_) {
    this.isCoveringScreen_ = true;
    if (goog.userAgent.IE) {
      goog.style.setStyle(this.root_, 'top', '0');
      this.body_.contentEditable = true;
      this.switchToInput_(e);
    } else {
      goog.style.setStyle(this.root_, 'height', '5000px');
    }
  }
};

/**
 * Uncover the screen.
 * @private
 */
goog.ui.DragDropDetector.prototype.uncoverScreen_ = function() {
  if (this.isCoveringScreen_) {
    this.isCoveringScreen_ = false;
    if (goog.userAgent.IE) {
      this.body_.contentEditable = false;
      goog.style.setStyle(this.root_, 'top', '-5000px');
    } else {
      goog.style.setStyle(this.root_, 'height', '10px');
    }
  }
};

/**
 * Re-insert the INPUT into the DIV.  Does nothing when the DIV is off screen.
 * @param {goog.events.BrowserEvent} e The event that caused this function call.
 * @private
 */
goog.ui.DragDropDetector.prototype.switchToInput_ = function(e) {
  // This is only called on IE.
  if (this.isCoveringScreen_) {
    goog.style.setElementShown(this.textInput_, true);
  }
};

/**
 * Remove the text INPUT so the IFRAME is showing.  Does nothing when the DIV is
 * off screen.
 * @param {goog.events.BrowserEvent} e The event that caused this function call.
 * @private
 */
goog.ui.DragDropDetector.prototype.switchToIframe_ = function(e) {
  // This is only called on IE.
  if (this.isCoveringScreen_) {
    goog.style.setElementShown(this.textInput_, false);
  }
};

/**
 * Handle a new drag event.
 * @param {goog.events.BrowserEvent} e The event object.
 * @return {boolean|undefined} Returns false in IE to cancel the event.
 * @private
 */
goog.ui.DragDropDetector.prototype.handleNewDrag_ = function(e) {
  var event = e.getBrowserEvent();

  // This is only called on IE.
  if (event.dataTransfer.dropEffect == 'link') {
    this.switchToInput_(e);
    e.preventDefault();
    return false;
  }

  // Things that aren't links can be placed in the contentEditable iframe.
  this.switchToIframe_(e);

  // No need to return true since for events return true is the same as no
  // return.
};

/**
 * Handle mouse tracking.
 * @param {goog.events.BrowserEvent} e The event object.
 * @private
 */
goog.ui.DragDropDetector.prototype.trackMouse_ = function(e) {
  this.mousePosition_.x = e.clientX;
  this.mousePosition_.y = e.clientY;

  // Check if the event is coming from within the iframe.
  if (goog.dom.getOwnerDocument(/** @type {Node} */ (e.target)) != document) {
    var iframePosition = goog.style.getClientPosition(this.element_);
    this.mousePosition_.x += iframePosition.x;
    this.mousePosition_.y += iframePosition.y;
  }
};

/**
 * Handle a drop on the IE text INPUT.
 * @param {goog.events.BrowserEvent} e The event object.
 * @private
 */
goog.ui.DragDropDetector.prototype.handleInputDrop_ = function(e) {
  this.dispatchEvent(
      new goog.ui.DragDropDetector.LinkDropEvent(
          e.getBrowserEvent().dataTransfer.getData('Text')));
  this.uncoverScreen_();
  e.preventDefault();
};

/**
 * Clear the contents of the iframe.
 * @private
 */
goog.ui.DragDropDetector.prototype.clearContents_ = function() {
  if (goog.userAgent.WEBKIT) {
    // Since this is called on a mutation event for the nodes we are going to
    // clear, calling this right away crashes some versions of WebKit.  Wait
    // until the events are finished.
    goog.global.setTimeout(goog.bind(function() {
      goog.dom.setTextContent(this, '');
    }, this.body_), 0);
  } else {
    this.document_.execCommand('selectAll', false, null);
    this.document_.execCommand('delete', false, null);
    this.document_.execCommand('selectAll', false, null);
  }
};

/**
 * Event handler called when the content of the iframe changes.
 * @param {goog.events.BrowserEvent} e The event that caused this function call.
 * @private
 */
goog.ui.DragDropDetector.prototype.handleNodeInserted_ = function(e) {
  var uri;

  if (this.body_.innerHTML.indexOf('<') == -1) {
    // If the document contains no tags (i.e. is just text), try it out.
    uri = goog.string.trim(goog.dom.getTextContent(this.body_));

    // See if it looks kind of like a url.
    if (!uri.match(goog.ui.DragDropDetector.URL_LIKE_REGEX_)) {
      uri = null;
    }
  }

  if (!uri) {
    var imgs = this.body_.getElementsByTagName(goog.dom.TagName.IMG);
    if (imgs && imgs.length) {
      // TODO(robbyw): Grab all the images, instead of just the first.
      var img = imgs[0];
      uri = img.src;
    }
  }

  if (uri) {
    var specialCases = goog.ui.DragDropDetector.SPECIAL_CASE_URLS_;
    var len = specialCases.length;
    for (var i = 0; i < len; i++) {
      var specialCase = specialCases[i];
      if (uri.match(specialCase.regex)) {
        alert(specialCase.message);
        break;
      }
    }

    // If no special cases matched, add the image.
    if (i == len) {
      this.dispatchEvent(
          new goog.ui.DragDropDetector.ImageDropEvent(
              uri, this.mousePosition_));
      return;
    }
  }

  var links = this.body_.getElementsByTagName(goog.dom.TagName.A);
  if (links) {
    for (i = 0, len = links.length; i < len; i++) {
      this.dispatchEvent(
          new goog.ui.DragDropDetector.LinkDropEvent(links[i].href));
    }
  }

  this.clearContents_();
  this.uncoverScreen_();
};

/** @override */
goog.ui.DragDropDetector.prototype.disposeInternal = function() {
  goog.base(this, 'disposeInternal');
  this.handler_.dispose();
  this.handler_ = null;
};

/**
 * Creates a new image drop event object.
 * @param {string} url The url of the dropped image.
 * @param {goog.math.Coordinate} position The screen position where the drop
 *     occurred.
 * @constructor
 * @extends {goog.events.Event}
 * @final
 */
goog.ui.DragDropDetector.ImageDropEvent = function(url, position) {
  goog.ui.DragDropDetector.ImageDropEvent.base(this, 'constructor',
      goog.ui.DragDropDetector.EventType.IMAGE_DROPPED);

  /**
   * The url of the image that was dropped.
   * @type {string}
   * @private
   */
  this.url_ = url;

  /**
   * The screen position where the drop occurred.
   * @type {goog.math.Coordinate}
   * @private
   */
  this.position_ = position;
};
goog.inherits(goog.ui.DragDropDetector.ImageDropEvent,
    goog.events.Event);

/**
 * @return {string} The url of the image that was dropped.
 */
goog.ui.DragDropDetector.ImageDropEvent.prototype.getUrl = function() {
  return this.url_;
};

/**
 * @return {goog.math.Coordinate} The screen position where the drop occurred.
 *     This may be have x and y of goog.ui.DragDropDetector.INIT_POSITION,
 *     indicating the drop position is unknown.
 */
goog.ui.DragDropDetector.ImageDropEvent.prototype.getPosition = function() {
  return this.position_;
};

/**
 * Creates a new link drop event object.
 * @param {string} url The url of the dropped link.
 * @constructor
 * @extends {goog.events.Event}
 * @final
 */
goog.ui.DragDropDetector.LinkDropEvent = function(url) {
  goog.ui.DragDropDetector.LinkDropEvent.base(this, 'constructor',
      goog.ui.DragDropDetector.EventType.LINK_DROPPED);

  /**
   * The url of the link that was dropped.
   * @type {string}
   * @private
   */
  this.url_ = url;
};
goog.inherits(goog.ui.DragDropDetector.LinkDropEvent,
    goog.events.Event);

/**
 * @return {string} The url of the link that was dropped.
 */
goog.ui.DragDropDetector.LinkDropEvent.prototype.getUrl = function() {
  return this.url_;
};


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../../base/Page');
import Response = require('../../../../http/response');
import V2010 = require('../../V2010');
import { SerializableClass } from '../../../../interfaces';

/**
 * Initialize the BalanceList
 *
 * @param version - Version of the resource
 * @param accountSid - Account Sid.
 */
declare function BalanceList(version: V2010, accountSid: string): BalanceListInstance;

interface BalanceListInstance {
  /**
   * fetch a BalanceInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: BalanceListInstance) => any): Promise<BalanceInstance>;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

interface BalancePayload extends BalanceResource, Page.TwilioResponsePayload {
}

interface BalanceResource {
  account_sid: string;
  balance: string;
  currency: string;
}

interface BalanceSolution {
  accountSid?: string;
}

declare class BalanceInstance extends SerializableClass {
  /**
   * Initialize the BalanceContext
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   * @param accountSid - Account Sid.
   */
  constructor(version: V2010, payload: BalancePayload, accountSid: string);

  accountSid: string;
  balance: string;
  currency: string;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

declare class BalancePage extends Page<V2010, BalancePayload, BalanceResource, BalanceInstance> {
  /**
   * Initialize the BalancePage
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: V2010, response: Response<string>, solution: BalanceSolution);

  /**
   * Build an instance of BalanceInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: BalancePayload): BalanceInstance;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

export { BalanceInstance, BalanceList, BalanceListInstance, BalancePage, BalancePayload, BalanceResource, BalanceSolution }


text:
package cruise.umple.core;

/**
 * The common  constants for code generation
 */
public interface CommonConstants {

	public static final String BLANK= ""; 				//$NON-NLS-1$
	public static final String LESS_THAN= "<"; 				//$NON-NLS-1$
	public static final String LESS_THAN_OR_EQUAL= "<="; 				//$NON-NLS-1$
	public static final String MORE_THAN= ">"; 				//$NON-NLS-1$
	public static final String EQUAL= "="; 				//$NON-NLS-1$
	public static final String TAB= "\t"; 				//$NON-NLS-1$
	public static final String ASTERISK= "*"; 				//$NON-NLS-1$
	public static final String COLON= ":"; 				//$NON-NLS-1$
	public static final String TILDE= "~"; 				//$NON-NLS-1$
	public static final String UNDERSCORE= "_";			//$NON-NLS-1$
	public static final String DOT= "."; 				//$NON-NLS-1$
	public static final String STRICT_DOT= "\\."; 				//$NON-NLS-1$
	public static final String NOT= "!"; 				//$NON-NLS-1$

	public static final String PLUS= "+"; 				//$NON-NLS-1$
	public static final String MINUS= "-"; 				//$NON-NLS-1$
	public static final String PLUS_SEPARATOR= "\\+"; 				//$NON-NLS-1$

	public static final String SPACE= " "; 				//$NON-NLS-1$
	public static final String SEMI_COLON= ";";			//$NON-NLS-1$
	public static final String FORWARD_SLASH= "/"; 		//$NON-NLS-1$
	public static final String BACK_SLASH= "\\"; 		//$NON-NLS-1$
	public static final String COMMA_SEPARATOR= ", "; 	//$NON-NLS-1$
	public static final String NEW_LINE= System.getProperties().getProperty("line.separator"); 			//$NON-NLS-1$
	public static final String OPEN_BRACE= "{"; 			//$NON-NLS-1$
	public static final String CLOSE_BRACE= "}"; 			//$NON-NLS-1$

	public static final String OPEN_SQUARE_BRACKET= "["; 			//$NON-NLS-1$
	public static final String CLOSE_SQUARE_BRACKET= "]"; 			//$NON-NLS-1$

	public static final String OPEN_BRACKET= "("; 			//$NON-NLS-1$
	public static final String CLOSE_BRACKET= ")"; 			//$NON-NLS-1$

	public static final String QUOTATION= "\"";			//$NON-NLS-1$

}


text:
package build

import (
	"crypto/tls"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/jlhawn/dockramp/build/commands"
	"github.com/jlhawn/dockramp/build/parser"
	"github.com/jlhawn/dockramp/build/util"
	"github.com/samalba/dockerclient"
)

type config struct {
	Cmd          []string
	Entrypoint   []string
	Env          []string
	ExposedPorts map[string]struct{}
	Labels       map[string]string
	User         string
	Volumes      map[string]struct{}
	WorkingDir   string
}

func (c *config) toDocker() *dockerclient.ContainerConfig {
	return &dockerclient.ContainerConfig{
		User:         c.User,
		ExposedPorts: c.ExposedPorts,
		Env:          c.Env,
		Cmd:          c.Cmd,
		Volumes:      c.Volumes,
		WorkingDir:   c.WorkingDir,
		Entrypoint:   c.Entrypoint,
		Labels:       c.Labels,
	}
}

type handlerFunc func(args []string, heredoc string) error

// Builder is able to build docker images from a local context directory, a
// Dockerfile, and a docker client connection.
type Builder struct {
	daemonURL        string
	tlsConfig        *tls.Config
	client           *dockerclient.DockerClient
	contextDirectory string
	dockerfilePath   string
	repo, tag        string

	out io.Writer

	config              *config
	maintainer          string
	imageID             string
	containerID         string
	uncommitted         bool
	uncommittedCommands []string

	cache map[string]string

	handlers map[string]handlerFunc
}

// NewBuilder creates a new builder.
func NewBuilder(daemonURL string, tlsConfig *tls.Config, contextDirectory, dockerfilePath, repoTag string) (*Builder, error) {
	// Validate that the context directory exists.
	stat, err := os.Stat(contextDirectory)
	if err != nil {
		return nil, fmt.Errorf("unable to access build context directory: %s", err)
	}
	if !stat.IsDir() {
		return nil, fmt.Errorf("context must be a directory")
	}

	if dockerfilePath == "" {
		// Use Default path.
		dockerfilePath = filepath.Join(contextDirectory, "Dockerfile")
	}

	if _, err := os.Stat(dockerfilePath); err != nil {
		return nil, fmt.Errorf("unable to access build file: %s", err)
	}

	// Validate the repository and tag.
	repo, tag := util.ParseRepositoryTag(repoTag)
	if repo != "" {
		if err := util.ValidateRepositoryName(repo); err != nil {
			return nil, fmt.Errorf("invalid repository name: %s", err)
		}
		if tag != "" {
			if err := util.ValidateTagName(tag); err != nil {
				return nil, fmt.Errorf("invalid tag: %s", err)
			}
		}
	}

	client, err := dockerclient.NewDockerClient(daemonURL, tlsConfig)
	if err != nil {
		return nil, fmt.Errorf("unable to initialize client: %s", err)
	}

	b := &Builder{
		daemonURL:        daemonURL,
		tlsConfig:        tlsConfig,
		client:           client,
		contextDirectory: contextDirectory,
		dockerfilePath:   dockerfilePath,
		repo:             repo,
		tag:              tag,
		out:              os.Stdout,
		config: &config{
			Labels:       map[string]string{},
			ExposedPorts: map[string]struct{}{},
			Volumes:      map[string]struct{}{},
		},
	}

	// Register Dockerfile Directive Handlers
	b.handlers = map[string]handlerFunc{
		commands.Cmd:        b.handleCmd,
		commands.Copy:       b.handleCopy,
		commands.Entrypoint: b.handleEntrypoint,
		commands.Env:        b.handleEnv,
		commands.Expose:     b.handleExpose,
		commands.Extract:    b.handleExtract,
		commands.From:       b.handleFrom,
		commands.Label:      b.handleLabel,
		commands.Maintainer: b.handleMaintainer,
		commands.Run:        b.handleRun,
		commands.User:       b.handleUser,
		commands.Volume:     b.handleVolume,
		commands.Workdir:    b.handleWorkdir,

		// Not implemented for now:
		commands.Add:     b.handleAdd,
		commands.Onbuild: b.handleOnbuild,
	}

	if err := b.loadCache(); err != nil {
		return nil, fmt.Errorf("unable to load build cache: %s", err)
	}

	return b, nil
}

// Run executes the build process.
func (b *Builder) Run() error {
	// Parse the Dockerfile.
	dockerfile, err := os.Open(b.dockerfilePath)
	if err != nil {
		return fmt.Errorf("unable to open Dockerfile: %s", err)
	}
	defer dockerfile.Close()

	commands, err := parser.Parse(dockerfile)
	if err != nil {
		return fmt.Errorf("unable to parse Dockerfile: %s", err)
	}

	if len(commands) == 0 {
		return fmt.Errorf("no commands found in Dockerfile")
	}

	for i, command := range commands {
		if err := b.dispatch(i, command); err != nil {
			return err
		}
	}

	// create container and commit if we need to (because of trailing
	// metadata directives).
	if b.uncommitted && !b.probeCache() {

		b.containerID, err = b.createContainer([]string{"/bin/sh", "-c"}, []string{"#(nop)"}, false)
		if err != nil {
			return fmt.Errorf("unable to create container: %s", err)
		}

		if err := b.commit(); err != nil {
			return fmt.Errorf("unable to commit container image: %s", err)
		}
	}

	imageName := b.imageID
	if b.repo != "" {
		if err := b.setTag(imageName, b.repo, b.tag); err != nil {
			return fmt.Errorf("unable to tag built image: %s", err)
		}

		imageName = b.repo
		if b.tag != "" {
			imageName = fmt.Sprintf("%s:%s", imageName, b.tag)
		}
	}

	fmt.Fprintf(b.out, "Successfully built %s\n", imageName)

	return nil
}

func (b *Builder) dispatch(stepNum int, command *parser.Command) error {
	cmd, args := strings.ToUpper(command.Args[0]), command.Args[1:]

	// FROM must be the first and only the first command.
	if (stepNum == 0) != (cmd == commands.From) {
		return fmt.Errorf("FROM must be the first Dockerfile command")
	}

	handler, exists := b.handlers[cmd]
	if !exists {
		return fmt.Errorf("unknown command: %q", cmd)
	}

	if _, ok := commands.ReplaceEnvAllowed[cmd]; ok {
		// Expand environment variables in the arguments.
		for i, arg := range args {
			arg, err := processShellWord(arg, b.config.Env)
			if err != nil {
				return err
			}

			args[i] = arg
		}
	}

	// Print the current step.
	commandStr := makeCommandString(cmd, args...)

	fmt.Fprintf(b.out, "Step %d: %s\n", stepNum, commandStr)

	b.uncommitted = true
	b.uncommittedCommands = append(b.uncommittedCommands, commandStr)

	if err := handler(args, command.Heredoc); err != nil {
		return err
	}

	// We may not need to commit now but we should if the current command may
	// have modified the filesystem. `b.uncommitted` will be set back to false
	// if there was a cache hit.
	if _, needCommit := commands.FilesystemModifierCommands[cmd]; needCommit && b.uncommitted {
		if err := b.commit(); err != nil {
			return fmt.Errorf("unable to commit container image: %s", err)
		}
	}

	return nil
}

// makeCommandString returns a printable form of the command and arguments with
// arguments quoted if necessary.
func makeCommandString(cmd string, args ...string) string {
	quotedArgs := make([]string, len(args))

	for i, arg := range args {
		if strings.ContainsAny(arg, "<#'\" \f\n\r\t\v\\") {
			arg = strconv.Quote(arg)
		}
		quotedArgs[i] = arg
	}

	return fmt.Sprintf("%s %s", cmd, strings.Join(quotedArgs, " "))
}


text:
<?php

namespace IPS\Helpers\Form;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * Select-box class for Form Builder
 */
class _Select extends FormAbstract
{
	/**
	 * @brief	Default Options
	 * @code
	 	$defaultOptions = array(
	 		'options'			=> array( 'key' => 'val', 'key' => 'val', ... )	// Options for select box
	 		'toggles'			=> array( 'key' => array( ... ) )	// IDs that each option should show/hide when toggled
	 		'multiple'			=> TRUE		// Sets the select box to allow multiple values to be selected. Default is FALSE.
	 		'class'				=> '',		// CSS class
	 		'disabled'			=> FALSE,	// Disables input. Default is FALSE.
	 		'parse'				=> 'lang',	// Sets how the values for options should be parsed. Acceptable values are "lang" (language keys), "normal" (htmlentities), "raw" (no parsing) or "image" (image URLs, only for Radio fields).  Default is "lang".
	 		'unlimited'			=> -1,			// If any value other than NULL is provided, an "Unlimited" checkbox will be displayed. If checked, the value specified will be sent.
	 		'unlimitedLang'		=> 'unlimited',	// Language string to use for unlimited checkbox label
	 		'unlimitedToggles'	=> array(...),	// Names of other input fields that should show/hide when the "Unlimited" checkbox is toggled.
	 		'unlimitedToggleOn'	=> TRUE,		// Whether the toggles should show on unlimited checked (TRUE) or unchecked(FALSE). Default is TRUE
	 		'userSuppliedInput'	=> ''		// If this option is selected (it must be a valid option passed to 'options'), a text input field will display, allowing the user to enter their own value
	 		'noDefault'			=> TRUE		// For radios, you can set this to TRUE if you do not want any radio option selected by default (useful for things like polls)
	 		'returnLabels'		=> FALSE	// If TRUE, will return the labels rather than the keys as the value
	 		'sort'				=> FALSE,	// If TRUE, options will be sorted by JavaScript. Useful where the options are language-dependant but you still want them to be in alphabetical order
	 	);
	 * @endcode
	 */
	protected $defaultOptions = array(
		'options'			=> array(),
		'toggles'			=> array(),
		'multiple'			=> FALSE,
		'class'				=> '',
		'disabled'			=> FALSE,
		'parse'				=> 'lang',
		'unlimited'			=> NULL,
		'unlimitedLang'		=> 'all',
		'unlimitedToggles'	=> array(),
		'unlimitedToggleOn'	=> TRUE,
		'userSuppliedInput'	=> '',
		'noDefault'			=> FALSE,
		'returnLabels'		=> FALSE,
		'sort'				=> FALSE,
	);

	/**
	 * Constructor
	 *
	 * @param	string		$name					Name
	 * @param	mixed		$defaultValue			Default value
	 * @param	bool		$required				Required?
	 * @param	array		$options				Type-specific options
	 * @param	callback	$customValidationCode	Custom validation code
	 * @param	string		$prefix					HTML to show before input field
	 * @param	string		$suffix					HTML to show after input field
	 * @param	string		$id						The ID to add to the row
	 * @return	void
	 */
	public function __construct( $name, $defaultValue=NULL, $required=FALSE, $options=array(), $customValidationCode=NULL, $prefix=NULL, $suffix=NULL, $id=NULL )
	{
		/* Set the default value to the first option if one isn't provided */
		if ( $defaultValue === NULL and ( !isset( $options['noDefault'] ) OR !$options['noDefault'] ) and is_array( $options['options'] ) )
		{
			foreach ( $options['options'] as $k => $v )
			{
				if ( is_array( $v ) )
				{
					foreach ( $v as $_k => $_v )
					{
						if ( !isset( $options['disabled'] ) OR ( is_array( $options['disabled'] ) AND !in_array( $_k, $options['disabled'] ) ) )
						{
							$defaultValue = $_k;
							break;
						}
					}
				}
				else
				{
					if ( !isset( $options['disabled'] ) OR ( is_array( $options['disabled'] ) AND !in_array( $k, $options['disabled'] ) ) )
					{
						$defaultValue = $k;
						break;
					}
				}
			}

			if ( isset( $options['multiple'] ) and $options['multiple'] === TRUE )
			{
				$defaultValue = array( $defaultValue );
			}
		}

		/* Call parent constructor */
		call_user_func( 'parent::__construct', $name, $defaultValue, $required, $options, $customValidationCode, $prefix, $suffix, $id );
	}

	/**
	 * Get HTML
	 *
	 * @return	string
	 */
	public function html()
	{
		/* Add [] to the name if this is a multi-select */
		$name = $this->name;
		if ( $this->options['multiple'] )
		{
			$name .= '[]';
		}

		/* Translate labels back to keys? */
		if ( $this->options['returnLabels'] )
		{
			$value = array();
			if ( is_array( $this->value ) )
			{
				foreach ( $this->value as $v )
				{
					$value[] = array_search( $v, $this->options['options'] );
				}
			}
			else
			{
				$value = array_search( $this->value, $this->options['options'] );
			}
		}
		else
		{
			$value = $this->value;
		}

		return \IPS\Theme::i()->getTemplate( 'forms', 'core' )->select( $name, $value, $this->required, $this->parseOptions(), $this->options['multiple'], $this->options['class'], $this->options['disabled'], $this->options['toggles'], $this->htmlId, $this->options['unlimited'], $this->options['unlimitedLang'], $this->options['unlimitedToggles'], $this->options['unlimitedToggleOn'], $this->options['userSuppliedInput'], $this->options['sort'], $this->options['parse'] );
	}

	/**
	 * Parse Values
	 *
	 * @return	array
	 */
	protected function parseOptions()
	{
		$options = $this->options['options'];
		switch ( $this->options['parse'] )
		{
			case 'lang':
				foreach ( $this->options['options'] as $k => $v )
				{
					if ( is_array( $v ) )
					{
						foreach ( $v as $x => $y )
						{
							$options[ $k ][ $x ] = \IPS\Member::loggedIn()->language()->addToStack( $y );
						}
					}
					else
					{
						$options[ $k ] = \IPS\Member::loggedIn()->language()->addToStack( $v );
					}
				}
				break;

			case 'normal':
				foreach ( $this->options['options'] as $k => $v )
				{
					if ( is_array( $v ) )
					{
						foreach ( $v as $x => $y )
						{
							$options[ $k ][ $x ] = htmlspecialchars( $y, \IPS\HTMLENTITIES, 'UTF-8', FALSE );
						}
					}
					else
					{
						$options[ $k ] = htmlspecialchars( $v, \IPS\HTMLENTITIES, 'UTF-8', FALSE );
					}
				}
				break;
		}

		return $options;
	}

	/**
	 * Get value
	 *
	 * @return	array
	 */
	public function getValue()
	{
		/* Unlimited? */
		$unlimitedName = "{$this->name}_unlimited";
		if ( $this->options['unlimited'] !== NULL and isset( \IPS\Request::i()->$unlimitedName ) )
		{
			return $this->options['unlimited'];
		}

		/* Get value */
		$value = parent::getValue();

		if( isset( $this->options['userSuppliedInput'] ) )
		{
			if( $value == $this->options['userSuppliedInput'] )
			{
				$name	= $this->options['userSuppliedInput'] . '_' . $this->name;
				$value	= mb_strpos( $name, '[' ) ? \IPS\Request::i()->valueFromArray( $name ) : \IPS\Request::i()->$name;
			}
		}

		if ( isset( $value ) AND is_array( $value ) AND $this->options['multiple'] AND array_search( '__EMPTY', $value ) !== FALSE )
		{
			unset( $value[ array_search( '__EMPTY', $value ) ] );
		}

		if ( $this->options['returnLabels'] )
		{
			if ( is_array( $value ) )
			{
				$return = array();
				foreach ( $value as $k => $v )
				{
					$return[ $k ] = $this->options['options'][ $v ];
				}
				return $return;
			}
			else
			{
				return $this->options['options'][ $value ];
			}
		}

		return $value;
	}

	/**
	 * Validate
	 *
	 * @throws	\OutOfRangeException
	 * @return	TRUE
	 */
	public function validate()
	{
		if( $this->options['userSuppliedInput'] )
		{
			return TRUE;
		}

		/* If it is not required and there is no value (pagination from table advanced search form then pass validation otherwise it throws an error) */
		if ( $this->value === NULL and ! $this->required )
		{
			return TRUE;
		}

		parent::validate();

		$acceptableValues = array();
		if ( $this->options['unlimited'] !== NULL )
		{
			$acceptableValues[] = $this->options['unlimited'];
		}
		foreach ( $this->options['options'] as $k => $v )
		{
			if ( is_array( $v ) )
			{
				$acceptableValues = array_merge( $acceptableValues, $this->options['returnLabels']  ? $v : array_keys( $v ) );
			}
			else
			{
				$acceptableValues[] = $this->options['returnLabels'] ? $v : $k;
			}
		}

		$disabledValues = ( is_array( $this->options['disabled'] ) ) ? $this->options['disabled'] : array( $this->options['disabled'] );
		$acceptableValues = array_diff( $acceptableValues, $disabledValues );

		$diff = array_diff( ( is_array( $this->value ) ? $this->value : array( $this->value ) ), $acceptableValues );
		if ( !empty( $diff ) )
		{
			/* Is the entire thing disabled? If so, just return any default value set (if one has been set)*/
			if ( $this->options['disabled'] === TRUE and $this->defaultValue )
			{
				return $this->defaultValue;
			}

			throw new \OutOfRangeException( 'form_bad_value' );
		}

		if ( $this->options['multiple'] and $this->required and empty( $this->value ) )
		{
			throw new \DomainException( 'form_required' );
		}

		return TRUE;
	}
}


text: main = putStr "Hello, world\n"


text:
<?php

declare(strict_types=1);

namespace Valkyrja\Filesystem\Constants;

use League\Flysystem\Adapter\Local;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use Valkyrja\Config\Constants\ConfigKeyPart as CKP;
use Valkyrja\Filesystem\Adapters\FlysystemAdapter;
use Valkyrja\Filesystem\Drivers\Driver;

/**
 * Constant ConfigValue.
 *
 * @author Melech Mizrachi
 */
final class ConfigValue
{
    public const DEFAULT = CKP::LOCAL;
    public const ADAPTER = FlysystemAdapter::class;
    public const DRIVER  = Driver::class;
    public const DISKS   = [
        CKP::LOCAL => [
            CKP::ADAPTER           => CKP::FLYSYSTEM,
            CKP::DRIVER            => CKP::DEFAULT,
            CKP::FLYSYSTEM_ADAPTER => Local::class,
            CKP::DIR               => '/',
        ],
        CKP::S3    => [
            CKP::ADAPTER           => CKP::FLYSYSTEM,
            CKP::DRIVER            => CKP::DEFAULT,
            CKP::FLYSYSTEM_ADAPTER => AwsS3Adapter::class,
            CKP::KEY               => '',
            CKP::SECRET            => '',
            CKP::REGION            => 'us1',
            CKP::VERSION           => 'latest',
            CKP::BUCKET            => '',
            CKP::PREFIX            => '',
            CKP::OPTIONS           => [],
        ],
    ];

    public static array $defaults = [
        CKP::DEFAULT => self::DEFAULT,
        CKP::ADAPTER => self::ADAPTER,
        CKP::DRIVER  => self::DRIVER,
        CKP::DISKS   => self::DISKS,
    ];
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".controllers.ServiceOrderActivity">

    <item
        android:id="@+id/actionAdd"
        android:title="@string/lbl_add"
        android:icon="@mipmap/ic_action_add"
        app:showAsAction="always" />

</menu>