Parse the response, and then emit the event passing along the response and the uploaded files!
775099
function parseJSON(str) {
                                            var result;
                                            try {
                                                result = $scope.options.parserFn(str);
                                            } catch (e) {
                                                return str;
                                            }
                                            return result;
                                        }
710202
def parse(self, stream, media_type=None, parser_context=None):
        

        parser_context = parser_context or {}
        request = parser_context['request']
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        meta = request.META
        upload_handlers = request.upload_handlers
        filename = self.get_filename(stream, media_type, parser_context)

        # Note that this code is extracted from Django's handling of
        # file uploads in MultiPartParser.
        content_type = meta.get('HTTP_CONTENT_TYPE',
                                meta.get('CONTENT_TYPE', ''))
        try:
            content_length = int(meta.get('HTTP_CONTENT_LENGTH',
                                          meta.get('CONTENT_LENGTH', 0)))
        except (ValueError, TypeError):
            content_length = None

        # See if the handler will want to take care of the parsing.
        for handler in upload_handlers:
            result = handler.handle_raw_input(None,
                                              meta,
                                              content_length,
                                              None,
                                              encoding)
            if result is not None:
                return DataAndFiles({}, {'file': result[1]})

        # This is the standard case.
        possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size]
        chunk_size = min([2 ** 31 - 4] + possible_sizes)
        chunks = ChunkIter(stream, chunk_size)
        counters = [0] * len(upload_handlers)

        for index, handler in enumerate(upload_handlers):
            try:
                handler.new_file(None, filename, content_type,
                                 content_length, encoding)
            except StopFutureHandlers:
                upload_handlers = upload_handlers[:index + 1]
                break

        for chunk in chunks:
            for index, handler in enumerate(upload_handlers):
                chunk_length = len(chunk)
                chunk = handler.receive_data_chunk(chunk, counters[index])
                counters[index] += chunk_length
                if chunk is None:
                    break

        for index, handler in enumerate(upload_handlers):
            file_obj = handler.file_complete(counters[index])
            if file_obj:
                return DataAndFiles({}, {'file': file_obj})
        raise ParseError("FileUpload parse error - "
                         "none of upload handlers can handle the stream")
240421
def emit(self):
        
        # Skip serialize
        if not isinstance(self.response, SerializedHttpResponse):
            return self.response

        self.response.content = self.serialize(self.response.response)
        self.response['Content-type'] = self.media_type
        return self.response
964876
def do_POST(self, request, response):
        # pylint: disable=C0103
        
        # Get the request JSON content
        data = jsonrpclib.loads(to_str(request.read_data()))

        # Convert from Jabsorb
        data = jabsorb.from_jabsorb(data)

        # Dispatch
        try:
            result = self._unmarshaled_dispatch(data, self._simple_dispatch)
        except NoMulticallResult:
            # No result (never happens, but who knows...)
            result = None

        if result is not None:
            # Convert result to Jabsorb
            if "result" in result:
                result["result"] = jabsorb.to_jabsorb(result["result"])

            # Store JSON
            result = jsonrpclib.jdumps(result)
        else:
            # It was a notification
            result = ""

        # Send the result
        response.send_content(200, result, "application/json-rpc")
1151399
function onResponse( res ) {
		self.res.status = res.statusCode;
		self.res.headers = res.headers;

		// TODO: record headers length

		res.on( 'data', onData );
		res.on( 'end', onEnd );
	}
398911
def handle_stream(self, response):
        
        event = {}
        line_buffer = bytearray()
        try:
            for chunk in response.iter_content(chunk_size = 1):
                if chunk:
                    for chunk_part in chunk:
                        chunk_part = bytearray([chunk_part])
                        if chunk_part == b'\n':
                            try:
                                line = line_buffer.decode('utf-8')
                            except UnicodeDecodeError as err:
                                exception = MastodonMalformedEventError("Malformed UTF-8")
                                self.on_abort(exception)
                                six.raise_from(
                                    exception,
                                    err
                                )
                            if line == '':
                                self._dispatch(event)
                                event = {}
                            else:
                                event = self._parse_line(line, event)
                            line_buffer = bytearray()
                        else:
                            line_buffer.extend(chunk_part)
        except ChunkedEncodingError as err:
            exception = MastodonNetworkError("Server ceased communication.")
            self.on_abort(exception)
            six.raise_from(
                exception,
                err
            )
        except MastodonReadTimeout as err:
            exception = MastodonReadTimeout("Timed out while reading from server."),
            self.on_abort(exception)
            six.raise_from(
                exception,
                err
            )
1102349
function parseHttpBody(req, cb) {
	// check for multipart streams that can contain file uploads

	var contentType = req.headers['content-type'];
	var m = contentType && contentType.match(/^multipart\/form-data; boundary=(.+)$/);

	if (m && m[1]) {
		parseMultipart(req, m[1], cb);
	} else {
		parseSinglepart(req, cb);
	}
}
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 ]);
  }
235788
def parse(self, stream, media_type=None, parser_context=None):
        
        parser_context = parser_context or {}
        request = parser_context['request']
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        meta = request.META.copy()
        meta['CONTENT_TYPE'] = media_type
        upload_handlers = request.upload_handlers

        try:
            parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
            data, files = parser.parse()
            return DataAndFiles(data, files)
        except MultiPartParserError as exc:
            raise ParseError('Multipart form parse error - %s' % six.text_type(exc))
1175473
function responder(request, response, next) {
  response.writeHead(200, 'OK', {
    'Content-Type': 'application/javascript'
  });
  response.end(jsContent);
  if (next) next();
}
1161990
function streamToValue (response, callback) {
  pump(
    response,
    concat((data) => callback(null, data)),
    (err) => {
      if (err) {
        callback(err)
      }
    })
}
318839
def process_response(self, request, response):
        """"""

        # For debug only.
        if not settings.DEBUG:
            return response

        # Check for responses where the data can't be inserted.
        content_encoding = response.get('Content-Encoding', '')
        content_type = response.get('Content-Type', '').split(';')[0]
        if any((getattr(response, 'streaming', False),
                'gzip' in content_encoding,
                content_type not in _HTML_TYPES)):
            return response

        content = force_text(response.content, encoding=settings.DEFAULT_CHARSET)

        pattern = re.escape('</body>')
        bits = re.split(pattern, content, flags=re.IGNORECASE)

        if len(bits) > 1:
            bits[-2] += debug_payload(request, response, self.view_data)
            response.content = "</body>".join(bits)
            if response.get('Content-Length', None):
                response['Content-Length'] = len(response.content)

        return response
880363
function onResponse(type, pRes) {
    contentTypes[type] = pRes.headers['content-type'].split(';')[0];
    responses[type]    = pRes;

    //
    // If we have both a public and a private
    // response.
    //
    if (responses.public && responses.private) {
      if (contentTypes.public === contentTypes.private) {
        return self.merge.handlers[contentTypes.public](req, res, responses);
      }

      res.writeHead(500, { 'content-type': 'text/plain' });
      res.end('Content-Type mismatch: ' + JSON.stringify(contentTypes));
    }
  }
714098
function onFileReady(err, data) {
    if (err) {
      if (onDone) onDone(err)
      else console.error('>>>' + err);
      return;
    }

    var fileContent = data.toString();

    var msg = {
      text:    fileContent,
      mode:    flavor,
      context: context
    };

    var jsonMsg = JSON.stringify(msg);

    var options = {
      method: 'POST',
      preambleCRLF: true,
      postambleCRLF: true,
      uri: 'https://api.github.com/markdown',
      'content-type': 'application/json',
      headers: {
        'User-Agent' : userName
      },
      body: jsonMsg
    };

    //=======================================================
    // Call the Github Markdown API to parse the file content
    //=======================================================
    request(options, handleResponse.bind(this));

    //======================================================
    // Enhance the output of the Github Markdown API with
    // optional header or trailer.
    //======================================================
    function handleResponse(err, response, body) {
      if (this.debug) console.error('>>>handling response...');
      if (err) {
        if (onDone) onDone(err)
        else console.error('>>>upload to github failed: ', err);
        return;
      }

      if (stylesheet || title) {
        if (titleText == null) titleText = fileName;
        this.cat('<!DOCTYPE html>\n' +
                 '<html>\n' +
                 '<head>\n' +
                 '  <title>' + titleText + '</title>\n' +
                 '  <link rel="stylesheet" href="' + stylesheet + '">\n' +
                 '</head>\n' +
                 '<body>\n' );
      }

      this.cat(body);
      this.cat('\n');

      if (stylesheet || title) {
        this.cat( '</body>\n</html>\n' );
      }

      if (this.debug) console.error('>>>finished getting code');
      this.done = true;
      if (onDone) onDone();
    } // end handleResponse
  }
521766
function parseResponse(xhr){
    var parsed;
    var self = this;
    if (window.karma || window.parent.karma){
        // #]*§ WTF!!
        LOG.info('TESTING MODE');
        xhr.responseType = self.options.responseType;
    }                        
    LOG.log('responseType in readyState ', xhr.responseType);                                                                                
    if (xhr.responseType === 'json' || xhr.responseType === 'arraybuffer'){
        LOG.log('JSON CASE!', xhr.response);                        
        parsed = xhr.response;
    } else if (xhr.responseType === 'document'){
        LOG.log('DOCUMENT CASE!', xhr.responseXML);
        parsed = xhr.responseXML;
    } else if (xhr.responseType === 'text' || xhr.responseType === ''){
        LOG.log('TEXT CASE!');                
        parsed = xhr.responseText;
    } else {
        LOG.log('DEFAULT CASE!', xhr.responseText);
        parsed = xhr.responseText;
    }
    
    return [parsed, xhr.status, xhr];
}
484013
function examineEvent(target, event) {
        if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) {
            var fileId = spec.templating.getFileId(target),
                status = spec.onGetUploadStatus(fileId);

            // We only allow users to change filenames of files that have been submitted but not yet uploaded.
            if (status === qq.status.SUBMITTED) {
                spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
                qq.preventDefault(event);

                inheritedInternalApi.handleFilenameEdit(fileId, target, true);
            }
        }
    }
1171508
def file_response(data: Union[bytes, str],  # HttpResponse encodes str if req'd
                  content_type: str,
                  filename: str) -> HttpResponse:
    
    response = HttpResponse(data, content_type=content_type)
    add_download_filename(response, filename)
    return response