text:
import styled from 'styled-components'

import css, { theme } from '@/utils/css'

export const Wrapper = styled.div`
  ${css.flexColumn()};
  width: 100%;
`
export const TabWrapper = styled.div`
  ${css.flex('align-center')};
  position: absolute;
  left: 0;
  bottom: -1px;
`


text:
package org.apache.zeppelin.rest;

import com.google.common.collect.Sets;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang3.StringUtils;
import org.apache.zeppelin.annotation.ZeppelinApi;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.NoteInfo;
import org.apache.zeppelin.notebook.Notebook;
import org.apache.zeppelin.notebook.NotebookAuthorization;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.rest.exception.BadRequestException;
import org.apache.zeppelin.rest.exception.ForbiddenException;
import org.apache.zeppelin.rest.exception.NoteNotFoundException;
import org.apache.zeppelin.rest.exception.ParagraphNotFoundException;
import org.apache.zeppelin.rest.message.CronRequest;
import org.apache.zeppelin.rest.message.NewNoteRequest;
import org.apache.zeppelin.rest.message.NewParagraphRequest;
import org.apache.zeppelin.rest.message.RenameNoteRequest;
import org.apache.zeppelin.rest.message.RunParagraphWithParametersRequest;
import org.apache.zeppelin.rest.message.UpdateParagraphRequest;
import org.apache.zeppelin.search.SearchService;
import org.apache.zeppelin.server.JsonResponse;
import org.apache.zeppelin.service.JobManagerService;
import org.apache.zeppelin.service.NotebookService;
import org.apache.zeppelin.service.SecurityService;
import org.apache.zeppelin.service.ServiceContext;
import org.apache.zeppelin.socket.NotebookServer;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Rest api endpoint for the notebook.
 */
@Path("/notebook")
@Produces("application/json")
@Singleton
public class NotebookRestApi extends AbstractRestApi {
  private static final Logger LOG = LoggerFactory.getLogger(NotebookRestApi.class);
  private static Gson gson = new Gson();

  private ZeppelinConfiguration zConf;
  private Notebook notebook;
  private NotebookServer notebookServer;
  private SearchService noteSearchService;
  private NotebookAuthorization notebookAuthorization;
  private NotebookService notebookService;
  private JobManagerService jobManagerService;
  private SecurityService securityService;

  @Inject
  public NotebookRestApi(
      Notebook notebook,
      NotebookServer notebookServer,
      NotebookService notebookService,
      SearchService search,
      NotebookAuthorization notebookAuthorization,
      ZeppelinConfiguration zConf,
      SecurityService securityService,
      JobManagerService jobManagerService) {
    super(securityService);
    this.notebook = notebook;
    this.notebookServer = notebookServer;
    this.notebookService = notebookService;
    this.jobManagerService = jobManagerService;
    this.noteSearchService = search;
    this.notebookAuthorization = notebookAuthorization;
    this.zConf = zConf;
    this.securityService = securityService;
  }

  /**
   * Get note authorization information.
   */
  @GET
  @Path("{noteId}/permissions")
  @ZeppelinApi
  public Response getNotePermissions(@PathParam("noteId") String noteId) throws IOException {
    checkIfUserIsAnon(getBlockNotAuthenticatedUserErrorMsg());
    checkIfUserCanRead(noteId,
        "Insufficient privileges you cannot get the list of permissions for this note");
    HashMap<String, Set<String>> permissionsMap = new HashMap<>();
    permissionsMap.put("owners", notebookAuthorization.getOwners(noteId));
    permissionsMap.put("readers", notebookAuthorization.getReaders(noteId));
    permissionsMap.put("writers", notebookAuthorization.getWriters(noteId));
    permissionsMap.put("runners", notebookAuthorization.getRunners(noteId));
    return new JsonResponse<>(Status.OK, "", permissionsMap).build();
  }

  private String ownerPermissionError(Set<String> current, Set<String> allowed) {
    LOG.info("Cannot change permissions. Connection owners {}. Allowed owners {}",
        current.toString(), allowed.toString());
    return "Insufficient privileges to change permissions.\n\n" +
        "Allowed owners: " + allowed.toString() + "\n\n" +
        "User belongs to: " + current.toString();
  }

  private String getBlockNotAuthenticatedUserErrorMsg() {
    return "Only authenticated user can set the permission.";
  }

  /*
   * Set of utils method to check if current user can perform action to the note.
   * Since we only have security on notebook level, from now we keep this logic in this class.
   * In the future we might want to generalize this for the rest of the api enmdpoints.
   */

  /**
   * Check if the current user is not authenticated(anonymous user) or not.
   */
  private void checkIfUserIsAnon(String errorMsg) {
    boolean isAuthenticated = securityService.isAuthenticated();
    if (isAuthenticated && securityService.getPrincipal().equals("anonymous")) {
      LOG.info("Anonymous user cannot set any permissions for this note.");
      throw new ForbiddenException(errorMsg);
    }
  }

  /**
   * Check if the current user own the given note.
   */
  private void checkIfUserIsOwner(String noteId, String errorMsg) {
    Set<String> userAndRoles = Sets.newHashSet();
    userAndRoles.add(securityService.getPrincipal());
    userAndRoles.addAll(securityService.getAssociatedRoles());
    if (!notebookAuthorization.isOwner(userAndRoles, noteId)) {
      throw new ForbiddenException(errorMsg);
    }
  }

  /**
   * Check if the current user is either Owner or Writer for the given note.
   */
  private void checkIfUserCanWrite(String noteId, String errorMsg) {
    Set<String> userAndRoles = Sets.newHashSet();
    userAndRoles.add(securityService.getPrincipal());
    userAndRoles.addAll(securityService.getAssociatedRoles());
    if (!notebookAuthorization.hasWriteAuthorization(userAndRoles, noteId)) {
      throw new ForbiddenException(errorMsg);
    }
  }

  /**
   * Check if the current user can access (at least he have to be reader) the given note.
   */
  private void checkIfUserCanRead(String noteId, String errorMsg) {
    Set<String> userAndRoles = Sets.newHashSet();
    userAndRoles.add(securityService.getPrincipal());
    userAndRoles.addAll(securityService.getAssociatedRoles());
    if (!notebookAuthorization.hasReadAuthorization(userAndRoles, noteId)) {
      throw new ForbiddenException(errorMsg);
    }
  }

  /**
   * Check if the current user can run the given note.
   */
  private void checkIfUserCanRun(String noteId, String errorMsg) {
    Set<String> userAndRoles = Sets.newHashSet();
    userAndRoles.add(securityService.getPrincipal());
    userAndRoles.addAll(securityService.getAssociatedRoles());
    if (!notebookAuthorization.hasRunAuthorization(userAndRoles, noteId)) {
      throw new ForbiddenException(errorMsg);
    }
  }

  private void checkIfNoteIsNotNull(Note note) {
    if (note == null) {
      throw new NoteNotFoundException("note not found");
    }
  }

  private void checkIfNoteSupportsCron(Note note) {
    if (!note.isCronSupported(notebook.getConf())) {
      LOG.error("Cron is not enabled from Zeppelin server");
      throw new ForbiddenException("Cron is not enabled from Zeppelin server");
    }
  }

  private void checkIfParagraphIsNotNull(Paragraph paragraph) {
    if (paragraph == null) {
      throw new ParagraphNotFoundException("paragraph not found");
    }
  }

  /**
   * Set note authorization information.
   */
  @PUT
  @Path("{noteId}/permissions")
  @ZeppelinApi
  public Response putNotePermissions(@PathParam("noteId") String noteId, String req)
      throws IOException {
    String principal = securityService.getPrincipal();
    Set<String> roles = securityService.getAssociatedRoles();
    HashSet<String> userAndRoles = new HashSet<>();
    userAndRoles.add(principal);
    userAndRoles.addAll(roles);

    checkIfUserIsAnon(getBlockNotAuthenticatedUserErrorMsg());
    checkIfUserIsOwner(noteId,
        ownerPermissionError(userAndRoles, notebookAuthorization.getOwners(noteId)));

    HashMap<String, HashSet<String>> permMap =
        gson.fromJson(req, new TypeToken<HashMap<String, HashSet<String>>>() {
        }.getType());
    Note note = notebook.getNote(noteId);

    LOG.info("Set permissions {} {} {} {} {} {}", noteId, principal, permMap.get("owners"),
        permMap.get("readers"), permMap.get("runners"), permMap.get("writers"));

    HashSet<String> readers = permMap.get("readers");
    HashSet<String> runners = permMap.get("runners");
    HashSet<String> owners = permMap.get("owners");
    HashSet<String> writers = permMap.get("writers");
    // Set readers, if runners, writers and owners is empty -> set to user requesting the change
    if (readers != null && !readers.isEmpty()) {
      if (runners.isEmpty()) {
        runners = Sets.newHashSet(securityService.getPrincipal());
      }
      if (writers.isEmpty()) {
        writers = Sets.newHashSet(securityService.getPrincipal());
      }
      if (owners.isEmpty()) {
        owners = Sets.newHashSet(securityService.getPrincipal());
      }
    }
    // Set runners, if writers and owners is empty -> set to user requesting the change
    if (runners != null && !runners.isEmpty()) {
      if (writers.isEmpty()) {
        writers = Sets.newHashSet(securityService.getPrincipal());
      }
      if (owners.isEmpty()) {
        owners = Sets.newHashSet(securityService.getPrincipal());
      }
    }
    // Set writers, if owners is empty -> set to user requesting the change
    if (writers != null && !writers.isEmpty()) {
      if (owners.isEmpty()) {
        owners = Sets.newHashSet(securityService.getPrincipal());
      }
    }

    notebookAuthorization.setReaders(noteId, readers);
    notebookAuthorization.setRunners(noteId, runners);
    notebookAuthorization.setWriters(noteId, writers);
    notebookAuthorization.setOwners(noteId, owners);
    LOG.debug("After set permissions {} {} {} {}", notebookAuthorization.getOwners(noteId),
        notebookAuthorization.getReaders(noteId), notebookAuthorization.getRunners(noteId),
        notebookAuthorization.getWriters(noteId));
    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
    notebook.saveNote(note, subject);
    notebookServer.broadcastNote(note);
    notebookServer.broadcastNoteList(subject, userAndRoles);
    return new JsonResponse<>(Status.OK).build();
  }

  @GET
  @ZeppelinApi
  public Response getNoteList() throws IOException {
    List<NoteInfo> notesInfo = notebookService.listNotesInfo(false, getServiceContext(),
        new RestServiceCallback<List<NoteInfo>>());
    return new JsonResponse<>(Status.OK, "", notesInfo).build();
  }

  @GET
  @Path("{noteId}")
  @ZeppelinApi
  public Response getNote(@PathParam("noteId") String noteId) throws IOException {
    Note note =
        notebookService.getNote(noteId, getServiceContext(), new RestServiceCallback());
    return new JsonResponse<>(Status.OK, "", note).build();
  }

  /**
   * export note REST API.
   *
   * @param noteId ID of Note
   * @return note JSON with status.OK
   * @throws IOException
   */
  @GET
  @Path("export/{noteId}")
  @ZeppelinApi
  public Response exportNote(@PathParam("noteId") String noteId) throws IOException {
    checkIfUserCanRead(noteId, "Insufficient privileges you cannot export this note");
    String exportJson = notebook.exportNote(noteId);
    return new JsonResponse<>(Status.OK, "", exportJson).build();
  }

  /**
   * import new note REST API.
   *
   * @param noteJson - note Json
   * @return JSON with new note ID
   * @throws IOException
   */
  @POST
  @Path("import")
  @ZeppelinApi
  public Response importNote(String noteJson) throws IOException {
    Note note = notebookService.importNote(null, noteJson, getServiceContext(),
        new RestServiceCallback());
    return new JsonResponse<>(Status.OK, "", note.getId()).build();
  }

  /**
   * Create new note REST API.
   *
   * @param message - JSON with new note name
   * @return JSON with new note ID
   * @throws IOException
   */
  @POST
  @ZeppelinApi
  public Response createNote(String message) throws IOException {
    String user = securityService.getPrincipal();
    LOG.info("Create new note by JSON {}", message);
    NewNoteRequest request = NewNoteRequest.fromJson(message);
    Note note = notebookService.createNote(
        request.getName(),
        zConf.getString(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_GROUP_DEFAULT),
        getServiceContext(),
        new RestServiceCallback<>());
    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
    if (request.getParagraphs() != null) {
      for (NewParagraphRequest paragraphRequest : request.getParagraphs()) {
        Paragraph p = note.addNewParagraph(subject);
        initParagraph(p, paragraphRequest, user);
      }
    }
    return new JsonResponse<>(Status.OK, "", note.getId()).build();
  }

  /**
   * Delete note REST API.
   *
   * @param noteId ID of Note
   * @return JSON with status.OK
   * @throws IOException
   */
  @DELETE
  @Path("{noteId}")
  @ZeppelinApi
  public Response deleteNote(@PathParam("noteId") String noteId) throws IOException {
    LOG.info("Delete note {} ", noteId);
    notebookService.removeNote(noteId,
        getServiceContext(),
        new RestServiceCallback<String>() {
          @Override
          public void onSuccess(String message, ServiceContext context) {
            notebookServer.broadcastNoteList(context.getAutheInfo(), context.getUserAndRoles());
          }
        });

    return new JsonResponse<>(Status.OK, "").build();
  }

  /**
   * Clone note REST API.
   *
   * @param noteId ID of Note
   * @return JSON with status.OK
   * @throws IOException
   * @throws CloneNotSupportedException
   * @throws IllegalArgumentException
   */
  @POST
  @Path("{noteId}")
  @ZeppelinApi
  public Response cloneNote(@PathParam("noteId") String noteId, String message)
      throws IOException, IllegalArgumentException {
    LOG.info("clone note by JSON {}", message);
    checkIfUserCanWrite(noteId, "Insufficient privileges you cannot clone this note");
    NewNoteRequest request = NewNoteRequest.fromJson(message);
    String newNoteName = null;
    if (request != null) {
      newNoteName = request.getName();
    }
    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
    Note newNote = notebookService.cloneNote(noteId, newNoteName, getServiceContext(),
        new RestServiceCallback<Note>(){
          @Override
          public void onSuccess(Note newNote, ServiceContext context) throws IOException {
            notebookServer.broadcastNote(newNote);
            notebookServer.broadcastNoteList(subject, context.getUserAndRoles());
          }
        });
    return new JsonResponse<>(Status.OK, "", newNote.getId()).build();
  }

  /**
   * Rename note REST API
   *
   * @param message - JSON containing new name
   * @return JSON with status.OK
   * @throws IOException
   */
  @PUT
  @Path("{noteId}/rename")
  @ZeppelinApi
  public Response renameNote(@PathParam("noteId") String noteId,
                             String message) throws IOException {
    LOG.info("rename note by JSON {}", message);
    RenameNoteRequest request = gson.fromJson(message, RenameNoteRequest.class);
    String newName = request.getName();
    if (newName.isEmpty()) {
      LOG.warn("Trying to rename notebook {} with empty name parameter", noteId);
      throw new BadRequestException("name can not be empty");
    }
    notebookService.renameNote(noteId, request.getName(), false, getServiceContext(),
        new RestServiceCallback<Note>(){
          @Override
          public void onSuccess(Note note, ServiceContext context) throws IOException {
            notebookServer.broadcastNote(note);
            notebookServer.broadcastNoteList(context.getAutheInfo(), context.getUserAndRoles());
          }
        });
    return new JsonResponse(Status.OK, "").build();
  }

  /**
   * Insert paragraph REST API.
   *
   * @param message - JSON containing paragraph's information
   * @return JSON with status.OK
   * @throws IOException
   */
  @POST
  @Path("{noteId}/paragraph")
  @ZeppelinApi
  public Response insertParagraph(@PathParam("noteId") String noteId, String message)
      throws IOException {
    String user = securityService.getPrincipal();
    LOG.info("insert paragraph {} {}", noteId, message);

    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanWrite(noteId, "Insufficient privileges you cannot add paragraph to this note");

    NewParagraphRequest request = NewParagraphRequest.fromJson(message);
    AuthenticationInfo subject = new AuthenticationInfo(user);
    Paragraph p;
    Double indexDouble = request.getIndex();
    if (indexDouble == null) {
      p = note.addNewParagraph(subject);
    } else {
      p = note.insertNewParagraph(indexDouble.intValue(), subject);
    }
    initParagraph(p, request, user);
    notebook.saveNote(note, subject);
    notebookServer.broadcastNote(note);
    return new JsonResponse<>(Status.OK, "", p.getId()).build();
  }

  /**
   * Get paragraph REST API.
   *
   * @param noteId ID of Note
   * @return JSON with information of the paragraph
   * @throws IOException
   */
  @GET
  @Path("{noteId}/paragraph/{paragraphId}")
  @ZeppelinApi
  public Response getParagraph(@PathParam("noteId") String noteId,
                               @PathParam("paragraphId") String paragraphId) throws IOException {
    LOG.info("get paragraph {} {}", noteId, paragraphId);

    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanRead(noteId, "Insufficient privileges you cannot get this paragraph");
    Paragraph p = note.getParagraph(paragraphId);
    checkIfParagraphIsNotNull(p);

    return new JsonResponse<>(Status.OK, "", p).build();
  }

  /**
   * Update paragraph.
   *
   * @param message json containing the "text" and optionally the "title" of the paragraph, e.g.
   *                {"text" : "updated text", "title" : "Updated title" }
   */
  @PUT
  @Path("{noteId}/paragraph/{paragraphId}")
  @ZeppelinApi
  public Response updateParagraph(@PathParam("noteId") String noteId,
                                  @PathParam("paragraphId") String paragraphId,
                                  String message) throws IOException {
    String user = securityService.getPrincipal();
    LOG.info("{} will update paragraph {} {}", user, noteId, paragraphId);

    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanWrite(noteId, "Insufficient privileges you cannot update this paragraph");
    Paragraph p = note.getParagraph(paragraphId);
    checkIfParagraphIsNotNull(p);

    UpdateParagraphRequest updatedParagraph = gson.fromJson(message, UpdateParagraphRequest.class);
    p.setText(updatedParagraph.getText());

    if (updatedParagraph.getTitle() != null) {
      p.setTitle(updatedParagraph.getTitle());
    }

    AuthenticationInfo subject = new AuthenticationInfo(user);
    notebook.saveNote(note, subject);
    notebookServer.broadcastParagraph(note, p);
    return new JsonResponse<>(Status.OK, "").build();
  }

  @PUT
  @Path("{noteId}/paragraph/{paragraphId}/config")
  @ZeppelinApi
  public Response updateParagraphConfig(@PathParam("noteId") String noteId,
                                        @PathParam("paragraphId") String paragraphId,
                                        String message) throws IOException {
    String user = securityService.getPrincipal();
    LOG.info("{} will update paragraph config {} {}", user, noteId, paragraphId);

    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanWrite(noteId, "Insufficient privileges you cannot update this paragraph config");
    Paragraph p = note.getParagraph(paragraphId);
    checkIfParagraphIsNotNull(p);

    Map<String, Object> newConfig = gson.fromJson(message, HashMap.class);
    configureParagraph(p, newConfig, user);
    AuthenticationInfo subject = new AuthenticationInfo(user);
    notebook.saveNote(note, subject);
    return new JsonResponse<>(Status.OK, "", p).build();
  }

  /**
   * Move paragraph REST API.
   *
   * @param newIndex - new index to move
   * @return JSON with status.OK
   * @throws IOException
   */
  @POST
  @Path("{noteId}/paragraph/{paragraphId}/move/{newIndex}")
  @ZeppelinApi
  public Response moveParagraph(@PathParam("noteId") String noteId,
                                @PathParam("paragraphId") String paragraphId,
                                @PathParam("newIndex") String newIndex)
      throws IOException {
    LOG.info("move paragraph {} {} {}", noteId, paragraphId, newIndex);
    notebookService.moveParagraph(noteId, paragraphId, Integer.parseInt(newIndex),
        getServiceContext(),
        new RestServiceCallback<Paragraph>() {
          @Override
          public void onSuccess(Paragraph result, ServiceContext context) throws IOException {
            notebookServer.broadcastNote(result.getNote());
          }
        });
    return new JsonResponse(Status.OK, "").build();

  }

  /**
   * Delete paragraph REST API.
   *
   * @param noteId ID of Note
   * @return JSON with status.OK
   * @throws IOException
   */
  @DELETE
  @Path("{noteId}/paragraph/{paragraphId}")
  @ZeppelinApi
  public Response deleteParagraph(@PathParam("noteId") String noteId,
                                  @PathParam("paragraphId") String paragraphId) throws IOException {
    LOG.info("delete paragraph {} {}", noteId, paragraphId);
    notebookService.removeParagraph(noteId, paragraphId, getServiceContext(),
        new RestServiceCallback<Paragraph>() {
          @Override
          public void onSuccess(Paragraph p, ServiceContext context) throws IOException {
            notebookServer.broadcastNote(p.getNote());
          }
        });

    return new JsonResponse(Status.OK, "").build();
  }

  /**
   * Clear result of all paragraphs REST API.
   *
   * @param noteId ID of Note
   * @return JSON with status.ok
   */
  @PUT
  @Path("{noteId}/clear")
  @ZeppelinApi
  public Response clearAllParagraphOutput(@PathParam("noteId") String noteId)
      throws IOException {
    LOG.info("clear all paragraph output of note {}", noteId);
    notebookService.clearAllParagraphOutput(noteId, getServiceContext(),
        new RestServiceCallback<>());
    return new JsonResponse(Status.OK, "").build();
  }

  /**
   * Run note jobs REST API.
   *
   * @param noteId ID of Note
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @POST
  @Path("job/{noteId}")
  @ZeppelinApi
  public Response runNoteJobs(@PathParam("noteId") String noteId,
                              @QueryParam("waitToFinish") Boolean waitToFinish)
      throws IOException, IllegalArgumentException {
    boolean blocking = waitToFinish == null || waitToFinish;
    LOG.info("run note jobs {} waitToFinish: {}", noteId, blocking);
    Note note = notebook.getNote(noteId);
    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
    subject.setRoles(new LinkedList<>(securityService.getAssociatedRoles()));
    checkIfNoteIsNotNull(note);
    checkIfUserCanRun(noteId, "Insufficient privileges you cannot run job for this note");

    try {
      note.runAll(subject, blocking);
    } catch (Exception ex) {
      LOG.error("Exception from run", ex);
      return new JsonResponse<>(Status.PRECONDITION_FAILED,
          ex.getMessage() + "- Not selected or Invalid Interpreter bind").build();
    }
    return new JsonResponse<>(Status.OK).build();
  }

  /**
   * Stop(delete) note jobs REST API.
   *
   * @param noteId ID of Note
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @DELETE
  @Path("job/{noteId}")
  @ZeppelinApi
  public Response stopNoteJobs(@PathParam("noteId") String noteId)
      throws IOException, IllegalArgumentException {
    LOG.info("stop note jobs {} ", noteId);
    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanRun(noteId, "Insufficient privileges you cannot stop this job for this note");

    for (Paragraph p : note.getParagraphs()) {
      if (!p.isTerminated()) {
        p.abort();
      }
    }
    return new JsonResponse<>(Status.OK).build();
  }

  /**
   * Get note job status REST API.
   *
   * @param noteId ID of Note
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @GET
  @Path("job/{noteId}")
  @ZeppelinApi
  public Response getNoteJobStatus(@PathParam("noteId") String noteId)
      throws IOException, IllegalArgumentException {
    LOG.info("get note job status.");
    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanRead(noteId, "Insufficient privileges you cannot get job status");

    return new JsonResponse<>(Status.OK, null, note.generateParagraphsInfo()).build();
  }

  /**
   * Get note paragraph job status REST API.
   *
   * @param noteId      ID of Note
   * @param paragraphId ID of Paragraph
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @GET
  @Path("job/{noteId}/{paragraphId}")
  @ZeppelinApi
  public Response getNoteParagraphJobStatus(@PathParam("noteId") String noteId,
                                            @PathParam("paragraphId") String paragraphId)
      throws IOException, IllegalArgumentException {
    LOG.info("get note paragraph job status.");
    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanRead(noteId, "Insufficient privileges you cannot get job status");

    Paragraph paragraph = note.getParagraph(paragraphId);
    checkIfParagraphIsNotNull(paragraph);

    return new JsonResponse<>(Status.OK, null, note.generateSingleParagraphInfo(paragraphId)).
        build();
  }

  /**
   * Run asynchronously paragraph job REST API.
   *
   * @param message - JSON with params if user wants to update dynamic form's value
   *                null, empty string, empty json if user doesn't want to update
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @POST
  @Path("job/{noteId}/{paragraphId}")
  @ZeppelinApi
  public Response runParagraph(@PathParam("noteId") String noteId,
                               @PathParam("paragraphId") String paragraphId, String message)
      throws IOException, IllegalArgumentException {
    LOG.info("run paragraph job asynchronously {} {} {}", noteId, paragraphId, message);

    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    Paragraph paragraph = note.getParagraph(paragraphId);
    checkIfParagraphIsNotNull(paragraph);

    Map<String, Object> params = new HashMap<>();
    if (!StringUtils.isEmpty(message)) {
      RunParagraphWithParametersRequest request =
          RunParagraphWithParametersRequest.fromJson(message);
      params = request.getParams();
    }
    notebookService.runParagraph(noteId, paragraphId, paragraph.getTitle(),
            paragraph.getText(), params, new HashMap<>(),
            false, false, getServiceContext(), new RestServiceCallback<>());
    return new JsonResponse<>(Status.OK).build();
  }

  /**
   * Run synchronously a paragraph REST API.
   *
   * @param noteId      - noteId
   * @param paragraphId - paragraphId
   * @param message     - JSON with params if user wants to update dynamic form's value
   *                    null, empty string, empty json if user doesn't want to update
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @POST
  @Path("run/{noteId}/{paragraphId}")
  @ZeppelinApi
  public Response runParagraphSynchronously(@PathParam("noteId") String noteId,
                                            @PathParam("paragraphId") String paragraphId,
                                            String message)
      throws IOException, IllegalArgumentException {
    LOG.info("run paragraph synchronously {} {} {}", noteId, paragraphId, message);

    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    Paragraph paragraph = note.getParagraph(paragraphId);
    checkIfParagraphIsNotNull(paragraph);

    Map<String, Object> params = new HashMap<>();
    if (!StringUtils.isEmpty(message)) {
      RunParagraphWithParametersRequest request =
          RunParagraphWithParametersRequest.fromJson(message);
      params = request.getParams();
    }

    if (notebookService.runParagraph(noteId, paragraphId, paragraph.getTitle(),
        paragraph.getText(), params,
        new HashMap<>(), false, true, getServiceContext(), new RestServiceCallback<>())) {
      note = notebookService.getNote(noteId, getServiceContext(), new RestServiceCallback<>());
      Paragraph p = note.getParagraph(paragraphId);
      InterpreterResult result = p.getReturn();
      if (result.code() == InterpreterResult.Code.SUCCESS) {
        return new JsonResponse<>(Status.OK, result).build();
      } else {
        return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR, result).build();
      }
    } else {
      return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR, "Fail to run paragraph").build();
    }
  }

  /**
   * Stop(delete) paragraph job REST API.
   *
   * @param noteId      ID of Note
   * @param paragraphId ID of Paragraph
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @DELETE
  @Path("job/{noteId}/{paragraphId}")
  @ZeppelinApi
  public Response cancelParagraph(@PathParam("noteId") String noteId,
                                  @PathParam("paragraphId") String paragraphId)
      throws IOException, IllegalArgumentException {
    LOG.info("stop paragraph job {} ", noteId);
    notebookService.cancelParagraph(noteId, paragraphId, getServiceContext(),
        new RestServiceCallback<Paragraph>());
    return new JsonResponse<>(Status.OK).build();
  }

  /**
   * Register cron job REST API.
   *
   * @param message - JSON with cron expressions.
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @POST
  @Path("cron/{noteId}")
  @ZeppelinApi
  public Response registerCronJob(@PathParam("noteId") String noteId, String message)
      throws IOException, IllegalArgumentException {
    LOG.info("Register cron job note={} request cron msg={}", noteId, message);

    CronRequest request = CronRequest.fromJson(message);

    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanRun(noteId, "Insufficient privileges you cannot set a cron job for this note");
    checkIfNoteSupportsCron(note);

    if (!CronExpression.isValidExpression(request.getCronString())) {
      return new JsonResponse<>(Status.BAD_REQUEST, "wrong cron expressions.").build();
    }

    Map<String, Object> config = note.getConfig();
    config.put("cron", request.getCronString());
    config.put("releaseresource", request.getReleaseResource());
    note.setConfig(config);
    notebook.refreshCron(note.getId());

    return new JsonResponse<>(Status.OK).build();
  }

  /**
   * Remove cron job REST API.
   *
   * @param noteId ID of Note
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @DELETE
  @Path("cron/{noteId}")
  @ZeppelinApi
  public Response removeCronJob(@PathParam("noteId") String noteId)
      throws IOException, IllegalArgumentException {
    LOG.info("Remove cron job note {}", noteId);

    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserIsOwner(noteId,
        "Insufficient privileges you cannot remove this cron job from this note");
    checkIfNoteSupportsCron(note);

    Map<String, Object> config = note.getConfig();
    config.remove("cron");
    config.remove("releaseresource");
    note.setConfig(config);
    notebook.refreshCron(note.getId());

    return new JsonResponse<>(Status.OK).build();
  }

  /**
   * Get cron job REST API.
   *
   * @param noteId ID of Note
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @GET
  @Path("cron/{noteId}")
  @ZeppelinApi
  public Response getCronJob(@PathParam("noteId") String noteId)
      throws IOException, IllegalArgumentException {
    LOG.info("Get cron job note {}", noteId);

    Note note = notebook.getNote(noteId);
    checkIfNoteIsNotNull(note);
    checkIfUserCanRead(noteId, "Insufficient privileges you cannot get cron information");
    checkIfNoteSupportsCron(note);
    Map<String, Object> response = new HashMap<>();
    response.put("cron", note.getConfig().get("cron"));
    response.put("releaseResource", note.getConfig().get("releaseresource"));

    return new JsonResponse<>(Status.OK, response).build();
  }

  /**
   * Get note jobs for job manager.
   *
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @GET
  @Path("jobmanager/")
  @ZeppelinApi
  public Response getJobListforNote() throws IOException, IllegalArgumentException {
    LOG.info("Get note jobs for job manager");
    List<JobManagerService.NoteJobInfo> noteJobs = jobManagerService
        .getNoteJobInfoByUnixTime(0, getServiceContext(), new RestServiceCallback<>());
    Map<String, Object> response = new HashMap<>();
    response.put("lastResponseUnixTime", System.currentTimeMillis());
    response.put("jobs", noteJobs);
    return new JsonResponse<>(Status.OK, response).build();
  }

  /**
   * Get updated note jobs for job manager
   * <p>
   * Return the `Note` change information within the post unix timestamp.
   *
   * @return JSON with status.OK
   * @throws IOException
   * @throws IllegalArgumentException
   */
  @GET
  @Path("jobmanager/{lastUpdateUnixtime}/")
  @ZeppelinApi
  public Response getUpdatedJobListforNote(@PathParam("lastUpdateUnixtime") long lastUpdateUnixTime)
      throws IOException, IllegalArgumentException {
    LOG.info("Get updated note jobs lastUpdateTime {}", lastUpdateUnixTime);
    List<JobManagerService.NoteJobInfo> noteJobs =
        jobManagerService.getNoteJobInfoByUnixTime(lastUpdateUnixTime, getServiceContext(),
            new RestServiceCallback<>());
    Map<String, Object> response = new HashMap<>();
    response.put("lastResponseUnixTime", System.currentTimeMillis());
    response.put("jobs", noteJobs);
    return new JsonResponse<>(Status.OK, response).build();
  }

  /**
   * Search for a Notes with permissions.
   */
  @GET
  @Path("search")
  @ZeppelinApi
  public Response search(@QueryParam("q") String queryTerm) {
    LOG.info("Searching notes for: {}", queryTerm);
    String principal = securityService.getPrincipal();
    Set<String> roles = securityService.getAssociatedRoles();
    HashSet<String> userAndRoles = new HashSet<>();
    userAndRoles.add(principal);
    userAndRoles.addAll(roles);
    List<Map<String, String>> notesFound = noteSearchService.query(queryTerm);
    for (int i = 0; i < notesFound.size(); i++) {
      String[] ids = notesFound.get(i).get("id").split("/", 2);
      String noteId = ids[0];
      if (!notebookAuthorization.isOwner(noteId, userAndRoles) &&
          !notebookAuthorization.isReader(noteId, userAndRoles) &&
          !notebookAuthorization.isWriter(noteId, userAndRoles) &&
          !notebookAuthorization.isRunner(noteId, userAndRoles)) {
        notesFound.remove(i);
        i--;
      }
    }
    LOG.info("{} notes found", notesFound.size());
    return new JsonResponse<>(Status.OK, notesFound).build();
  }

  private void handleParagraphParams(String message, Note note, Paragraph paragraph)
      throws IOException {
    // handle params if presented
    if (!StringUtils.isEmpty(message)) {
      RunParagraphWithParametersRequest request =
          RunParagraphWithParametersRequest.fromJson(message);
      Map<String, Object> paramsForUpdating = request.getParams();
      if (paramsForUpdating != null) {
        paragraph.settings.getParams().putAll(paramsForUpdating);
        AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
        notebook.saveNote(note, subject);
      }
    }
  }

  private void initParagraph(Paragraph p, NewParagraphRequest request, String user) {
    LOG.info("Init Paragraph for user {}", user);
    checkIfParagraphIsNotNull(p);
    p.setTitle(request.getTitle());
    p.setText(request.getText());
    Map<String, Object> config = request.getConfig();
    if (config != null && !config.isEmpty()) {
      configureParagraph(p, config, user);
    }
  }

  private void configureParagraph(Paragraph p, Map<String, Object> newConfig, String user) {
    LOG.info("Configure Paragraph for user {}", user);
    if (newConfig == null || newConfig.isEmpty()) {
      LOG.warn("{} is trying to update paragraph {} of note {} with empty config",
          user, p.getId(), p.getNote().getId());
      throw new BadRequestException("paragraph config cannot be empty");
    }
    Map<String, Object> origConfig = p.getConfig();
    for (final Map.Entry<String, Object> entry : newConfig.entrySet()) {
      origConfig.put(entry.getKey(), entry.getValue());
    }

    p.setConfig(origConfig);
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: brodriguez
 * Date: 09/10/16
 * Time: 09:56 AM
 */

namespace Despacho\Controller;

use Almacen\Model\DisponibilidadAlmacenEntity;
use Almacen\Model\DisponibilidadProductoEntity;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    protected $userMapper;
    protected $roleMapper;

    public function indexAction()
    {
        $id = $this->params('id');
        $mapper = $this->getPedidoMapper();
        $itemMapper = $this->getItemMapper();

        $pedidosDespacho = $mapper->fetchAllEstatus(array('3'));

        $despachadores = $this->listarDespachadores();
        $listaNombDespachador = $this->extraerNombres($despachadores);

        $request = $this->getRequest();
        if ($request->isPost()) {
            $idpedido = $request->getPost()->get('idpedido');
            $idpedido1 = $request->getPost()->get('idpedido1');
            $idpedido2 = $request->getPost()->get('idpedido2');
            $idpedido3 = $request->getPost()->get('idpedido3');
            $idpedido4 = $request->getPost()->get('idpedido4');
            $panel1 = $request->getPost()->get('panel1');
            $panel2 = $request->getPost()->get('panel2');
            $panel3 = $request->getPost()->get('panel3');
            $panel4 = $request->getPost()->get('panel4');
            $accion = $request->getPost()->get('submit');
            $asignado = false;

            $pedidoMapper = $this->getPedidoMapper();

            $pedido1 = array();
            $items1 = array();
            $pedido2 = array();
            $items2 = array();
            $pedido3 = array();
            $items3 = array();
            $pedido4 = array();
            $items4 = array();

                        if (in_array($accion, $listaNombDespachador)) {
                switch ($accion) {
                    case $listaNombDespachador[0]:
                        if ($panel1 != 'Ocupado') {
                            $idpedido1 = $idpedido;
                            $panel1 = 'Ocupado';
                            $pedido = $mapper->getPedido($idpedido1);
                            $pedido->setEstatus(3);
                            $despachador = $despachadores[0];
                            $idDespachador = $despachador->getId();
                            $nombDespachador = $despachador->getDisplayName();
                            $pedido->setDespachador($idDespachador);
                            $mapper->savePedido($pedido);
                        } else {
                            $despachador = $despachadores[0];
                            $nombDespachador = utf8_encode($despachador->getDisplayName());
                            echo "<script type='text/javascript'> alert('$nombDespachador ya esta atendiendo un pedido.')</script>";
                        }
                        break;
                    case $listaNombDespachador[1]:
                        if ($panel2 != 'Ocupado') {
                            $idpedido2 = $idpedido;
                            $panel2 = 'Ocupado';
                            $asignado = true;
                            $pedido = $mapper->getPedido($idpedido2);
                            $pedido->setEstatus(3);
                            $despachador = $despachadores[1];
                            $idDespachador = $despachador->getId();
                            $pedido->setDespachador($idDespachador);
                            $mapper->savePedido($pedido);
                        } else {
                            $despachador = $despachadores[1];
                            $nombDespachador = utf8_encode($despachador->getDisplayName());
                            echo "<script type='text/javascript'> alert('$nombDespachador ya esta atendiendo un pedido.')</script>";
                        }
                        break;
                    case $listaNombDespachador[2]:
                        if ($panel3 != 'Ocupado') {
                            $idpedido3 = $idpedido;
                            $panel3 = 'Ocupado';
                            $asignado = true;
                            $pedido = $mapper->getPedido($idpedido3);
                            $pedido->setEstatus(3);
                            $despachador = $despachadores[2];
                            $idDespachador = $despachador->getId();
                            $pedido->setDespachador($idDespachador);
                            $mapper->savePedido($pedido);
                        } else {
                            $despachador = $despachadores[2];
                            $nombDespachador = utf8_encode($despachador->getDisplayName());
                            echo "<script type='text/javascript'> alert('$nombDespachador ya esta atendiendo un pedido.')</script>";
                        }
                        break;
                    case $listaNombDespachador[3]:
                        if (($panel4 != 'Ocupado') && !($asignado)) {
                            $idpedido4 = $idpedido;
                            $panel4 = 'Ocupado';
                            $asignado = true;
                            $pedido = $mapper->getPedido($idpedido4);
                            $pedido->setEstatus(3);
                            $despachador = $despachadores[3];
                            $idDespachador = $despachador->getId();
                            $pedido->setDespachador($idDespachador);
                            $mapper->savePedido($pedido);
                        } else {
                            $despachador = $despachadores[3];
                            $nombDespachador = utf8_encode($despachador->getDisplayName());
                            echo "<script type='text/javascript'> alert('$nombDespachador ya esta atendiendo un pedido.')</script>";
                        }
                        break;
                }
            }

            if ($accion === 'Finalizar') {
                $idfinalizado = $request->getPost()->get('idfinalizado');

                if ($idfinalizado === 'panel1') {
                    $this->finalizarPedido($idpedido1);
                    $panel1 = null;
                    $idpedido1 = null;
                }

                if ($idfinalizado === 'panel2') {
                    $this->finalizarPedido($idpedido2);
                    $panel2 = null;
                    $idpedido2 = null;
                }

                if ($idfinalizado === 'panel3') {
                    $this->finalizarPedido($idpedido3);
                    $panel3 = null;
                    $idpedido3 = null;
                }

                if ($idfinalizado === 'panel4') {
                    $this->finalizarPedido($idpedido4);
                    $panel4 = null;
                    $idpedido4 = null;
                }
            }

            if ($accion === 'Eliminar') {
                $idfinalizado = $request->getPost()->get('idfinalizado');

                if ($idfinalizado === 'panel1') {
                    $this->eliminarPedido($idpedido1);
                    $panel1 = null;
                    $idpedido1 = null;
                }

                if ($idfinalizado === 'panel2') {
                    $this->eliminarPedido($idpedido2);
                    $panel2 = null;
                    $idpedido2 = null;
                }

                if ($idfinalizado === 'panel3') {
                    $this->eliminarPedido($idpedido3);
                    $panel3 = null;
                    $idpedido3 = null;
                }

                if ($idfinalizado === 'panel4') {
                    $this->eliminarPedido($idpedido4);
                    $panel4 = null;
                    $idpedido4 = null;
                }
            }

            if ($accion === 'Descartar') {
                $idfinalizado = $request->getPost()->get('idfinalizado');

                if ($idfinalizado === 'panel1') {
                    $this->descartarPedido($idpedido1);
                    $panel1 = null;
                    $idpedido1 = null;
                }

                if ($idfinalizado === 'panel2') {
                    $this->descartarPedido($idpedido2);
                    $panel2 = null;
                    $idpedido2 = null;
                }

                if ($idfinalizado === 'panel3') {
                    $this->descartarPedido($idpedido3);
                    $panel3 = null;
                    $idpedido3 = null;
                }

                if ($idfinalizado === 'panel4') {
                    $this->descartarPedido($idpedido4);
                    $panel4 = null;
                    $idpedido4 = null;
                }
            }

            if (!is_null($idpedido1) && !empty($idpedido1)) {
                $pedido1 = $pedidoMapper->getPedido($idpedido1);
                $items1 = $itemMapper->getItemsPedido($idpedido1);
            }

            if (!is_null($idpedido2) && !empty($idpedido2)) {
                $pedido2 = $pedidoMapper->getPedido($idpedido2);
                $items2 = $itemMapper->getItemsPedido($idpedido2);
            }

            if (!is_null($idpedido3) && !empty($idpedido3)) {
                $pedido3 = $pedidoMapper->getPedido($idpedido3);
                $items3 = $itemMapper->getItemsPedido($idpedido3);
            }

            if (!is_null($idpedido4) && !empty($idpedido4)) {
                $pedido4 = $pedidoMapper->getPedido($idpedido4);
                $items4 = $itemMapper->getItemsPedido($idpedido4);
            }

            return array(
                'pedidos' => $mapper->fetchAllEstatus(array('2')),
                'panel1' => $panel1,
                'idpedido1' => $idpedido1,
                'pedido1' => $pedido1,
                'items1' => $items1,
                'panel2' => $panel2,
                'idpedido2' => $idpedido2,
                'pedido2' => $pedido2,
                'items2' => $items2,
                'panel3' => $panel3,
                'idpedido3' => $idpedido3,
                'pedido3' => $pedido3,
                'items3' => $items3,
                'panel4' => $panel4,
                'idpedido4' => $idpedido4,
                'pedido4' => $pedido4,
                'items4' => $items4,
                'despachadores' => $listaNombDespachador,
                'usuarios' => $despachadores
            );
        } elseif ($pedidosDespacho) {
            $arreglo = $this->extraerId($despachadores);
            foreach ($pedidosDespacho as $despachoPedido) {
                $buscar = $despachoPedido->getDespachador();
                $clave = array_search($buscar,$arreglo);
                $arrayPedidos[$clave] = $despachoPedido->getId();
            }
            $idpedido1 = (!empty($arrayPedidos[0])) ? $arrayPedidos[0] : null;
            $pedido1 = (is_null($idpedido1)) ? null : $mapper->getPedido($idpedido1);
            $panel1 = (is_null($idpedido1)) ? null : 'Ocupado';
            $items1 = (is_null($idpedido1)) ? null : $itemMapper->getItemsPedido($idpedido1);

            $idpedido2 = (!empty($arrayPedidos[1])) ? $arrayPedidos[1] : null;
            $pedido2 = (is_null($idpedido2)) ? null : $mapper->getPedido($idpedido2);
            $panel2 = (is_null($idpedido2)) ? null : 'Ocupado';
            $items2 = (is_null($idpedido2)) ? null : $itemMapper->getItemsPedido($idpedido2);

            $idpedido3 = (!empty($arrayPedidos[2])) ? $arrayPedidos[2] : null;
            $pedido3 = (is_null($idpedido3)) ? null : $mapper->getPedido($idpedido3);
            $panel3 = (is_null($idpedido3)) ? null : 'Ocupado';
            $items3 = (is_null($idpedido3)) ? null : $itemMapper->getItemsPedido($idpedido3);

            $idpedido4 = (!empty($arrayPedidos[3])) ? $arrayPedidos[3] : null;
            $pedido4 = (is_null($idpedido4)) ? null : $mapper->getPedido($idpedido4);
            $panel4 = (is_null($idpedido4)) ? null : 'Ocupado';
            $items4 = (is_null($idpedido4)) ? null : $itemMapper->getItemsPedido($idpedido4);

        }

        return new ViewModel(array(
                'pedidos' => $mapper->fetchAllEstatus(array('2')),
                'panel1' => $panel1,
                'idpedido1' => $idpedido1,
                'pedido1' => $pedido1,
                'items1' => $items1,
                'panel2' => $panel2,
                'idpedido2' => $idpedido2,
                'pedido2' => $pedido2,
                'items2' => $items2,
                'panel3' => $panel3,
                'idpedido3' => $idpedido3,
                'pedido3' => $pedido3,
                'items3' => $items3,
                'panel4' => $panel4,
                'idpedido4' => $idpedido4,
                'pedido4' => $pedido4,
                'items4' => $items4,
                'despachadores' => $listaNombDespachador,
                'usuarios' => $despachadores
            )
        );
    }

    public function getPedidoMapper()
    {
        $sm = $this->getServiceLocator();
        return $sm->get('PedidoMapper');
    }

    public function getItemMapper()
    {
        $sm = $this->getServiceLocator();
        return $sm->get('ItemMapper');
    }

    public function getDisponibilidadMapper()
    {
        $sm = $this->getServiceLocator();
        return $sm->get('DisponibilidadMapper');
    }

    public function getIngresoMapper()
    {
        $sm = $this->getServiceLocator();
        return $sm->get('IngresoMapper');
    }

    public function deleteAction()
    {
        $id = $this->params('id');
        $pedido = $this->getPedidoMapper()->getPedido($id);
        $items = $this->getItemMapper()->getItemsPedido($id);
        if (!$pedido) {
            return $this->redirect()->toRoute('pedido');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            if ($request->getPost()->get('del') == 'Si') {
                $this->getItemMapper()->deleteItems($id);
                $this->getPedidoMapper()->deletePedido($id);
            }

            return $this->redirect()->toRoute('pedido');
        }

        return array(
            'id' => $id,
            'pedido' => $pedido,
            'items' => $items
        );
    }

    public function finalizarPedido($id)
    {
        $itemMapper = $this->getItemMapper();
        $pedidoMapper = $this->getPedidoMapper();

        $pedido = $pedidoMapper->getPedido($id);
        $pedido->setEstatus(4);
        $pedidoMapper->savePedido($pedido);

        $almacen = $pedido->getIdalmacen();
        $ingreso = $this->getIngresoMapper();
        $items = $itemMapper->getItemsPedido($id);
        foreach ($items as $item) {
            $producto = $item->getProducto();

            $disponibilidadAlmacen = $ingreso->existeRegistro($almacen, $producto);

            if ($disponibilidadAlmacen) {
                $cantAnterior = $disponibilidadAlmacen->getCantidad();
                $cantidad = $cantAnterior - $item->getCantidad();
                $disponibilidadAlmacen->setCantidad($cantidad);
                if ($cantidad <= 0 ){
                    $disponibilidadProducto = new DisponibilidadProductoEntity();
                    $disponibilidadProducto->setIdproducto($producto);
                    $disponibilidadProducto->setDisponible(false);
                    $this->getDisponibilidadMapper()->actualizarProducto($disponibilidadProducto);
                }
                $this->getIngresoMapper()->actualizarDisponibilidadAlmacen($disponibilidadAlmacen);
            } else {
                $disponibilidadAlmacen = new DisponibilidadAlmacenEntity();
                $disponibilidadAlmacen->setProducto($producto);
                $disponibilidadAlmacen->setAlmacen($almacen);
                $disponibilidadAlmacen->setCantidad($item->getCantidad());
                if ($item->getCantidad() <= 0 ){
                    $disponibilidadProducto = new DisponibilidadProductoEntity();
                    $disponibilidadProducto->setIdproducto($producto);
                    $disponibilidadProducto->setDisponible(false);
                    $this->getDisponibilidadMapper()->actualizarProducto($disponibilidadProducto);
                }
                $this->getIngresoMapper()->actualizarDisponibilidadAlmacen($disponibilidadAlmacen);
            }

        }
    }

    public function eliminarPedido($id)
    {
        $pedidoMapper = $this->getPedidoMapper();

        $pedido = $pedidoMapper->getPedido($id);
        $pedido->setEstatus(5);
        $pedidoMapper->savePedido($pedido);

    }

    public function descartarPedido($id)
    {
        $pedidoMapper = $this->getPedidoMapper();

        $pedido = $pedidoMapper->getPedido($id);
        $pedido->setEstatus(2);
        $pedido->setDespachador(null);
        $pedidoMapper->savePedido($pedido);

    }

    public function listarDespachadores()
    {
        $userMapper = $this->getUserMapper();
        $users = $userMapper->fetchAll();

        foreach ($users as $user)
        {
            $roles = $this->getRoleMapper()->getRolesById($user->getId());
                $rolId = $roles->getRoleId();

                if ($rolId === 'despachador'){
                    $despachadores[] = $user;
                }

        }
        return $despachadores;
    }

    public function getRoleMapper()
    {
        if (null === $this->roleMapper) {
            $this->roleMapper = $this->getServiceLocator()->get('RoleMapper');
        }
        return $this->roleMapper;
    }

    public function getUserMapper()
    {
        if (null === $this->userMapper) {
            $this->userMapper = $this->getServiceLocator()->get('UsuarioMapper');
        }
        return $this->userMapper;
    }

    public function extraerNombres($despachadores)
    {
        $usuarios = $despachadores;

        foreach ($usuarios as $user)
        {
            $arrayNombres[] = substr($user->getDisplayName(),0,7);
        }

        return $arrayNombres;
    }

    public function extraerId($despachadores)
    {
        $usuarios = $despachadores;

        foreach ($usuarios as $user)
        {
            $arrayId[] = $user->getId();
        }

        return $arrayId;
    }
}


text:
package org.osgl.issues;

import org.junit.Test;
import org.osgl.$;
import org.osgl.TestBase;
import org.osgl.util.S;

import java.security.Key;

public class Gh118 extends TestBase {

    public static class Source {
        String id = S.random();
    }

    public static class Target {
        Key id;
        String sid;
    }

    @Test
    public void test() {
        Source source = new Source();
        Target target = $.copy(source).map("id").to("sid").to(Target.class);
        eq(source.id, target.sid);
        isNull(target.id);
    }

}


text:
<?php

namespace Abby\Knowledgebase;

use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\Router;

class KnowledgebaseServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        // publish views
        $this->publishes([__DIR__.'/resources/views' => base_path('resources/views')], 'views');

        // publish translation files
        $this->publishes([__DIR__.'/resources/lang' => resource_path('lang/vendor/backpack')], 'lang');

        // publish migrations
        $this->publishes([__DIR__.'/database/migrations' => database_path('migrations')], 'migrations');
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function setupRoutes(Router $router)
    {
        $router->group(['namespace' => 'Abby\Knowledgebase\app\Http\Controllers'], function ($router) {
            \Route::group(['prefix' => config('backpack.base.route_prefix', 'admin').'/knowledgebase', 'middleware' => ['web', 'admin'], 'namespace' => 'Admin'], function () {
                \CRUD::resource('space', 'SpaceCrudController');
                \CRUD::resource('article', 'ArticleCrudController')->with(function() {
                    \Route::get('article/{id}/export/word', 'ArticleCrudController@exportWord');
                    \Route::get('article/{id}/export/pdf', 'ArticleCrudController@exportPDF');
                });;
            });
        });
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        // register its dependencies
        $this->app->register(\Cviebrock\EloquentSluggable\ServiceProvider::class);

        $this->setupRoutes($this->app->router);
    }
}


text:
namespace doppia {

// nothing to do here, all declaration are templated methods defined in the header

}


text:
SELECT
*

FROM
view_beban_barang5_paringintimur

UNION ALL


text:
namespace translate {

namespace {

// Constants for UMA statistic collection.
static const char kTranslateCaptureText[] = "Translate.CaptureText";
static const char kTranslateFrameCount[] = "Translate.TranslateFrameCount";
static const char kTranslateSubframeSuccessPercentage[] =
    "Translate.TranslateSubframe.SuccessPercentage";
static const char kTranslateSubframeErrorType[] =
    "Translate.TranslateSubframe.ErrorType";

// A helper function for CombineTextNodesAndMakeCallback() below.
// This is a copy of logic from macos specific RenderWidgetHostViewMac
// that was created in https://chromium-review.googlesource.com/956029
// TODO(dougarnett): Factor this out into a utility class that can be
// shared here and with the original macos copy.
void AddTextNodesToVector(const ui::AXNode* node,
                          std::vector<base::string16>* strings) {
  const ui::AXNodeData& node_data = node->data();

  if (node_data.role == ax::mojom::Role::kStaticText) {
    if (node_data.HasStringAttribute(ax::mojom::StringAttribute::kName)) {
      strings->emplace_back(
          node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
    }
    return;
  }

  for (const auto* child : node->children())
    AddTextNodesToVector(child, strings);
}

using PageContentsCallback = base::OnceCallback<void(const base::string16&)>;
void CombineTextNodesAndMakeCallback(PageContentsCallback callback,
                                     const ui::AXTreeUpdate& update) {
  ui::AXTree tree;
  if (!tree.Unserialize(update)) {
    std::move(callback).Run(base::ASCIIToUTF16(""));
    return;
  }

  std::vector<base::string16> text_node_contents;
  text_node_contents.reserve(update.nodes.size());

  AddTextNodesToVector(tree.root(), &text_node_contents);

  std::move(callback).Run(
      base::JoinString(text_node_contents, base::ASCIIToUTF16("\n")));
}
}  // namespace

PerFrameContentTranslateDriver::PendingRequestStats::PendingRequestStats() =
    default;
PerFrameContentTranslateDriver::PendingRequestStats::~PendingRequestStats() =
    default;

void PerFrameContentTranslateDriver::PendingRequestStats::Clear() {
  frame_request_count = 0;
  main_frame_success = false;
  main_frame_error = TranslateErrors::NONE;
  frame_success_count = 0;
  frame_errors.clear();
}

void PerFrameContentTranslateDriver::PendingRequestStats::Report() {
  UMA_HISTOGRAM_COUNTS_100(kTranslateFrameCount, frame_request_count);
  if (main_frame_success) {
    if (frame_request_count > 1) {
      int success_percentage_as_int =
          (frame_success_count * 100) / frame_request_count;
      UMA_HISTOGRAM_PERCENTAGE(kTranslateSubframeSuccessPercentage,
                               success_percentage_as_int);
    }
    for (TranslateErrors::Type error_type : frame_errors) {
      UMA_HISTOGRAM_ENUMERATION(kTranslateSubframeErrorType, error_type,
                                TranslateErrors::TRANSLATE_ERROR_MAX);
    }
  }
}

PerFrameContentTranslateDriver::PerFrameContentTranslateDriver(
    content::NavigationController* nav_controller,
    language::UrlLanguageHistogram* url_language_histogram)
    : ContentTranslateDriver(nav_controller, url_language_histogram) {}

PerFrameContentTranslateDriver::~PerFrameContentTranslateDriver() = default;

// TranslateDriver methods

void PerFrameContentTranslateDriver::TranslatePage(
    int page_seq_no,
    const std::string& translate_script,
    const std::string& source_lang,
    const std::string& target_lang) {
  if (!IsForCurrentPage(page_seq_no))
    return;

  ReportUserActionDuration(language_determined_time_, base::TimeTicks::Now());
  stats_.Clear();

  web_contents()->ForEachFrame(base::BindRepeating(
      &PerFrameContentTranslateDriver::TranslateFrame, base::Unretained(this),
      translate_script, source_lang, target_lang));
}

void PerFrameContentTranslateDriver::TranslateFrame(
    const std::string& translate_script,
    const std::string& source_lang,
    const std::string& target_lang,
    content::RenderFrameHost* render_frame_host) {
  if (render_frame_host->IsFrameDisplayNone() ||
      !translate::IsTranslatableURL(render_frame_host->GetLastCommittedURL())) {
    return;
  }

  bool is_main_frame = (!render_frame_host->GetParent());
  mojo::AssociatedRemote<mojom::TranslateAgent> frame_agent;
  render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface(
      &frame_agent);
  frame_agent->TranslateFrame(
      translate_script, source_lang, target_lang,
      base::BindOnce(&PerFrameContentTranslateDriver::OnFrameTranslated,
                     weak_pointer_factory_.GetWeakPtr(), is_main_frame,
                     std::move(frame_agent)));
  stats_.frame_request_count++;
  stats_.pending_request_count++;
}

void PerFrameContentTranslateDriver::RevertTranslation(int page_seq_no) {
  if (!IsForCurrentPage(page_seq_no))
    return;

  web_contents()->ForEachFrame(base::BindRepeating(
      &PerFrameContentTranslateDriver::RevertFrame, base::Unretained(this)));
}

void PerFrameContentTranslateDriver::RevertFrame(
    content::RenderFrameHost* render_frame_host) {
  if (render_frame_host->IsFrameDisplayNone() ||
      !translate::IsTranslatableURL(render_frame_host->GetLastCommittedURL())) {
    return;
  }

    mojo::AssociatedRemote<mojom::TranslateAgent> frame_agent;
    render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface(
        &frame_agent);
    frame_agent->RevertTranslation();
}

// content::WebContentsObserver methods
void PerFrameContentTranslateDriver::NavigationEntryCommitted(
    const content::LoadCommittedDetails& load_details) {
  // Check whether this is a reload: When doing a page reload, the
  // TranslateLanguageDetermined IPC is not sent so the translation needs to be
  // explicitly initiated.

  content::NavigationEntry* entry =
      web_contents()->GetController().GetLastCommittedEntry();
  if (!entry) {
    NOTREACHED();
    return;
  }

  // If the navigation happened while offline don't show the translate
  // bar since there will be nothing to translate.
  if (load_details.http_status_code == 0 ||
      load_details.http_status_code == net::HTTP_INTERNAL_SERVER_ERROR) {
    return;
  }

  if (!load_details.is_main_frame &&
      translate_manager()->GetLanguageState().translation_declined()) {
    // Some sites (such as Google map) may trigger sub-frame navigations
    // when the user interacts with the page.  We don't want to show a new
    // infobar if the user already dismissed one in that case.
    return;
  }

  // If not a reload, return.
  if (!ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
                                    ui::PAGE_TRANSITION_RELOAD) &&
      load_details.type != content::NAVIGATION_TYPE_SAME_PAGE) {
    return;
  }

  if (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
    // Workaround for http://crbug.com/653051: back navigation sometimes have
    // the reload core type. Once http://crbug.com/669008 got resolved, we
    // could revisit here for a thorough solution.
    //
    // This means that the new translation won't be started when the page
    // is restored from back-forward cache, which is the right thing to do.
    // TODO(crbug.com/1001087): Ensure that it stays disabled for
    // back-forward navigations even when bug above is fixed.
    return;
  }

  if (!translate_manager()->GetLanguageState().page_needs_translation())
    return;

  // Note that we delay it as the ordering of the processing of this callback
  // by WebContentsObservers is undefined and might result in the current
  // infobars being removed. Since the translation initiation process might add
  // an infobar, it must be done after that.
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::BindOnce(
          &PerFrameContentTranslateDriver::InitiateTranslation,
          weak_pointer_factory_.GetWeakPtr(),
          translate_manager()->GetLanguageState().original_language(), 0));
}

void PerFrameContentTranslateDriver::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  if (!navigation_handle->HasCommitted())
    return;

  // Let the LanguageState clear its state.
  const bool reload =
      navigation_handle->GetReloadType() != content::ReloadType::NONE ||
      navigation_handle->IsSameDocument();

  const base::Optional<url::Origin>& initiator_origin =
      navigation_handle->GetInitiatorOrigin();

  bool navigation_from_google =
      initiator_origin.has_value() &&
      (google_util::IsGoogleDomainUrl(initiator_origin->GetURL(),
                                      google_util::DISALLOW_SUBDOMAIN,
                                      google_util::ALLOW_NON_STANDARD_PORTS) ||
       IsAutoHrefTranslateAllOriginsEnabled());

  translate_manager()->GetLanguageState().DidNavigate(
      navigation_handle->IsSameDocument(), navigation_handle->IsInMainFrame(),
      reload, navigation_handle->GetHrefTranslate(), navigation_from_google);
}

void PerFrameContentTranslateDriver::DOMContentLoaded(
    content::RenderFrameHost* render_frame_host) {
  if (render_frame_host->GetParent()) {
    // Nothing to do for sub frames here.
    return;
  }

  // Main frame loaded, set new sequence number.
  current_seq_no_ = (current_seq_no_ % 100000) + 1;
  translate_manager()->set_current_seq_no(current_seq_no_);
}

void PerFrameContentTranslateDriver::DocumentOnLoadCompletedInMainFrame() {
  if (translate::IsTranslatableURL(web_contents()->GetURL()))
    StartLanguageDetection();
}

void PerFrameContentTranslateDriver::StartLanguageDetection() {
  // Get page contents (via snapshot of a11y tree) for language determination.
  // This will include subframe content for any subframes loaded at this point.
  base::TimeTicks capture_begin_time = base::TimeTicks::Now();
  awaiting_contents_ = true;
  web_contents()->RequestAXTreeSnapshot(
      base::BindOnce(
          CombineTextNodesAndMakeCallback,
          base::BindOnce(&PerFrameContentTranslateDriver::OnPageContents,
                         weak_pointer_factory_.GetWeakPtr(),
                         capture_begin_time)),
      ui::AXMode::kWebContents);

  // Kick off language detection by first requesting web language details.
  details_ = LanguageDetectionDetails();
  mojo::AssociatedRemote<mojom::TranslateAgent> frame_agent;
  web_contents()->GetMainFrame()->GetRemoteAssociatedInterfaces()->GetInterface(
      &frame_agent);
  frame_agent->GetWebLanguageDetectionDetails(base::BindOnce(
      &PerFrameContentTranslateDriver::OnWebLanguageDetectionDetails,
      weak_pointer_factory_.GetWeakPtr(), std::move(frame_agent)));
}

void PerFrameContentTranslateDriver::OnPageLanguageDetermined(
    const LanguageDetectionDetails& details,
    bool page_needs_translation) {
  language_determined_time_ = base::TimeTicks::Now();

  // If we have a language histogram (i.e. we're not in incognito), update it
  // with the detected language of every page visited.
  if (language_histogram() && details.is_cld_reliable)
    language_histogram()->OnPageVisited(details.cld_language);

  if (translate_manager() && web_contents()) {
    translate_manager()->GetLanguageState().LanguageDetermined(
        details.adopted_language, page_needs_translation);
    translate_manager()->InitiateTranslation(details.adopted_language);
  }

  for (auto& observer : observer_list())
    observer.OnLanguageDetermined(details);
}

void PerFrameContentTranslateDriver::OnWebLanguageDetectionDetails(
    mojo::AssociatedRemote<mojom::TranslateAgent> translate_agent,
    const std::string& content_language,
    const std::string& html_lang,
    const GURL& url,
    bool has_notranslate_meta) {
  details_.content_language = content_language;
  details_.html_root_language = html_lang;
  details_.url = url;
  details_.has_notranslate = has_notranslate_meta;

  if (!awaiting_contents_)
    ComputeActualPageLanguage();
}

void PerFrameContentTranslateDriver::OnPageContents(
    base::TimeTicks capture_begin_time,
    const base::string16& contents) {
  details_.contents = contents;
  UMA_HISTOGRAM_TIMES(kTranslateCaptureText,
                      base::TimeTicks::Now() - capture_begin_time);

  // Run language detection of contents in a sandboxed utility process.
  mojo::Remote<language_detection::mojom::LanguageDetectionService> service =
      language_detection::LaunchLanguageDetectionService();
  service->DetermineLanguage(
      contents,
      base::BindOnce(&PerFrameContentTranslateDriver::OnPageContentsLanguage,
                     weak_pointer_factory_.GetWeakPtr(), std::move(service)));
}

void PerFrameContentTranslateDriver::OnPageContentsLanguage(
    mojo::Remote<language_detection::mojom::LanguageDetectionService>
        service_handle,
    const std::string& contents_language,
    bool is_contents_language_reliable) {
  awaiting_contents_ = false;
  details_.cld_language = contents_language;
  details_.is_cld_reliable = is_contents_language_reliable;

  if (!details_.url.is_empty())
    ComputeActualPageLanguage();
}

void PerFrameContentTranslateDriver::ComputeActualPageLanguage() {
  // TODO(crbug.com/1063520): Move this language detection to a sandboxed
  // utility process.
  std::string language = DeterminePageLanguage(
      details_.content_language, details_.html_root_language,
      details_.cld_language, details_.is_cld_reliable);

  if (!language.empty()) {
    details_.time = base::Time::Now();
    details_.adopted_language = language;

    OnPageLanguageDetermined(details_,
                             !details_.has_notranslate && !language.empty());
  }
  details_ = LanguageDetectionDetails();
}

void PerFrameContentTranslateDriver::OnFrameTranslated(
    bool is_main_frame,
    mojo::AssociatedRemote<mojom::TranslateAgent> translate_agent,
    bool cancelled,
    const std::string& original_lang,
    const std::string& translated_lang,
    TranslateErrors::Type error_type) {
  if (cancelled)
    return;

  if (error_type == TranslateErrors::NONE) {
    stats_.frame_success_count++;
    if (is_main_frame) {
      stats_.main_frame_success = true;
    }
  } else {
    stats_.frame_errors.push_back(error_type);
    if (is_main_frame) {
      stats_.main_frame_error = error_type;
    }
  }

  if (--stats_.pending_request_count == 0) {
    OnPageTranslated(cancelled, original_lang, translated_lang,
                     stats_.main_frame_error);
    stats_.Report();
  }
}

bool PerFrameContentTranslateDriver::IsForCurrentPage(int page_seq_no) {
  return page_seq_no > 0 && page_seq_no == current_seq_no_;
}

}  // namespace translate


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  	<display-name>TagsUI</display-name>
  	<jsp-config>
    <taglib>
      <taglib-uri>http://www.edunola.com.ar/</taglib-uri>
      <taglib-location>/WEB-INF/taglib.tld</taglib-location>
    </taglib>
  	</jsp-config>

<!--  	<env-entry> -->
<!-- 		<env-entry-name>enola/ServerDefinition</env-entry-name> -->
<!-- 		<env-entry-type>java.lang.String</env-entry-type> -->
<!-- 		<env-entry-value>content/ServerDefinition-2015-04-21.properties</env-entry-value>		 -->
<!-- 	</env-entry> -->

  	<display-name>JavaServerFaces</display-name>

	<!-- Change to "Production" when you are ready to deploy -->
	<context-param>
		<param-name>javax.faces.PROJECT_STAGE</param-name>
		<param-value>Development</param-value>
	</context-param>
<!-- 	<context-param> -->
<!-- 	    <param-name>facelets.LIBRARIES</param-name> -->
<!-- 	    <param-value>/META-INF/jsf.taglib.xml</param-value> -->
<!-- 	 </context-param> -->

	<!-- JSF mapping -->
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map these files with JSF -->
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.jsf</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.faces</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>

</web-app>


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 299908 $ -->

<refentry xml:id="reflectionextension.export" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>ReflectionExtension::export</refname>
  <refpurpose>Export</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <modifier>static</modifier> <type>string</type><methodname>ReflectionExtension::export</methodname>
   <methodparam><type>string</type><parameter>name</parameter></methodparam>
   <methodparam choice="opt"><type>string</type><parameter>return</parameter><initializer>false</initializer></methodparam>
  </methodsynopsis>
  <para>
   Exports a reflected extension. The output format of this function is
   the same as the CLI argument <literal>--re [extension]</literal>.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>name</parameter></term>
     <listitem>
      <para>
       &reflection.export.param.name;
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>return</parameter></term>
     <listitem>
      <para>
       &reflection.export.param.return;
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   &reflection.export.return;
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><methodname>ReflectionExtension::info</methodname></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
struct DabValue;

typedef std::function<DabValue(DabValue, std::vector<DabValue>)> dab_function_reg_t;

struct DabRuntimeError : public std::runtime_error
{
    DabRuntimeError(std::string message) : std::runtime_error("DabRuntimeError"), message(message)
    {
    }
    virtual char const *what() const throw()
    {
        return message.c_str();
    }

  private:
    std::string message;
};

struct DabCastError : public DabRuntimeError
{
    DabCastError(const char *message) : DabRuntimeError(message)
    {
    }
};

struct DabFunctionReflection
{
    std::vector<std::string> arg_names;
    std::vector<dab_class_t> arg_klasses;
    dab_class_t              ret_klass;
};

struct DabFunction
{
    bool               regular   = true;
    dab_function_reg_t extra_reg = nullptr;

    uint64_t    address = 0;
    std::string name;

    DabFunctionReflection reflection;

    uint64_t source_ring = 0;
};

enum
{
    TYPE_INVALID = 0,
    TYPE_FIXNUM,
    TYPE_BOOLEAN,
    TYPE_NIL,
    TYPE_CLASS,
    TYPE_OBJECT,
    TYPE_ARRAY,
    TYPE_UINT8,
    TYPE_UINT16,
    TYPE_UINT32,
    TYPE_UINT64,
    TYPE_INT8,
    TYPE_INT16,
    TYPE_INT32,
    TYPE_INT64,
    TYPE_METHOD,
    TYPE_INTPTR,
    TYPE_BYTEBUFFER,
    TYPE_LITERALSTRING,
    TYPE_DYNAMICSTRING,
    TYPE_FLOAT,
};

#include "../cshared/classes.h"

enum
{
    REFLECT_METHOD_ARGUMENTS               = 0,
    REFLECT_METHOD_ARGUMENT_NAMES          = 1,
    REFLECT_INSTANCE_METHOD_ARGUMENT_TYPES = 2,
    REFLECT_INSTANCE_METHOD_ARGUMENT_NAMES = 3,
};

struct DabVM;
struct DabValue;

struct DabClass
{
    std::string name;
    dab_class_t index;
    bool        builtin = false;
    std::map<dab_symbol_t, DabFunction> functions;
    std::map<dab_symbol_t, DabFunction> static_functions;
    dab_class_t superclass_index = CLASS_OBJECT;

    const DabFunction &get_instance_function(dab_symbol_t symbol) const;

    const DabFunction &get_static_function(dab_symbol_t symbol) const;

    void _add_reg_function(bool is_static, const std::string &func_name, dab_function_reg_t body);

    void add_static_reg_function(const std::string &func_name, dab_function_reg_t body)
    {
        _add_reg_function(true, func_name, body);
    }

    void add_reg_function(const std::string &func_name, dab_function_reg_t body)
    {
        _add_reg_function(false, func_name, body);
    }

    bool is_subclass_of(const DabClass &klass) const;

  private:
    const DabFunction &_get_function(bool _static, dab_symbol_t symbol,
                                     const DabClass &base_class) const;
};

enum
{
    COUNTER_OBJECT = 1,
    COUNTER_PROXY  = 2,
    COUNTER_VALUE  = 3,
};

template <int type>
struct DabMemoryCounter
{
    DabMemoryCounter()
    {
        _counter()++;
    }
    ~DabMemoryCounter()
    {
        _counter()--;
    }
    static size_t counter()
    {
        return _counter();
    }

  private:
    static size_t &_counter()
    {
        static size_t counter = 0;
        return counter;
    }
};

struct DabBaseObject;

struct DabObjectProxy
{
    DabMemoryCounter<COUNTER_PROXY> _counter;

    DabBaseObject *object;
    size_t         count_strong;
    bool           destroying = false;

    void retain(DabValue *value);
    void release(DabValue *value);
    void destroy(DabValue *value);
};

struct DabValueData
{
    int type = TYPE_INVALID;

    union {
        uint64_t _initialize = 0;

        int64_t         fixnum;
        uint8_t         num_uint8;
        uint16_t        num_uint16;
        uint32_t        num_uint32;
        uint64_t        num_uint64;
        int8_t          num_int8;
        int16_t         num_int16;
        int32_t         num_int32;
        int64_t         num_int64;
        bool            boolean;
        DabObjectProxy *object;
        void *          intptr;
        float           floatval;
    };
};

struct DabValue
{
    DabMemoryCounter<COUNTER_VALUE> _counter;
    DabValueData                    data;

    void dump(FILE *file = nullptr) const;

    dab_class_t class_index() const;
    std::string class_name() const;
    DabClass &  get_class() const;

    void print(FILE *out, bool debug = false) const;

    bool truthy() const;

    DabValue _get_instvar(dab_symbol_t symbol);
    DabValue get_instvar(dab_symbol_t symbol);

    void set_instvar(dab_symbol_t symbol, const DabValue &value);

    void set_data(const DabValueData &other_data);

    bool is_a(const DabClass &klass) const;

    std::string print_value(bool debug = false) const;

    DabValue()
    {
    }
    DabValue(std::nullptr_t)
    {
        data.type = TYPE_NIL;
    }
    DabValue(const std::string &value) : DabValue(CLASS_DYNAMICSTRING, value.c_str())
    {
    }
    DabValue(const DabClass &klass)
    {
        data.type   = TYPE_CLASS;
        data.fixnum = klass.index;
    }
    DabValue(uint64_t value)
    {
        data.type   = TYPE_FIXNUM;
        data.fixnum = value;
    }
    DabValue(bool value)
    {
        data.type    = TYPE_BOOLEAN;
        data.boolean = value;
    }
    DabValue(size_t class_index, bool value)
    {
        assert(class_index == CLASS_BOOLEAN);
        data.type    = TYPE_BOOLEAN;
        data.boolean = value;
    }
    DabValue(size_t class_index, uint8_t value)
    {
        assert(class_index == CLASS_UINT8);
        data.type      = TYPE_UINT8;
        data.num_uint8 = value;
    }
    DabValue(size_t class_index, uint16_t value)
    {
        assert(class_index == CLASS_UINT16);
        data.type       = TYPE_UINT16;
        data.num_uint16 = value;
    }
    DabValue(size_t class_index, uint32_t value)
    {
        assert(class_index == CLASS_UINT32);
        data.type       = TYPE_UINT32;
        data.num_uint32 = value;
    }
    DabValue(size_t class_index, int64_t value)
    {
        assert(class_index == CLASS_INT64);
        data.type      = TYPE_INT64;
        data.num_int64 = value;
    }
    DabValue(size_t class_index, uint64_t value)
    {
        if (class_index == CLASS_UINT64)
        {
            data.type       = TYPE_UINT64;
            data.num_uint64 = value;
        }
        else if (class_index == CLASS_FIXNUM)
        {
            data.type   = TYPE_FIXNUM;
            data.fixnum = value;
        }
        else
        {
            assert(false);
        }
    }
    DabValue(size_t class_index, int8_t value)
    {
        assert(class_index == CLASS_INT8);
        data.type     = TYPE_INT8;
        data.num_int8 = value;
    }
    DabValue(size_t class_index, int16_t value)
    {
        assert(class_index == CLASS_INT16);
        data.type      = TYPE_INT16;
        data.num_int16 = value;
    }
    DabValue(size_t class_index, int32_t value)
    {
        assert(class_index == CLASS_INT32);
        data.type      = TYPE_INT32;
        data.num_int32 = value;
    }
    DabValue(size_t class_index, void *value)
    {
        assert(class_index == CLASS_INTPTR);
        data.type   = TYPE_INTPTR;
        data.intptr = value;
    }
    DabValue(size_t class_index, float value)
    {
        assert(class_index == CLASS_FLOAT);
        data.type     = TYPE_FLOAT;
        data.floatval = value;
    }
    DabValue(size_t class_index, const char *value)
    {
        data.type = TYPE_NIL;
        assert(class_index == CLASS_DYNAMICSTRING);
        auto obj = allocate_dynstr(value);
        std::swap(data, obj.data);
    }

    DabValue(const DabValue &other);
    DabValue &operator=(const DabValue &other);

    ~DabValue();

    static DabValue allocate_dynstr(const char *str);

    std::vector<DabValue> &array() const;
    std::vector<uint8_t> & bytebuffer() const;

    std::string literal_string() const;
    std::string dynamic_string() const;

    std::string string() const;

    DabValue create_instance() const;

    size_t use_count() const;
    void   retain();
    void   release();

    bool is_object() const
    {
        return data.type == TYPE_OBJECT || data.type == TYPE_ARRAY ||
               data.type == TYPE_BYTEBUFFER || data.type == TYPE_LITERALSTRING ||
               data.type == TYPE_DYNAMICSTRING;
    }
};

struct DabBaseObject
{
    DabMemoryCounter<COUNTER_OBJECT> _counter;
    uint64_t                         klass;
    virtual ~DabBaseObject()
    {
    }
};

struct DabObject : public DabBaseObject
{
    std::map<dab_symbol_t, DabValue> instvars;
};

struct DabArray : public DabBaseObject
{
    std::vector<DabValue> array;
};

struct DabByteBuffer : public DabBaseObject
{
    std::vector<uint8_t> bytebuffer;
};

struct DabLiteralString : public DabBaseObject
{
    const char *pointer = nullptr;
    uint64_t    length  = 0;
};

struct DabDynamicString : public DabBaseObject
{
    std::string value;
};

struct Coverage
{
    void add_file(uint64_t hash, const std::string &filename);
    void add_line(uint64_t hash, uint64_t line);
    void dump(FILE *out = stdout) const;

  private:
    std::map<uint64_t, std::string> files;
    std::map<uint64_t, std::map<uint64_t, uint64_t>> lines;
};

struct DabVMReset
{
    ~DabVMReset();
};

struct DabRunOptions
{
    std::vector<FILE *> inputs = {stdin};

    bool close_file      = false;
    bool autorun         = true;
    bool extract         = false;
    bool raw             = false;
    bool autorelease     = true;
    bool verbose         = false;
    bool with_attributes = false;
    bool leaktest        = false;
    bool bare            = false;

    bool coverage_testing = false;

    FILE *output       = stdout;
    bool  close_output = false;

    std::string extract_part;

    std::string entry = "main";

    FILE *console       = stderr;
    bool  close_console = false;

    void parse(const std::vector<std::string> &args);
};

struct DabStackFrame
{
    uint64_t       prev_ip;
    DabValue       self;
    uint64_t       block_addr;
    DabValue       capture;
    dab_register_t out_reg;
    DabValue       retvalue;

    std::vector<DabValue> args;
};

struct DabSymbol
{
    std::string value;
    uint64_t    source_ring;
};

struct DabVM
{
    DabRunOptions options;

    uint64_t last_ring_offset;

    bool       shutdown = false;
    DabVMReset reset;
    Coverage   coverage;

    Stream instructions;
    std::map<dab_symbol_t, DabFunction> functions;

    std::vector<DabSymbol> symbols;

    std::map<dab_class_t, DabClass> classes;

    std::set<uint64_t> breakpoints;

    std::vector<DabValue>              _registers;
    std::vector<std::vector<DabValue>> _register_stack;

    std::vector<DabStackFrame> stackframes;

    std::vector<BinSection> sections;

    DabClass &get_class(dab_class_t index);
    void predefine_default_classes();
    void define_default_classes();
    void define_defaults();

    DabVM();
    DabVM(const DabVM &) = delete;
    DabVM &operator=(const DabVM &) = delete;
    ~DabVM();

    std::string get_symbol(dab_symbol_t index) const;

    dab_symbol_t get_symbol_index(const std::string &string) const
    {
        for (size_t i = 0; i < symbols.size(); i++)
        {
            auto &symbol = symbols[i];
            if (symbol.value == string)
            {
                return (dab_symbol_t)i;
            }
        }
        throw DabRuntimeError("Unknown symbol: " + string);
    }

    void kernel_print(dab_register_t out_reg, std::vector<dab_register_t> reglist);

    bool pop_frame(bool regular);

    void push_new_frame(const DabValue &self, uint64_t block_addr, dab_register_t out_reg,
                        const DabValue &capture, std::vector<dab_register_t> reglist = {});

    void _dump(const char *name, const std::vector<DabValue> &data, FILE *output);

    uint64_t ip() const;

    int run(std::vector<Stream> &inputs);

    void load_newformat(Stream &input);

    DabStackFrame *current_frame();

    bool has_arg(int arg_index);
    DabValue &get_arg(int arg_index);

    DabValue &get_retval();

    DabValue &get_self();

    uint64_t get_prev_ip();

    uint64_t get_block_addr();
    DabValue get_block_capture();

    dab_register_t get_out_reg();

    int number_of_args();

    void call(dab_register_t out_reg, dab_symbol_t symbol, int n_args, dab_symbol_t block_symbol,
              const DabValue &capture, std::vector<dab_register_t> reglist = {});

    void _call_function(bool use_self, dab_register_t out_reg, const DabValue &self,
                        const DabFunction &fun, int n_args, void *blockaddress,
                        const DabValue &capture, std::vector<dab_register_t> reglist = {},
                        DabValue *return_value = nullptr, size_t stack_pos = 0);

    void execute_debug(Stream &input);

    void execute(Stream &input);

    bool execute_single(Stream &input);

    DabValue cast(const DabValue &value, dab_class_t klass_index);

    void add_class(const std::string &name, dab_class_t index, dab_class_t parent_index);

    void kernelcall(dab_register_t out_reg, int call, std::vector<dab_register_t> reglist);

    DabFunction &add_function(uint64_t address, const std::string &name, uint16_t class_index);

    void read_classes(Stream &input, uint64_t classes_address, uint64_t classes_length);

    void read_functions(Stream &input, uint64_t func_address, uint64_t func_length,
                        uint64_t offset);
    void read_functions_ex(Stream &input, uint64_t func_address, uint64_t func_length);

    void read_coverage_files(Stream &stream, uint64_t address, uint64_t length);

    void read_symbols(Stream &input, uint64_t symb_address, uint64_t symb_length, uint64_t offset);

    void instcall(const DabValue &recv, dab_symbol_t symbol, size_t n_args,
                  dab_symbol_t block_symbol = DAB_SYMBOL_NIL, const DabValue &capture = nullptr,
                  dab_register_t              outreg  = dab_register_t::nilreg(),
                  std::vector<dab_register_t> reglist = {}, DabValue *return_value = nullptr,
                  size_t stack_pos = 0);

    DabClass &define_builtin_class(const std::string &name, dab_class_t class_index,
                                   dab_class_t superclass_index = CLASS_OBJECT);

    void get_instvar(dab_symbol_t symbol, dab_register_t out_reg);
    void set_instvar(dab_symbol_t symbol, const DabValue &value);

    void extract(const std::string &name);

    DabValue merge_arrays(const DabValue &array0, const DabValue &array1);

    void reflect(size_t reflection_type, const DabValue &symbol, dab_register_t reg, bool has_class,
                 uint16_t class_index);
    void reflect_instance_method(size_t reflection_type, const DabValue &symbol, dab_register_t reg,
                                 bool has_class, uint16_t class_index);
    void reflect_method_arguments(size_t reflection_type, const DabValue &symbol,
                                  dab_register_t reg);

    void _reflect(const DabFunction &function, dab_register_t reg, bool output_names);

    DabValue register_get(dab_register_t reg_index);
    void register_set(dab_register_t reg_index, const DabValue &value);

    bool run_leaktest(FILE *output);

    dab_symbol_t get_or_create_symbol_index(const std::string &string);

    DabValue cinstcall(DabValue self, const std::string &name, std::vector<DabValue> args = {});

    void define_default_classes_int();

    void dump_vm(FILE *out);
};

struct DabVM_debug
{
    DabVM &vm;
    DabVM_debug(DabVM &vm) : vm(vm)
    {
    }
    void print_registers();
    void print_classes();
    void print_functions();
    void print_constants();
    void print_stack();
    void print_code(bool current_only);
    void print_ssa_registers();

  private:
    typedef std::vector<std::pair<uint64_t, std::string>> disasm_map_t;
    disasm_map_t disasm;
    bool         has_disasm = false;
    void         prepare_disasm();
};

#if defined(__GNUC__) && !defined(__clang__)
#define $VM __GLOBAL_VM
#endif

extern DabVM *$VM;

void setup_handlers();


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- res/layout/activity_main.xml -->
<merge xmlns:android="http://schemas.android.com/apk/res/android">
  <fragment
      android:name="info.evelio.fragments.HelloFragment"
      android:id="@+id/hello_fragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</merge>


text:
using System.Collections.Generic;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;

namespace osu.Game.Rulesets.Mania.UI
{
    /// <summary>
    /// Ensures that only the most recent <see cref="HitObject"/> is hittable, affectionately known as "note lock".
    /// </summary>
    public class OrderedHitPolicy
    {
        private readonly HitObjectContainer hitObjectContainer;

        public OrderedHitPolicy(HitObjectContainer hitObjectContainer)
        {
            this.hitObjectContainer = hitObjectContainer;
        }

        /// <summary>
        /// Determines whether a <see cref="DrawableHitObject"/> can be hit at a point in time.
        /// </summary>
        /// <remarks>
        /// Only the most recent <see cref="DrawableHitObject"/> can be hit, a previous hitobject's window cannot extend past the next one.
        /// </remarks>
        /// <param name="hitObject">The <see cref="DrawableHitObject"/> to check.</param>
        /// <param name="time">The time to check.</param>
        /// <returns>Whether <paramref name="hitObject"/> can be hit at the given <paramref name="time"/>.</returns>
        public bool IsHittable(DrawableHitObject hitObject, double time)
        {
            var nextObject = hitObjectContainer.AliveObjects.GetNext(hitObject);
            return nextObject == null || time < nextObject.HitObject.StartTime;
        }

        /// <summary>
        /// Handles a <see cref="HitObject"/> being hit to potentially miss all earlier <see cref="HitObject"/>s.
        /// </summary>
        /// <param name="hitObject">The <see cref="HitObject"/> that was hit.</param>
        public void HandleHit(DrawableHitObject hitObject)
        {
            foreach (var obj in enumerateHitObjectsUpTo(hitObject.HitObject.StartTime))
            {
                if (obj.Judged)
                    continue;

                ((DrawableManiaHitObject)obj).MissForcefully();
            }
        }

        private IEnumerable<DrawableHitObject> enumerateHitObjectsUpTo(double targetTime)
        {
            foreach (var obj in hitObjectContainer.AliveObjects)
            {
                if (obj.HitObject.GetEndTime() >= targetTime)
                    yield break;

                yield return obj;

                foreach (var nestedObj in obj.NestedHitObjects)
                {
                    if (nestedObj.HitObject.GetEndTime() >= targetTime)
                        break;

                    yield return nestedObj;
                }
            }
        }
    }
}