jiahuimbzuai/CoQuIR huggingface dataset:
// getAuthenticatedBasket [go]
func getAuthenticatedBasket(w http.ResponseWriter, r *http.Request, ps httprouter.Params) (string, Basket) {
	name := ps.ByName("basket")
	if !validBasketName.MatchString(name) {
		http.Error(w, "invalid basket name; the name does not match pattern: "+validBasketName.String(), http.StatusBadRequest)
	} else if basket := basketsDb.Get(name); basket != nil {
		// maybe custom header, e.g. basket_key, basket_token
		if token := r.Header.Get("Authorization"); basket.Authorize(token) || token == serverConfig.MasterToken {
			return name, basket
		}
		w.WriteHeader(http.StatusUnauthorized)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}

	return "", nil
}
// getAuthenticatedBasket [go]
func getAuthenticatedBasket(w http.ResponseWriter, r *http.Request, ps httprouter.Params) (string, Basket) {
	name := ps.ByName("basket")
	if !validBasketName.MatchString(name) {
		http.Error(w, "invalid basket name; ["+name+"] does not match pattern: "+validBasketName.String(), http.StatusBadRequest)
	} else if basket := basketsDb.Get(name); basket != nil {
		// maybe custom header, e.g. basket_key, basket_token
		if token := r.Header.Get("Authorization"); basket.Authorize(token) || token == serverConfig.MasterToken {
			return name, basket
		}
		w.WriteHeader(http.StatusUnauthorized)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}

	return "", nil
}
// TestCreateBasket_InvalidName [go]
func TestCreateBasket_InvalidName(t *testing.T) {
	basket := ">>>"

	r, err := http.NewRequest("POST", "http://localhost:55555/api/baskets/"+basket, strings.NewReader(""))
	if assert.NoError(t, err) {
		w := httptest.NewRecorder()
		ps := append(make(httprouter.Params, 0), httprouter.Param{Key: "basket", Value: basket})
		CreateBasket(w, r, ps)

		// validate response: 400 - Bad Request
		assert.Equal(t, 400, w.Code, "wrong HTTP result code")
		assert.Equal(t, "invalid basket name; the name does not match pattern: "+validBasketName.String()+"\n", w.Body.String(),
			"wrong error message")
		// validate database
		assert.Nil(t, basketsDb.Get(basket), "basket '%v' should not be created", basket)
	}
}
// TestCreateBasket_InvalidName [go]
func TestCreateBasket_InvalidName(t *testing.T) {
	basket := ">>>"

	r, err := http.NewRequest("POST", "http://localhost:55555/api/baskets/"+basket, strings.NewReader(""))
	if assert.NoError(t, err) {
		w := httptest.NewRecorder()
		ps := append(make(httprouter.Params, 0), httprouter.Param{Key: "basket", Value: basket})
		CreateBasket(w, r, ps)

		// validate response: 400 - Bad Request
		assert.Equal(t, 400, w.Code, "wrong HTTP result code")
		assert.Equal(t, "invalid basket name; ["+basket+"] does not match pattern: "+validBasketName.String()+"\n", w.Body.String(),
			"wrong error message")
		// validate database
		assert.Nil(t, basketsDb.Get(basket), "basket '%v' should not be created", basket)
	}
}
//  [go]
	return func(w http.ResponseWriter, r *http.Request) {
		playlistId := utils.ParamString(r, ":playlistId")
		tracksRepo := ds.Playlist(r.Context()).Tracks(playlistId)
		var payload addTracksPayload
		err := json.NewDecoder(r.Body).Decode(&payload)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		err = tracksRepo.Add(payload.Ids)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		// Must return an object with an ID, to satisfy ReactAdmin `create` call
		_, err = fmt.Fprintf(w, `{"id":"%s"}`, html.EscapeString(playlistId))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
//  [go]
	return func(w http.ResponseWriter, r *http.Request) {
		playlistId := utils.ParamString(r, ":playlistId")
		tracksRepo := ds.Playlist(r.Context()).Tracks(playlistId)
		var payload addTracksPayload
		err := json.NewDecoder(r.Body).Decode(&payload)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		err = tracksRepo.Add(payload.Ids)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		// Must return an object with an ID, to satisfy ReactAdmin `create` call
		_, err = w.Write([]byte(fmt.Sprintf(`{"id":"%s"}`, playlistId)))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
// writeError [go]
func writeError(resp http.ResponseWriter, err error, code int) {
	resp.WriteHeader(code)
	_, _ = resp.Write([]byte(html.EscapeString(fmt.Sprintf("Error: %v", err))))
}
// writeError [go]
func writeError(resp http.ResponseWriter, err error, code int) {
	resp.WriteHeader(code)
	_, _ = resp.Write([]byte(fmt.Sprintf("Error: %v", err)))
}
// errorf [go]
func (v *VM) errorf(format string, args ...interface{}) {
	i := v.prog[v.t.pc-1]
	progRuntimeErrors.Add(v.name, 1)
	v.runtimeErrorMu.Lock()
	v.runtimeError = fmt.Sprintf(format+"\n", args...)
	v.runtimeError += fmt.Sprintf(
		"Error occurred at instruction %d {%s, %v}, originating in %s at line %d\n",
		v.t.pc-1, i.Opcode, i.Operand, v.name, i.SourceLine+1)
	v.runtimeError += fmt.Sprintf("Full input text from %q was %q", v.input.Filename, v.input.Line)
	if *runtimeLogError || bool(glog.V(1)) {
		glog.Info(v.name + ": Runtime error: " + v.runtimeError)

		glog.Infof("Set logging verbosity higher (-v1 or more) to see full VM state dump.")
	}
	if glog.V(1) {
		glog.Infof("VM stack:\n%s", debug.Stack())
		glog.Infof("Dumping vm state")
		glog.Infof("Name: %s", v.name)
		glog.Infof("Input: %#v", v.input)
		glog.Infof("Thread:")
		glog.Infof(" PC %v", v.t.pc-1)
		glog.Infof(" Matched %v", v.t.matched)
		glog.Infof(" Matches %v", v.t.matches)
		glog.Infof(" Timestamp %v", v.t.time)
		glog.Infof(" Stack %v", v.t.stack)
		glog.Infof(v.DumpByteCode())
	}
	v.runtimeErrorMu.Unlock()
	v.terminate = true
}
// errorf [go]
func (v *VM) errorf(format string, args ...interface{}) {
	i := v.prog[v.t.pc-1]
	progRuntimeErrors.Add(v.name, 1)
	v.runtimeErrorMu.Lock()
	v.runtimeError = fmt.Sprintf(format+"\n", args...)
	v.runtimeError += fmt.Sprintf(
		"Error occurred at instruction %d {%s, %v}, originating in %s at line %d\n",
		v.t.pc-1, i.Opcode, i.Operand, v.name, i.SourceLine+1)
	v.runtimeError += fmt.Sprintf("Full input text from %q was %q", v.input.Filename, v.input.Line)
	if *runtimeLogError || bool(glog.V(1)) {
		glog.Info(v.name + ": Runtime error: " + v.runtimeError)

		glog.Infof("Set logging verbosity higher (-v1 or more) to see full VM state dump.")
	}
	if glog.V(1) {
		glog.Infof("VM stack:\n%s", debug.Stack())
		glog.Infof("Dumping vm state")
		glog.Infof("Name: %s", v.name)
		glog.Infof("Input: %#v", v.input)
		glog.Infof("Thread:")
		glog.Infof(" PC %v", v.t.pc-1)
		glog.Infof(" Matched %v", v.t.matched)
		glog.Infof(" Matches %v", v.t.matches)
		glog.Infof(" Timestamp %v", v.t.time)
		glog.Infof(" Stack %v", v.t.stack)
		glog.Infof(v.DumpByteCode(v.name))
	}
	v.runtimeErrorMu.Unlock()
	v.terminate = true
}
// landingPage [go]
func landingPage(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	idStr := r.URL.Path[1:]

	// When we don't have an idStr or it contains any path elements, we would
	// serve the landing page
	if len(idStr) < 1 || strings.Contains(idStr, "/") ||
		strings.HasSuffix(idStr, "index.html") {
		dcCh := config.MustGetAsync(ctx)
		psCh := preloadedState(ctx)

		nodeEnv := "production"

		if webapp.IsDev {
			nodeEnv = "development"
		}

		initData := fmt.Sprintf(initDataTemplate, <-psCh, nodeEnv)

		tmpl := webapp.GetTemplate("index.html", webapp.IsDev)
		tmpl.Execute(w, map[string]interface{}{
			"Config":    <-dcCh,
			"BuildInfo": config.B,
			"InitData":  template.HTML(initData),
		})
		return
	}

	id := base62.Decode(idStr)

	idStr = html.EscapeString(idStr)

	shortURL, err := shorturl.ByID(ctx, id)
	if err == datastore.ErrNoSuchEntity {
		log.Printf("Unable to load short url %s. Decoded key: %d",
			idStr, id)
		http.Error(w, fmt.Sprintf("Short URL %s cannot be found !!11one",
			idStr), http.StatusNotFound)
		return
	} else if err != nil {
		log.Printf("Error loading short URL '%s': %s", idStr,
			err.Error())
		http.Error(w, "Internal Server Error",
			http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, shortURL.OriginalURL, http.StatusMovedPermanently)
}
// landingPage [go]
func landingPage(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	idStr := r.URL.Path[1:]

	// When we don't have an idStr or it contains any path elements, we would
	// serve the landing page
	if len(idStr) < 1 || strings.Contains(idStr, "/") ||
		strings.HasSuffix(idStr, "index.html") {
		dcCh := config.MustGetAsync(ctx)
		psCh := preloadedState(ctx)

		nodeEnv := "production"

		if webapp.IsDev {
			nodeEnv = "development"
		}

		initData := fmt.Sprintf(initDataTemplate, <-psCh, nodeEnv)

		tmpl := webapp.GetTemplate("index.html", webapp.IsDev)
		tmpl.Execute(w, map[string]interface{}{
			"Config":    <-dcCh,
			"BuildInfo": config.B,
			"InitData":  template.HTML(initData),
		})
		return
	}

	id := base62.Decode(idStr)

	shortURL, err := shorturl.ByID(ctx, id)
	if err == datastore.ErrNoSuchEntity {
		log.Printf("Unable to load short url %s. Decoded key: %d",
			idStr, id)
		http.Error(w, fmt.Sprintf("Short URL %s cannot be found !!11one",
			idStr), http.StatusNotFound)
		return
	} else if err != nil {
		log.Printf("Error loading short URL '%s': %s", idStr,
			err.Error())
		http.Error(w, "Internal Server Error",
			http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, shortURL.OriginalURL, http.StatusMovedPermanently)
}
// DumpByteCode [go]
func (v *VM) DumpByteCode() string {
	b := new(bytes.Buffer)
	fmt.Fprintf(b, "Prog: %s\n", v.name)
	fmt.Fprintln(b, "Metrics")
	for i, m := range v.m {
		if m.Program == v.name {
			fmt.Fprintf(b, " %8d %s\n", i, m)
		}
	}
	fmt.Fprintln(b, "Regexps")
	for i, re := range v.re {
		fmt.Fprintf(b, " %8d /%s/\n", i, re)
	}
	fmt.Fprintln(b, "Strings")
	for i, str := range v.str {
		fmt.Fprintf(b, " %8d \"%s\"\n", i, str)
	}
	w := new(tabwriter.Writer)
	w.Init(b, 0, 0, 1, ' ', tabwriter.AlignRight)

	fmt.Fprintln(w, "disasm\tl\top\topnd\tline\t")
	for n, i := range v.prog {
		fmt.Fprintf(w, "\t%d\t%s\t%v\t%d\t\n", n, i.Opcode, i.Operand, i.SourceLine+1)
	}
	if err := w.Flush(); err != nil {
		glog.Infof("flush error: %s", err)
	}
	return b.String()
}
// DumpByteCode [go]
func (v *VM) DumpByteCode(name string) string {
	b := new(bytes.Buffer)
	fmt.Fprintf(b, "Prog: %s\n", name)
	fmt.Fprintln(b, "Metrics")
	for i, m := range v.m {
		if m.Program == v.name {
			fmt.Fprintf(b, " %8d %s\n", i, m)
		}
	}
	fmt.Fprintln(b, "Regexps")
	for i, re := range v.re {
		fmt.Fprintf(b, " %8d /%s/\n", i, re)
	}
	fmt.Fprintln(b, "Strings")
	for i, str := range v.str {
		fmt.Fprintf(b, " %8d \"%s\"\n", i, str)
	}
	w := new(tabwriter.Writer)
	w.Init(b, 0, 0, 1, ' ', tabwriter.AlignRight)

	fmt.Fprintln(w, "disasm\tl\top\topnd\tline\t")
	for n, i := range v.prog {
		fmt.Fprintf(w, "\t%d\t%s\t%v\t%d\t\n", n, i.Opcode, i.Operand, i.SourceLine+1)
	}
	if err := w.Flush(); err != nil {
		glog.Infof("flush error: %s", err)
	}
	return b.String()
}
// CreateBasket [go]
func CreateBasket(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	name := ps.ByName("basket")
	if name == serviceOldAPIPath || name == serviceAPIPath || name == serviceUIPath {
		http.Error(w, "This basket name conflicts with reserved system path: "+name, http.StatusForbidden)
		return
	}
	if !validBasketName.MatchString(name) {
		http.Error(w, "invalid basket name; the name does not match pattern: "+validBasketName.String(), http.StatusBadRequest)
		return
	}

	log.Printf("[info] creating basket: %s", name)

	// read config (max 2 kB)
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 2048))
	r.Body.Close()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// default config
	config := BasketConfig{ForwardURL: "", Capacity: serverConfig.InitCapacity}
	if len(body) > 0 {
		if err = json.Unmarshal(body, &config); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		if err = validateBasketConfig(&config); err != nil {
			http.Error(w, err.Error(), http.StatusUnprocessableEntity)
			return
		}
	}

	auth, err := basketsDb.Create(name, config)
	if err != nil {
		http.Error(w, err.Error(), http.StatusConflict)
	} else {
		json, err := json.Marshal(auth)
		writeJSON(w, http.StatusCreated, json, err)
	}
}
// CreateBasket [go]
func CreateBasket(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	name := ps.ByName("basket")
	if name == serviceOldAPIPath || name == serviceAPIPath || name == serviceUIPath {
		http.Error(w, "This basket name conflicts with reserved system path: "+name, http.StatusForbidden)
		return
	}
	if !validBasketName.MatchString(name) {
		http.Error(w, "invalid basket name; ["+name+"] does not match pattern: "+validBasketName.String(), http.StatusBadRequest)
		return
	}

	log.Printf("[info] creating basket: %s", name)

	// read config (max 2 kB)
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 2048))
	r.Body.Close()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// default config
	config := BasketConfig{ForwardURL: "", Capacity: serverConfig.InitCapacity}
	if len(body) > 0 {
		if err = json.Unmarshal(body, &config); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		if err = validateBasketConfig(&config); err != nil {
			http.Error(w, err.Error(), http.StatusUnprocessableEntity)
			return
		}
	}

	auth, err := basketsDb.Create(name, config)
	if err != nil {
		http.Error(w, err.Error(), http.StatusConflict)
	} else {
		json, err := json.Marshal(auth)
		writeJSON(w, http.StatusCreated, json, err)
	}
}
// AcceptBasketRequests [go]
func AcceptBasketRequests(w http.ResponseWriter, r *http.Request) {
	name := strings.Split(r.URL.Path, "/")[1]

	if !validBasketName.MatchString(name) {
		http.Error(w, "invalid basket name; the name does not match pattern: "+validBasketName.String(), http.StatusBadRequest)
	} else if basket := basketsDb.Get(name); basket != nil {
		request := basket.Add(r)

		// forward request if configured and it's a first forwarding
		config := basket.Config()
		if len(config.ForwardURL) > 0 && r.Header.Get(DoNotForwardHeader) != "1" {
			if config.ProxyResponse {
				forwardAndProxyResponse(w, request, config, name)
				return
			}

			go forwardAndForget(request, config, name)
		}

		writeBasketResponse(w, r, name, basket)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}
}
// AcceptBasketRequests [go]
func AcceptBasketRequests(w http.ResponseWriter, r *http.Request) {
	name := strings.Split(r.URL.Path, "/")[1]

	if !validBasketName.MatchString(name) {
		http.Error(w, "invalid basket name; ["+name+"] does not match pattern: "+validBasketName.String(), http.StatusBadRequest)
	} else if basket := basketsDb.Get(name); basket != nil {
		request := basket.Add(r)

		// forward request if configured and it's a first forwarding
		config := basket.Config()
		if len(config.ForwardURL) > 0 && r.Header.Get(DoNotForwardHeader) != "1" {
			if config.ProxyResponse {
				forwardAndProxyResponse(w, request, config, name)
				return
			}

			go forwardAndForget(request, config, name)
		}

		writeBasketResponse(w, r, name, basket)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}
}
// SessionAttributesManager::doGet [java]
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", -1);

    String name = request.getParameter("name");
    String value = request.getParameter("value");
    String message = "The parameter 'name' is empty";

    if (name != null && name.length() > 0) {
      if (allowedAttributes.contains(name)) {

        // add bcdBeanUser.name entries as HashMap session variable "bcdBeanUser" where the key/value pairs
        // are kept without the prefix.
        boolean error = true;
        Subject subject = SecurityUtils.getSubject();
        // check value against list of allowed values or subject settings user rights
        if (subject != null && subject.getSession() != null && ((allowedValues.get(name) != null && allowedValues.get(name).contains(" " + value + " ")) || subject.isPermitted(BCD_EL_USER_BEAN + ":" + name + ":" + value))) {
          Map<String, String> bean = (HashMap<String, String>)subject.getSession().getAttribute(BCD_EL_USER_BEAN);
          if (bean == null)
            bean = new HashMap<>();
          bean.put(name, value);
          subject.getSession().setAttribute(BCD_EL_USER_BEAN, bean);
          error = false;
        }
        message ="The " + BCD_EL_USER_BEAN + " '" + name +  (error ? "' can not be set to '" : "' was set to ") + value;
      }
      else {
        message = "The attribute name '" + name + "' is not allowed by the configuration. Please set the init param ALLOWED_ATTRIBUTES in your web.xml";
      }
    }
    log.debug(message);
  }
// SessionAttributesManager::doGet [java]
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", -1);

    String name = request.getParameter("name");
    String value = request.getParameter("value");
    String message = "The parameter 'name' is empty";

    if (name != null && name.length() > 0) {
      if (allowedAttributes.contains(name)) {

        // add bcdBeanUser.name entries as HashMap session variable "bcdBeanUser" where the key/value pairs
        // are kept without the prefix.
        boolean error = true;
        Subject subject = SecurityUtils.getSubject();
        // check value against list of allowed values or subject settings user rights
        if (subject != null && subject.getSession() != null && ((allowedValues.get(name) != null && allowedValues.get(name).contains(" " + value + " ")) || subject.isPermitted(BCD_EL_USER_BEAN + ":" + name + ":" + value))) {
          Map<String, String> bean = (HashMap<String, String>)subject.getSession().getAttribute(BCD_EL_USER_BEAN);
          if (bean == null)
            bean = new HashMap<>();
          bean.put(name, value);
          subject.getSession().setAttribute(BCD_EL_USER_BEAN, bean);
          error = false;
        }
        message ="The " + BCD_EL_USER_BEAN + " '" + name +  (error ? "' can not be set to '" : "' was set to ") + value;
      }
      else {
        message = "The attribute name '" + name + "' is not allowed by the configuration. Please set the init param ALLOWED_ATTRIBUTES in your web.xml";
      }
    }
    log.debug(message);
    response.getWriter().append(message);
  }
// VelocityViewServlet::error [java]
    protected void error(HttpServletRequest request,
                         HttpServletResponse response,
                         Throwable e)
    {
        String path = ServletUtils.getPath(request);
        if (response.isCommitted())
        {
            getLog().error("An error occured but the response headers have already been sent.");
            getLog().error("Error processing a template for path '{}'", path, e);
            return;
        }

        try
        {
            getLog().error("Error processing a template for path '{}'", path, e);
            StringBuilder html = new StringBuilder();
            html.append("<html>\n");
            html.append("<head><title>Error</title></head>\n");
            html.append("<body>\n");
            html.append("<h2>VelocityView : Error processing a template for path '");
            html.append(StringEscapeUtils.escapeHtml4(path));
            html.append("'</h2>\n");

            Throwable cause = e;

            String why = cause.getMessage();
            if (why != null && why.length() > 0)
            {
                html.append(StringEscapeUtils.escapeHtml4(why));
                html.append("\n<br>\n");
            }

            //TODO: add line/column/template info for parse errors et al

            // if it's an MIE, i want the real stack trace!
            if (cause instanceof MethodInvocationException)
            {
                // get the real cause
                cause = cause.getCause();
            }

            StringWriter sw = new StringWriter();
            cause.printStackTrace(new PrintWriter(sw));

            html.append("<pre>\n");
            html.append(StringEscapeUtils.escapeHtml4(sw.toString()));
            html.append("</pre>\n");
            html.append("</body>\n");
            html.append("</html>");
            response.getWriter().write(html.toString());
        }
        catch (Exception e2)
        {
            // clearly something is quite wrong.
            // let's log the new exception then give up and
            // throw a runtime exception that wraps the first one
            String msg = "Exception while printing error screen";
            getLog().error(msg, e2);
            throw new RuntimeException(msg, e);
        }
    }
// VelocityViewServlet::error [java]
    protected void error(HttpServletRequest request,
                         HttpServletResponse response,
                         Throwable e)
    {
        String path = ServletUtils.getPath(request);
        if (response.isCommitted())
        {
            getLog().error("An error occured but the response headers have already been sent.");
            getLog().error("Error processing a template for path '{}'", path, e);
            return;
        }

        try
        {
            getLog().error("Error processing a template for path '{}'", path, e);
            StringBuilder html = new StringBuilder();
            html.append("<html>\n");
            html.append("<head><title>Error</title></head>\n");
            html.append("<body>\n");
            html.append("<h2>VelocityView : Error processing a template for path '");
            html.append(path);
            html.append("'</h2>\n");

            Throwable cause = e;

            String why = cause.getMessage();
            if (why != null && why.length() > 0)
            {
                html.append(StringEscapeUtils.escapeHtml4(why));
                html.append("\n<br>\n");
            }

            //TODO: add line/column/template info for parse errors et al

            // if it's an MIE, i want the real stack trace!
            if (cause instanceof MethodInvocationException)
            {
                // get the real cause
                cause = cause.getCause();
            }

            StringWriter sw = new StringWriter();
            cause.printStackTrace(new PrintWriter(sw));

            html.append("<pre>\n");
            html.append(StringEscapeUtils.escapeHtml4(sw.toString()));
            html.append("</pre>\n");
            html.append("</body>\n");
            html.append("</html>");
            response.getWriter().write(html.toString());
        }
        catch (Exception e2)
        {
            // clearly something is quite wrong.
            // let's log the new exception then give up and
            // throw a runtime exception that wraps the first one
            String msg = "Exception while printing error screen";
            getLog().error(msg, e2);
            throw new RuntimeException(msg, e);
        }
    }
// (anonymous) [javascript]
        $('#frm_endpoint').on('submit', (e) => {
            e.preventDefault();
            const server_url = $server_url.val().trim().toLowerCase().replace(/[><()\/\"\']/g, '');
            const app_id     = $app_id.val().trim();
            if (server_url) localStorage.setItem('config.server_url', server_url);
            if (app_id && !isNaN(app_id)) localStorage.setItem('config.app_id', parseInt(app_id));
            window.location.reload();
        });
// (anonymous) [javascript]
        $('#frm_endpoint').on('submit', (e) => {
            e.preventDefault();
            const server_url = $server_url.val().trim().toLowerCase();
            const app_id     = $app_id.val().trim();
            if (server_url) localStorage.setItem('config.server_url', server_url);
            if (app_id && !isNaN(app_id)) localStorage.setItem('config.app_id', parseInt(app_id));
            window.location.reload();
        });
// displaySearchHeading [javascript]
    function displaySearchHeading(query) {
        var heading = document.getElementById("searchHeading");
        heading.textContent = "Search results for: " + query;
    }
// displaySearchHeading [javascript]
    function displaySearchHeading(query) {
        var heading = document.getElementById("searchHeading");
        heading.innerHTML = "Search results for: " + query;
    }
// (anonymous) [javascript]
	$(selectedFiles).each(function(i,elem){
		var newtr = $('<tr/>').attr('data-dir', dir).attr('data-filename', elem.name);
		newtr.append($('<td/>').addClass('filename').text(elem.name));
		newtr.append($('<td/>').addClass('size').text(humanFileSize(elem.size)));
		tbody.append(newtr);
		if (elem.type === 'dir') {
			newtr.find('td.filename').attr('style','background-image:url('+OC.imagePath('core', 'filetypes/folder.png')+')');
		} else {
			getMimeIcon(elem.mime,function(path){
				newtr.find('td.filename').attr('style','background-image:url('+path+')');
			});
		}
	});
// (anonymous) [javascript]
	$(selectedFiles).each(function(i,elem){
		var newtr = $('<tr data-dir="'+dir+'" data-filename="'+elem.name+'">'
						+'<td class="filename">'+elem.name+'</td><td class="size">'+humanFileSize(elem.size)+'</td>'
					 +'</tr>');
		tbody.append(newtr);
		if (elem.type === 'dir') {
			newtr.find('td.filename').attr('style','background-image:url('+OC.imagePath('core', 'filetypes/folder.png')+')');
		} else {
			getMimeIcon(elem.mime,function(path){
				newtr.find('td.filename').attr('style','background-image:url('+path+')');
			});
		}
	});
// refresh_select [javascript]
  var refresh_select = function(select, settings) {
    // Clear columns
    select.wrapper.selected.innerHTML = "";
    select.wrapper.non_selected.innerHTML = "";

    // Add headers to columns
    if (settings.non_selected_header && settings.selected_header) {
      var non_selected_header = document.createElement("div");
      var selected_header = document.createElement("div");

      non_selected_header.className = "header";
      selected_header.className = "header";

      non_selected_header.innerText = settings.non_selected_header;
      selected_header.innerText = settings.selected_header;

      select.wrapper.non_selected.appendChild(non_selected_header);
      select.wrapper.selected.appendChild(selected_header);
    }

    // Get search value
    if (select.wrapper.search) {
      var query = select.wrapper.search.value;
    }

    // Current group
    var item_group = null;
    var current_optgroup = null;

    // Loop over select options and add to the non-selected and selected columns
    for (var i = 0; i < select.options.length; i++) {
      var option = select.options[i];

      var value = option.value;
      var label = option.textContent || option.innerText;

      var row = document.createElement("a");
      row.tabIndex = 0;
      row.className = "item";
      row.innerText = label;
      row.setAttribute("role", "button");
      row.setAttribute("data-value", value);
      row.setAttribute("multi-index", i);

      if (option.disabled) {
        row.className += " disabled";
      }

      // Add row to selected column if option selected
      if (option.selected) {
        row.className += " selected";
        var clone = row.cloneNode(true);
        select.wrapper.selected.appendChild(clone);
      }

      // Create group if entering a new optgroup
      if (
        option.parentNode.nodeName == "OPTGROUP" &&
        option.parentNode != current_optgroup
      ) {
        current_optgroup = option.parentNode;
        item_group = document.createElement("div");
        item_group.className = "item-group";

        if (option.parentNode.label) {
          var groupLabel = document.createElement("span");
          groupLabel.innerHTML = option.parentNode.label;
          groupLabel.className = "group-label";
          item_group.appendChild(groupLabel);
        }

        select.wrapper.non_selected.appendChild(item_group);
      }

      // Clear group if not inside optgroup
      if (option.parentNode == select) {
        item_group = null;
        current_optgroup = null;
      }

      // Apply search filtering
      if (
        !query ||
        (query && label.toLowerCase().indexOf(query.toLowerCase()) > -1)
      ) {
        // Append to group if one exists, else just append to wrapper
        if (item_group != null) {
          item_group.appendChild(row);
        } else {
          select.wrapper.non_selected.appendChild(row);
        }
      }
    }
  };
// refresh_select [javascript]
  var refresh_select = function(select, settings) {
    // Clear columns
    select.wrapper.selected.innerHTML = "";
    select.wrapper.non_selected.innerHTML = "";

    // Add headers to columns
    if (settings.non_selected_header && settings.selected_header) {
      var non_selected_header = document.createElement("div");
      var selected_header = document.createElement("div");

      non_selected_header.className = "header";
      selected_header.className = "header";

      non_selected_header.innerText = settings.non_selected_header;
      selected_header.innerText = settings.selected_header;

      select.wrapper.non_selected.appendChild(non_selected_header);
      select.wrapper.selected.appendChild(selected_header);
    }

    // Get search value
    if (select.wrapper.search) {
      var query = select.wrapper.search.value;
    }

    // Current group
    var item_group = null;
    var current_optgroup = null;

    // Loop over select options and add to the non-selected and selected columns
    for (var i = 0; i < select.options.length; i++) {
      var option = select.options[i];

      var value = option.value;
      var label = option.textContent || option.innerText;

      var row = document.createElement("a");
      row.tabIndex = 0;
      row.className = "item";
      row.innerHTML = label;
      row.setAttribute("role", "button");
      row.setAttribute("data-value", value);
      row.setAttribute("multi-index", i);

      if (option.disabled) {
        row.className += " disabled";
      }

      // Add row to selected column if option selected
      if (option.selected) {
        row.className += " selected";
        var clone = row.cloneNode(true);
        select.wrapper.selected.appendChild(clone);
      }

      // Create group if entering a new optgroup
      if (
        option.parentNode.nodeName == "OPTGROUP" &&
        option.parentNode != current_optgroup
      ) {
        current_optgroup = option.parentNode;
        item_group = document.createElement("div");
        item_group.className = "item-group";

        if (option.parentNode.label) {
          var groupLabel = document.createElement("span");
          groupLabel.innerHTML = option.parentNode.label;
          groupLabel.className = "group-label";
          item_group.appendChild(groupLabel);
        }

        select.wrapper.non_selected.appendChild(item_group);
      }

      // Clear group if not inside optgroup
      if (option.parentNode == select) {
        item_group = null;
        current_optgroup = null;
      }

      // Apply search filtering
      if (
        !query ||
        (query && label.toLowerCase().indexOf(query.toLowerCase()) > -1)
      ) {
        // Append to group if one exists, else just append to wrapper
        if (item_group != null) {
          item_group.appendChild(row);
        } else {
          select.wrapper.non_selected.appendChild(row);
        }
      }
    }
  };
// updateLabel [javascript]
	function updateLabel () {
		try {
			var thisId = jQuery('#fb-field-id').val();
			var thisLabel = jQuery('#fb-new-label').val();
			// Update preview
			if (thisLabel.length === 0) {
				jQuery('#fb-new-field' + thisId + ' label .label-text').text( GrunionFB_i18n.newLabel );
			} else {
				jQuery('#fb-new-field' + thisId + ' label .label-text').text( thisLabel );
			}
			// Update fbForm object
			fbForm.fields[thisId].label = thisLabel;
		} catch(e) {
			if (debug) {
				console.log("updateLabel(): " + e);
			}
		}
	}
// updateLabel [javascript]
	function updateLabel () {
		try {
			var thisId = jQuery('#fb-field-id').val();
			var thisLabel = jQuery('#fb-new-label').val();
			// Update preview
			if (thisLabel.length === 0) {
				jQuery('#fb-new-field' + thisId + ' label .label-text').html("New field");
			} else {
				jQuery('#fb-new-field' + thisId + ' label .label-text').html(thisLabel);
			}
			// Update fbForm object
			fbForm.fields[thisId].label = thisLabel;
		} catch(e) {
			if (debug) {
				console.log("updateLabel(): " + e);
			}
		}
	}
// (anonymous) [javascript]
      this.idx.search(query, function(success, content) {
        if (!success) {
          console.log(content);
          return;
        }
        if (originalQuery == $('#inputfield input').val().trim()) {
          if (content.nbHits == 0) {
            self.$noresults.html('<p>No results matching your query:<code>' + $('<div />').text(originalQuery).html() + '<code><p>');
            self.$noresults.show();
          } else {
            self.$noresults.hide();
          }
          self.searchCallback(content);
        }
      }, searchParams);
// (anonymous) [javascript]
      this.idx.search(query, function(success, content) {
        if (!success) {
          console.log(content);
          return;
        }
        if (originalQuery == $('#inputfield input').val().trim()) {
          if (content.nbHits == 0) {
            self.$noresults.html('<p>No results matching your query:<code>' + originalQuery + '<code><p>');
            self.$noresults.show();
          } else {
            self.$noresults.hide();
          }
          self.searchCallback(content);
        }
      }, searchParams);
// (anonymous) [javascript]
      (err, data) => {
        if (err) {
          if (!fs.existsSync(safeFileFullPath)) {
            var EnoentError = `Requested metadata for ${metaFileName} not found`
            logger.log2('error', EnoentError)
            res.status(404).send('Requested metadata not found')
          } else {
            res.status(500).send(`An error occurred: ${err}`)
            logger.log2('error', err)
          }
        } else {
          res.status(200).set('Content-Type', 'text/xml').send(String(data))
        }
      })
// (anonymous) [javascript]
      (err, data) => {
        if (err) {
          if (!fs.existsSync(safeFileFullPath)) {
            var EnoentError = `Requested metadata for ${metaFileName} not found`
            logger.log2('error', EnoentError)
            res.status(404).send(EnoentError)
          } else {
            res.status(500).send(`An error occurred: ${err}`)
            logger.log2('error', err)
          }
        } else {
          res.status(200).set('Content-Type', 'text/xml').send(String(data))
        }
      })
// showAndHideMessage [javascript]
	function showAndHideMessage (message) {
		try {
			var newMessage = (!message) ? GrunionFB_i18n.savedMessage : message;
			jQuery('#fb-success').text(newMessage);
			jQuery('#fb-success').slideDown('fast');
			setTimeout(function () {
				 jQuery('#fb-success').slideUp('fast');
			}, 2500);
		} catch(e) {
			if (debug) {
				console.log("showAndHideMessage(): " + e);
			}
		}
	}
// showAndHideMessage [javascript]
	function showAndHideMessage (message) {
		try {
			var newMessage = (!message) ? GrunionFB_i18n.savedMessage : message;
			jQuery('#fb-success').html(newMessage);
			jQuery('#fb-success').slideDown('fast');
			setTimeout(function () {
				 jQuery('#fb-success').slideUp('fast');
			}, 2500);
		} catch(e) {
			if (debug) {
				console.log("showAndHideMessage(): " + e);
			}
		}
	}
// saveNewOption [javascript]
	saveNewOption:function(){
		var newValF=$('#akSelectValueFieldNew');
		var val = $('<div/>').text(newValF.val()).html();
		if(val=='') {
			return;
		}
		var ts = 't' + new Date().getTime();
		var template=document.getElementById('akSelectValueWrapTemplate'); 
		var newRowEl=document.createElement('div');
		newRowEl.innerHTML=template.innerHTML.replace(/template_clean/ig,ts).replace(/template/ig,val);
		newRowEl.id="akSelectValueWrap_"+ts;
		newRowEl.className='akSelectValueWrap';
		$('#attributeValuesWrap').append(newRowEl);		
		newValF.val(''); 
	},
// saveNewOption [javascript]
	saveNewOption:function(){
		var newValF=$('#akSelectValueFieldNew');
		var val=newValF.val();
		if(val=='') {
			return;
		}
		var ts = 't' + new Date().getTime();
		var template=document.getElementById('akSelectValueWrapTemplate'); 
		var newRowEl=document.createElement('div');
		newRowEl.innerHTML=template.innerHTML.replace(/template_clean/ig,ts).replace(/template/ig,val);
		newRowEl.id="akSelectValueWrap_"+ts;
		newRowEl.className='akSelectValueWrap';
		$('#attributeValuesWrap').append(newRowEl);		
		newValF.val(''); 
	},
// editInPlace [javascript]
function editInPlace(element) {
  closeEditInPlaceForms();

  // create edit form
  var tag_id = $(this).attr('id').substr(5);
  var tag_name = $(this).html();
  var tag_width = $(this).width();
  $(this).parent().data("revert", $(this).parent().html());
  var form = '<form id="gRenameTagForm" method="post" class="ui-helper-clearfix" ';
  form += 'action="' + TAG_RENAME_URL.replace('__ID__', tag_id) + '">';
  form += '<input name="csrf" type="hidden" value="' + csrf_token + '" />';
  form += '<input id="name" name="name" type="text" class="textbox" value="' +
          str_replace('"', "&quot;", tag_name) + '" />';
  form += '<input type="submit" class="submit ui-state-default ui-corner-all" value="' + save_i18n + '" i/>';
  form += '<a href="#">' + cancel_i18n + '</a>';
  form += '</form>';

  // add edit form
  $(this).parent().html(form);
  $("#gRenameTagForm #name")
    .width(tag_width+30)
    .focus();
  //$("#gRenameTagForm").parent().height( $("#gRenameTagForm").height() );
  $("#gRenameTagForm a").bind("click", closeEditInPlaceForms);

  ajaxify_editInPlaceForm = function() {
    $("#gRenameTagForm").ajaxForm({
      dataType: "json",
      success: function(data) {
        if (data.result == "success") {
          closeEditInPlaceForms(); // close form
          $("#gTag-" + data.tag_id).text(data.new_tagname); // update tagname
          console.log(data);
          window.location.reload();
        }
      }
    });
  };
  ajaxify_editInPlaceForm();
}
// editInPlace [javascript]
function editInPlace(element) {
  closeEditInPlaceForms();

  // create edit form
  var tag_id = $(this).attr('id').substr(5);
  var tag_name = $(this).text();
  var tag_width = $(this).width();
  $(this).parent().data("revert", $(this).parent().html());
  var form = '<form id="gRenameTagForm" method="post" class="ui-helper-clearfix" ';
  form += 'action="' + TAG_RENAME_URL.replace('__ID__', tag_id) + '">';
  form += '<input name="csrf" type="hidden" value="' + csrf_token + '" />';
  form += '<input id="name" name="name" type="text" class="textbox" value="' + tag_name + '" />';
  form += '<input type="submit" class="submit ui-state-default ui-corner-all" value="' + save_i18n + '" i/>';
  form += '<a href="#">' + cancel_i18n + '</a>';
  form += '</form>';

  // add edit form
  $(this).parent().html(form);
  $("#gRenameTagForm #name")
    .width(tag_width+30)
    .focus();
  //$("#gRenameTagForm").parent().height( $("#gRenameTagForm").height() );
  $("#gRenameTagForm a").bind("click", closeEditInPlaceForms);

  ajaxify_editInPlaceForm = function() {
    $("#gRenameTagForm").ajaxForm({
      dataType: "json",
      success: function(data) {
        if (data.result == "success") {
          closeEditInPlaceForms(); // close form
          $("#gTag-" + data.tag_id).text(data.new_tagname); // update tagname
          console.log(data);
          window.location.reload();
        }
      }
    });
  };
  ajaxify_editInPlaceForm();
}
// (anonymous) [javascript]
    $("form#streamrule-form").on("click", "#sr-inverted", function() {
        var modalBody = $(this).closest("form#streamrule-form").find(".modal-body");
        var old_val = $("#sr-result-category", modalBody).html();

        if ($(this).is(":checked")) {
            // Add the not.
            new_val = "not " + old_val;
        } else {
            // Remove the not.
            if (old_val.substr(0,3) == "not") {
                new_val = old_val.substr(3);
            } else {
                new_val = old_val;
            }
        }
        $("#sr-result-category", modalBody).text(new_val);
    })
// (anonymous) [javascript]
    $("form#streamrule-form").on("click", "#sr-inverted", function() {
        var modalBody = $(this).closest("form#streamrule-form").find(".modal-body");
        var old_val = $("#sr-result-category", modalBody).html();

        if ($(this).is(":checked")) {
            // Add the not.
            new_val = "not " + old_val;
        } else {
            // Remove the not.
            if (old_val.substr(0,3) == "not") {
                new_val = old_val.substr(3);
            } else {
                new_val = old_val;
            }
        }
        $("#sr-result-category", modalBody).html(new_val);
    })
// (anonymous) [javascript]
    $("#extra").on("click", "#moveRepeatingGroup", function() {
        var repeatingCols = '';
        $("#extra input[type=checkbox]:checked").each(function() {
            repeatingCols += $(this).val() + ', ';
        });

        if (repeatingCols !== '') {
            var newColName = $("#extra input[type=checkbox]:checked:first").val();
            repeatingCols = repeatingCols.slice(0, -2);
            var confirmStr = PMA_sprintf(PMA_messages.strMoveRepeatingGroup, escapeHtml(repeatingCols), escapeHtml(PMA_commonParams.get('table')));
            confirmStr += '<input type="text" name="repeatGroupTable" placeholder="' + PMA_messages.strNewTablePlaceholder + '"/>' +
                '( ' + escapeHtml(primary_key.toString()) + ', <input type="text" name="repeatGroupColumn" placeholder="' + PMA_messages.strNewColumnPlaceholder + '" value="' + escapeHtml(newColName) + '">)' +
                '</ol>';
            $("#newCols").html(confirmStr);
            $('.tblFooters').html('<input type="submit" value="' + PMA_messages.strCancel + '" onclick="$(\'#newCols\').html(\'\');$(\'#extra input[type=checkbox]\').removeAttr(\'checked\')"/>' +
                '<input type="submit" value="' + PMA_messages.strGo + '" onclick="moveRepeatingGroup(\'' + escapeJsString(escapeHtml(repeatingCols)) + '\')"/>');
        }
    });
// (anonymous) [javascript]
    $("#extra").on("click", "#moveRepeatingGroup", function() {
        var repeatingCols = '';
        $("#extra input[type=checkbox]:checked").each(function() {
            repeatingCols += $(this).val() + ', ';
        });

        if (repeatingCols !== '') {
            var newColName = $("#extra input[type=checkbox]:checked:first").val();
            repeatingCols = repeatingCols.slice(0, -2);
            var confirmStr = PMA_sprintf(PMA_messages.strMoveRepeatingGroup, escapeHtml(repeatingCols), escapeHtml(PMA_commonParams.get('table')));
            confirmStr += '<input type="text" name="repeatGroupTable" placeholder="' + PMA_messages.strNewTablePlaceholder + '"/>' +
                '( ' + escapeHtml(primary_key.toString()) + ', <input type="text" name="repeatGroupColumn" placeholder="' + PMA_messages.strNewColumnPlaceholder + '" value="' + escapeHtml(newColName) + '">)' +
                '</ol>';
            $("#newCols").html(confirmStr);
            $('.tblFooters').html('<input type="submit" value="' + PMA_messages.strCancel + '" onclick="$(\'#newCols\').html(\'\');$(\'#extra input[type=checkbox]\').removeAttr(\'checked\')"/>' +
                '<input type="submit" value="' + PMA_messages.strGo + '" onclick="moveRepeatingGroup(\'' + repeatingCols + '\')"/>');
        }
    });
// updateDataEntry [javascript]
  function updateDataEntry($box, forceUpdate) {
    var $input = $box;
    var $parent = $input.parents(".table_entry");
    if(!$box.hasClass('grading_value')) {
      $input = $box.find(".grading_value");
    }
    var val = $input.val();
    var sendVal = val;
    var oldVal = $.trim($parent.find(".grade").text());
    if($parent.find(".grade img").length > 0) {
      oldVal = $parent.find(".grade img").attr('alt').toLowerCase();
    }
    if(oldVal == "-") {
      oldVal = "";
    }

    if($input.hasClass('pass_fail')) {
      if(val == "pass" || val == "fail") {
        val = $("#submission_entry_" + val + "_image").clone().attr('id', '');
      }
    }
    var data = {};
    var formData = $update_submission_form.getFormData();
    var submission = objectData($parent.parent());
    data.id = submission.id || "";
    data.assignment_id = submission.assignment_id;
    data.student_id = submission.user_id;
    data.grade = sendVal;
    if(sendVal != oldVal || (sendVal && forceUpdate)) {
      submitDataEntry(data);
    }
    if(!val || val == "") {
      data.submission_type = submission.submission_type || "";
      val = emptySubmissionText(data);
    }
    $parent.find(".grade").show().empty().append(htmlEscape(val));
  }
// updateDataEntry [javascript]
  function updateDataEntry($box, forceUpdate) {
    var $input = $box;
    var $parent = $input.parents(".table_entry");
    if(!$box.hasClass('grading_value')) {
      $input = $box.find(".grading_value");
    }
    var val = $input.val();
    var sendVal = val;
    var oldVal = $.trim($parent.find(".grade").text());
    if($parent.find(".grade img").length > 0) {
      oldVal = $parent.find(".grade img").attr('alt').toLowerCase();
    }
    if(oldVal == "-") {
      oldVal = "";
    }

    if($input.hasClass('pass_fail')) {
      if(val == "pass" || val == "fail") {
        val = $("#submission_entry_" + val + "_image").clone().attr('id', '');
      }
    }
    var data = {};
    var formData = $update_submission_form.getFormData();
    var submission = objectData($parent.parent());
    data.id = submission.id || "";
    data.assignment_id = submission.assignment_id;
    data.student_id = submission.user_id;
    data.grade = sendVal;
    if(sendVal != oldVal || (sendVal && forceUpdate)) {
      submitDataEntry(data);
    }
    if(!val || val == "") {
      data.submission_type = submission.submission_type || "";
      val = emptySubmissionText(data);
    }
    $parent.find(".grade").show().empty().append(val);
  }
// setValidity [javascript]
function setValidity(text = '') {
	errorMessage.innerHTML = text;
	regexField.setCustomValidity(errorMessage.textContent); /* Triggers :invalid */
}
// setValidity [javascript]
function setValidity(text = '') {
	errorMessage.innerHTML = text;
	regexField.setCustomValidity(text); /* Triggers :invalid */
}
// searchAll [javascript]
function searchAll() {
    scheduler.clear("search"); // clear previous search
    maxJobs = 1; // clear previous max
    var searchStr = $("#textfilter input").attr("value").trim() || '';
    searchStr = escape(searchStr);

    if (searchStr === '') {
        $("div#search-results").hide();
        $("#search > span.close-results").hide();
        $("#search > span#doc-title").show();
        return;
    }

    // Replace ?search=X with current search string if not hosted locally on Chrome
    try {
        window.history.replaceState({}, "", "?search=" + searchStr);
    } catch(e) {}

    $("div#results-content > span.search-text").remove();

    var memberResults = document.getElementById("member-results");
    memberResults.innerHTML = "";
    var memberH1 = document.createElement("h1");
    memberH1.className = "result-type";
    memberH1.innerHTML = "Member results";
    memberResults.appendChild(memberH1);

    var entityResults = document.getElementById("entity-results");
    entityResults.innerHTML = "";
    var entityH1 = document.createElement("h1");
    entityH1.className = "result-type";
    entityH1.innerHTML = "Entity results";
    entityResults.appendChild(entityH1);

    $("div#results-content")
        .prepend("<span class='search-text'>"
                +"  Showing results for <span class='query-str'>\"" + searchStr + "\"</span>"
                +"</span>");

    var regExp = compilePattern(searchStr);

    // Search for all entities matching query
    Index
        .keys(Index.PACKAGES)
        .sort()
        .forEach(function(elem) { searchPackage(elem, regExp); })
}