Builds response headers and in process renders templates, if any.

        This method overrides SimpleHTTPRequestHandlet.send_head()
164337
def send_head(self):
        
        path = self.translate_path(self.path)
        f = None
        to_render = False
        if os.path.isdir(path):
            if not self.path.endswith('/'):
                # redirect browser - doing basically what apache does
                self.send_response(301)
                self.send_header("Location", self.path + "/")
                self.end_headers()
                return None
        else:
            # check if URL corresponds to a template to render
            if path.endswith("/"):
                index = path[:-1]
            else:
                index = path
            for ext in '.html', '.htm':
                if os.path.exists(index + ext):
                    to_render = True
                    realpath = index + ext
                    break
        if os.path.isdir(path):
            # if dir, check for existence of index.htm*
            for index in "index.html", "index.htm":
                index = os.path.join(path, index)
                if os.path.exists(index):
                    realpath = index
                    to_render = True
                    break
            else:
                return self.list_directory(path)
        # deny if URL directly requests for *.html file, allow if dir
        file_extension = os.path.splitext(path)[1]
        if file_extension in ('.html', '.htm') and not os.path.isdir(path):
            self.send_error(404, "File not found")
            return None
        if to_render:
            path = realpath
        ctype = self.guess_type(path)
        try:
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None
        fs = os.fstat(f.fileno())
        if to_render:
            stream, length = self.gen_response_stream(f)
        else:
            length = fs[6]
        self.send_response(200)
        self.send_header("Content-type", ctype)
        self.send_header("Content-Length", str(length))
        self.send_header("Last-Modified", self.date_time_string(
            fs.st_mtime))
        self.end_headers()
        if to_render:
            return stream
        return f
828264
function onHeaders(ev, status, newUrl, oldUrl, statusCode, method, referrer, headers, resourceType) {
    if (resourceType !== 'mainFrame') return;

    let headerArray = [];

    Object.keys(headers).forEach(name => {
      headers[name].forEach(value => {
        headerArray.push({ name, value });
      });
    });

    response = {
      url: newUrl,
      method,
      status: statusCode,
      contentType: headers['content-type'][0],
      headers: headerArray
    };

    notify([ 'header event', status, newUrl, oldUrl, statusCode, method, referrer, headers, resourceType ]);
  }
790129
function renderHeader(&$header)
    {
        $name = $header->getName();
        if (!empty($name) && isset($this->_templates[$name])) {
            $this->_html .= str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
        } else {
            $this->_html .= str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
        }
    }
1193354
protected void doResponseHeaders(final HttpServletResponse response, final String mimeType) {
        if (mimeType != null) {
            response.setContentType(mimeType);
        }
    }
612470
protected function _buildAndExecuteProxyResponse()
    {
        if($this->_responseModifier)
        {
          $data = call_user_func_array($this->_responseModifier, array(&$this->_responseBody, &$this->_responseHeaders));
        }

        $this->_generateProxyResponseHeaders();

        $this->_output($this->_responseBody);
    }
124247
def head(self, url, *args, **kwargs):
        
        res = self._conn.head(url, headers=self._prepare_headers(**kwargs))
        if res.status_code == 200:
            return res
        return None
81398
public function renderResponse() {

		if(isset($this->methodName)) {
			$methodName = $this->methodName;
			$this->$methodName()->send();
		}
		else {
			$this->execute()->send();
		}

	}
284770
public void sendResponse(HttpResponse resp, boolean close) throws IOException {
		StringBuilder header = new StringBuilder();
		header.append("HTTP/1.1").append(' ').append(resp.getStatus().getCode()).append(' ').append(resp.getStatus());
		header.append('\r').append('\n');
		// Set the content type header if it's not already set
		if (!resp.getHeaders().containsKey(HttpHeader.CONTENT_TYPE)) {
			resp.addHeader(HttpHeader.CONTENT_TYPE, "text/html; charset=utf-8");
		}
		// Set the content length header if it's not already set
		if (!resp.getHeaders().containsKey(HttpHeader.CONTENT_LENGTH)) {
			resp.addHeader(HttpHeader.CONTENT_LENGTH, resp.getResponseLength());
		}
		// Copy in the headers
		for (Entry<String, List<Object>> entry : resp.getHeaders().entrySet()) {
			String headerName = HttpUtil.capitalizeHeader(entry.getKey());
			for (Object o : entry.getValue()) {
				header.append(headerName);
				header.append(':').append(' ');
				header.append(o);
				header.append('\r').append('\n');
			}
		}
		header.append('\r').append('\n');
		// Write the header
		output.write(header.toString().getBytes("UTF-8"));

		// Ignore the body for headers and no content
		if (request != null && request.getMethod() == HttpMethod.HEAD || resp.getStatus() == HttpStatus.NO_CONTENT) {
			if (resp.getResponse() instanceof InputStream) {
				((InputStream) resp.getResponse()).close();
			}
		} else {
			// Responses can be InputStreams or Strings
			if (resp.getResponse() instanceof InputStream) {
				// InputStreams will block the session thread (No big deal) and send
				// data without loading it into memory
				InputStream res = resp.getResponse();
				try {
					long remaining = resp.getResponseLength();
					// Write the body
					byte[] buffer = new byte[1024];
					while (remaining > 0) {
						int read = res.read(buffer, 0, remaining > buffer.length ? buffer.length : (int) remaining);
						if (read == -1) {
							break;
						}

						output.write(buffer, 0, read);

						remaining -= read;
					}
				} finally {
					res.close();
				}
			} else if (resp.getResponse() instanceof String) {
				String responseString = resp.getResponse();
				output.write(responseString.getBytes("UTF-8"));
			} else if (resp.getResponse() instanceof byte[]) {
				output.write((byte[]) resp.getResponse());
			}
		}
		// Close it if required.
		if (close) {
			socket.close();
		}
	}

	/**
	 * Send an HttpStatus
	 *
	 * @param status The status to send
	 * @throws IOException If an error occurred while sending
	 */
	public void sendError(HttpStatus status) throws IOException {
		sendResponse(new HttpResponse(status, status.toString()));
	}

	/**
	 * Send an HttpStatus with the specified error message
	 *
	 * @param status The status to send
	 * @param message The error message to send
	 * @throws IOException If an error occurred while sending
	 */
	public void sendError(HttpStatus status, String message) throws IOException {
		sendResponse(new HttpResponse(status, status.toString() + ':' + message));
	}

	/**
	 * Get the remote address from this session
	 *
	 * @return The remote address
	 */
	public InetSocketAddress getRemoteAddress() {
		return (InetSocketAddress) socket.getRemoteSocketAddress();
	}
}
728681
public void writeHeaders(HttpResponse response,Resource resource, long count)
        throws IOException
    {
        ResourceCache.ResourceMetaData metaData =
            (ResourceCache.ResourceMetaData)resource.getAssociate();

        response.setContentType(metaData.getMimeType());
        if (count != -1)
        {
            if (count==resource.length())
                response.setField(HttpFields.__ContentLength,metaData.getLength());
            else
                response.setContentLength((int)count);
        }

        response.setField(HttpFields.__LastModified,metaData.getLastModified());
        
        if (_acceptRanges && response.getHttpRequest().getDotVersion()>0)
            response.setField(HttpFields.__AcceptRanges,"bytes");
    }
245792
def build_final_response(request, meta, result, menu, hproject, proxyMode, context):
    """"""

    if 'no_template' in meta and meta['no_template']:  # Just send the json back
        return HttpResponse(result)

    # TODO this breaks pages not using new template
    # Add sidebar toggler if plugit did not add by itself
    # if not "sidebar-toggler" in result:
    #     result = "<div class=\"menubar\"><div class=\"sidebar-toggler visible-xs\"><i class=\"ion-navicon\"></i></div></div>" + result

    # render the template into the whole page
    if not settings.PIAPI_STANDALONE:
        return render_to_response('plugIt/' + hproject.get_plugItTemplate_display(),
                                  {"project": hproject,
                                   "plugit_content": result,
                                   "plugit_menu": menu,
                                   'context': context},
                                  context_instance=RequestContext(request))

    if proxyMode:  # Force inclusion inside template
        return render_to_response('plugIt/base.html',
                                  {'plugit_content': result,
                                   "plugit_menu": menu,
                                   'context': context},
                                  context_instance=RequestContext(request))

    renderPlugItTemplate = 'plugItBase.html'
    if settings.PIAPI_PLUGITTEMPLATE:
        renderPlugItTemplate = settings.PIAPI_PLUGITTEMPLATE

    return render_to_response('plugIt/' + renderPlugItTemplate,
                              {"plugit_content": result,
                               "plugit_menu": menu,
                               'context': context},
                              context_instance=RequestContext(request))
387025
@Override
	public void renderHead(IHeaderResponse response) {
		super.renderHead(response);
		
		StringBuilder sb = new StringBuilder();
		if(container.isVisible()) sb.append("$('#"+BootstrapModal.this.getMarkupId()+"').modal('show');");
		else sb.append("$('#"+BootstrapModal.this.getMarkupId()+"').modal('hide');");
		response.render(OnDomReadyHeaderItem.forScript(sb.toString()));
	}
793034
protected function __renderHeaders()
    {
        if (!is_array($this->_headers) || empty($this->_headers)) {
            return;
        }

        // Legacy check
        if ($this->_status != null) {
            $this->setHttpStatus($this->_status);
        }

        foreach ($this->_headers as $key => $value) {
            // If this is the http status
            if ($key == 'status' && isset($value['response_code'])) {
                $res_code = intval($value['response_code']);
                self::renderStatusCode($res_code);
            } else {
                header($value['header']);
            }
        }
    }
1242288
protected function __build()
    {
        $this->__generateHead();
        $this->Html->appendChild($this->Head);
        $this->Html->appendChild($this->Body);
    }
1111036
protected function handleHead() : HttpResponse
    {
        $key = $this->request->key();

        if ( ! $fileMeta = $this->cache->get($key)) {
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
        }

        $offset = $fileMeta['offset'] ?? false;

        if (false === $offset) {
            return $this->response->send(null, HttpResponse::HTTP_GONE);
        }

        return $this->response->send(null, HttpResponse::HTTP_OK, $this->getHeadersForHeadRequest($fileMeta));
    }
7603
def on_headers(self, response, exc=None):
        ''''''

        if response.status_code == 101:
            connection = response.connection
            request = response.request
            handler = request.websocket_handler
            if not handler:
                handler = WS()
            parser = request.client.frame_parser(kind=1)
            consumer = partial(WebSocketClient.create,
                               response, handler, parser)
            connection.upgrade(consumer)
            response.event('post_request').fire()
            websocket = connection.current_consumer()
            response.request_again = lambda r: websocket
1139695
function _setResponseHeaders(headers) {
            this.responseHeaders = {};

            for (var header in headers) {
                if (headers.hasOwnProperty(header)) {
                    this.responseHeaders[header] = headers[header];
                }
            }

            if (this.async) {
                this._readyStateChange(IsotropyXMLHttpRequest.HEADERS_RECEIVED);
            } else {
                this.readyState = IsotropyXMLHttpRequest.HEADERS_RECEIVED;
            }
        }
943493
def _build_response(data, renderer=None):
    
    if isinstance(data, Response) or isinstance(data, BaseResponse):
        return data
    if not renderer:
        raise AttributeError(" Renderer is required")
    if isinstance(data, dict) or data is None:
        data = {} if data is None else data
        for _ in __view_parsers:
            data = _(data)
        return renderer(data), 200
    elif isinstance(data, tuple):
        data, status, headers = _normalize_response_tuple(data)
        for _ in __view_parsers:
            data = _(data)
        return renderer(data or {}), status, headers
    return data