/*
the bread and butter
- parse the request, load the file, resolve the content
489732
async function(request, modules_root, options){
        /*
            extract request details for this request
        */
        var request_details = await this.utils.promise_to_decompose_request(
            request, // a relative path, absolute path, or module name
            modules_root, // defines where to look for modules
            options.relative_path_root, // defines where the relative path should start from
            options.search_for_dependencies // modules can define to not search for dependencies on their own, overriding the user
        );

        /*
            load dependencies into cache before loading the main file
                - recursive operation
        */
        if(request_details.search_for_dependencies){
            // this is the main (and most obvious) downside to synchronous_require; waiting until all dependencies load.
            var dependency_relative_path_root = request_details.path.substring(0, request_details.path.lastIndexOf("/")) + "/";
            await this.promise_dependencies_are_loaded(request_details.dependencies, dependency_relative_path_root, request_details.search_for_dependencies); // wait untill dependencies are loaded
        }

        /*
            retreive content with loader functions
                - handles scoping and env setup of js files (retreives content based on CommonJS exports)
                - supports js, css, html, json, txt, etc
        */
        var content = await this.utils.loader_functions[request_details.type](request_details.path);

        /*
            resolve with content
        */
        return content;
    }
1270529
function handleUpdateFile(response) {

        var path = response.path,
            type = response.type,
            $deferredHints = getPendingRequest(path, OFFSET_ZERO, type);

        if ($deferredHints) {
            $deferredHints.resolve();
        }
    }
1025363
function load(root, path, callback, errback) {
		resolve(root, path, function (realPath, contents) {
			process(realPath, contents, callback, errback);
		}, errback);
	}
470068
function parse_request(){
		parent::parse_request();
		
		if (isset($_GET["pos"])){
			if (!$this->dload)	//not critical, so just write a log message
				LogMaster::log("Dyn loading request received, but server side was not configured to process dyn. loading. ");
			else
				$this->request->set_limit($_GET["pos"],$this->dload);
		}
			
		if (isset($_GET["mask"]))
			$this->request->set_filter($this->config->text[0]["db_name"],$_GET["mask"]."%","LIKE");
			
		LogMaster::log($this->request);
	}
1076067
function loadpage(path, vars, user, newvalue) {
  // __dirname = path.resolve(); // If in the REPL
  if(typeof vars != "object") vars = {};
  var serverFileContent = readServerFile();
  var env = {
      googleClientId: googleClientId,
      vars: vars,
      user: toLeoQuery(user || {}),
      defaultOptions: toLeoQuery(defaultOptions),
      path: path,
      fileOperations: [] };
  
  if(typeof newvalue == "undefined") {
    return [evaluateToHtml(path, env, serverFileContent), vars];
  } else { // We update the page and re-render it.
    var newVal = sns.nativeToVal(newvalue);
    console.log("Started to update...");
    var result = sns.objEnv.string.update(env)(serverFileContent)(newVal);
    console.log("Update finished (first solution)");
    if(result.ctor == "Ok") {
      var allSolutions = result._0;
      // Instead of iterating through all the solutions, just detect if there is an ambiguity.
      var solution = getOneSolution(path, serverFileContent, allSolutions);
      if(solution === false) {
        return [{ctor: "Err", _0: "Empty list of solutions"}];
      } else {
        console.log("Checking for ambiguities");
        var allSolutionsTail = sns.lazyList.tail(allSolutions);
        var solution2 = getOneSolution(path, serverFileContent, allSolutionsTail);
        if(solution2 === false) { // No ambiguity, we can immediately process the change.
          console.log("No ambiguity");
          return solution;
        } else {
          console.log("Ambiguity found");
          var solutionKey = uniqueKey();
          var cachedSolution = {
              timestamp: (+ new Date()),
              computed: [solution, solution2],
              remaining: allSolutionsTail,
              path: path,
              serverFileContent: serverFileContent
          }
          cachedSolutions[solutionKey] = cachedSolution;
          return solution.concat(solutionKey);
        }
      }
    } else return [result];
  }
}
543050
function load() {
  if (process.env.BABEL_DISABLE_CACHE) return;

  process.on("exit", save);
  process.nextTick(save);

  if (!_pathExists2["default"].sync(FILENAME)) return;

  try {
    data = JSON.parse(_fs2["default"].readFileSync(FILENAME));
  } catch (err) {
    return;
  }
}
139882
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
            throws IOException {
        // Validate the requested file ------------------------------------------------------------

        // Get requested file by path info.
        String requestedFile = request.getPathInfo();
        if (logger.isDebugEnabled()) {
            logger.debug("Requested path:" + requestedFile);
        }

        // Check if file is actually supplied to the request URL.
        if (requestedFile == null) {
            logger.debug("No file requested, return 404.");
            // Do your thing if the file is not supplied to the request URL.
            // Throw an exception, or send 404, or show default/warning page, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        Configuration rootConfiguration = (Configuration) request.getServletContext().getAttribute(Configuration.class.getName());
        Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings");

        String basePath = runtimeConfiguration.getString("cache-path");
        int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE);
        long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME);

        // URL-decode the file name (might contain spaces and on) and prepare file object.
        String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8");
        File file = new File(basePath, fDecodedPath);

        // Check if file actually exists in filesystem.
        if (!file.exists()) {
            logger.debug("Requested file not found, return 404.");
            // Do your thing if the file appears to be non-existing.
            // Throw an exception, or send 404, or show default/warning page, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // Prepare some variables. The ETag is an unique identifier of the file.
        String fileName = file.getName();
        long length = file.length();
        long lastModified = file.lastModified();
        String eTag = fileName + "_" + length + "_" + lastModified;
        long expires = System.currentTimeMillis() + expireTime;

        // Validate request headers for caching ---------------------------------------------------
        // If-None-Match header should contain "*" or ETag. If so, then return 304.
        String ifNoneMatch = request.getHeader("If-None-Match");
        if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
            logger.debug("IfNoneMatch/Etag not matching, return 304.");
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", eTag); // Required in 304.
            response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
            return;
        }

        // If-Modified-Since header should be greater than LastModified. If so, then return 304.
        // This header is ignored if any If-None-Match header is specified.
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
            logger.debug("IfModifiedSince not matching, return 304.");
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", eTag); // Required in 304.
            response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
            return;
        }

        // Validate request headers for resume ----------------------------------------------------
        // If-Match header should contain "*" or ETag. If not, then return 412.
        String ifMatch = request.getHeader("If-Match");
        if (ifMatch != null && !matches(ifMatch, eTag)) {
            logger.debug("ifMatch not matching, return 412.");
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }

        // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
        long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
        if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
            logger.debug("ifUnmodifiedSince not matching, return 412.");
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }

        // Prepare and initialize response --------------------------------------------------------
        // Get content type by file name and content disposition.
        String contentType = getServletContext().getMimeType(fileName);
        String disposition = "inline";

        // If content type is unknown, then set the default value.
        // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
        // To add new content types, add new mime-mapping entry in web.xml.
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        // If content type is text, expand content type with the one and right character encoding.
        if (contentType.startsWith("text")) {
            contentType += ";charset=UTF-8";
        } // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        else if (!contentType.startsWith("image")) {
            String accept = request.getHeader("Accept");
            disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
        }

        // Initialize response.
        response.reset();
        response.setBufferSize(bufferSize);
        response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("ETag", eTag);
        response.setDateHeader("Last-Modified", lastModified);
        response.setDateHeader("Expires", expires);

        // Send requested file (part(s)) to client ------------------------------------------------
        // Prepare streams.
        FileInputStream input = null;
        OutputStream output = null;

        if (content) {
            logger.debug("Content requested,streaming.");
            // Open streams.
            input = new FileInputStream(file);
            output = response.getOutputStream();
            long streamed = stream(input, output, bufferSize);
            if (logger.isDebugEnabled()) {
                logger.debug("Bytes streamed:" + streamed);
            }
        }

    }
488250
function parseExternalLink(elem) {
    var path = elem.href;
    elem.setAttribute('data-parsed', true);
    var rawFile = new XMLHttpRequest();
    rawFile.open('GET', path, true);
    rawFile.onreadystatechange = function processStylesFile() {
      if (rawFile.readyState === 4 && (rawFile.status === 200 || rawFile.status === 0)) {
        var styleEl = document.createElement('style');
        document.head.appendChild(styleEl);

        styleEl.innerText = window.cssThemeService(rawFile.responseText);
      }
    };
    rawFile.send(null);
  }
219067
function promiseReadFile(path, encoding = 'utf-8') {
  return new Promise((resolve, reject) => {
    fs.readFile(path, encoding, (err, content) => {
      if (err) reject(err);

      resolve({
        path,
        fileName: path.split('/').pop(),
        content
      });
    });
  });
}
443803
function () {
    if (this.loadTypeSet || this.loadType === LoaderBase.typeText) {
      this.content = this.xhr.response || this.xhr.responseText;
    } else {
      switch (this.loadType) {

        case LoaderBase.typeArraybuffer:

          if (ArrayBuffer) {
            this.content = stringToArrayBuffer(this.xhr.response);
          } else {
            throw new Error('This browser does not support ArrayBuffer');
          }
          break;

        case LoaderBase.typeBlob:
        case LoaderBase.typeVideo:
        case LoaderBase.typeAudio:

          if (Blob) {
            if (!this.fileMeta) {
              this.fileMeta = new FileMeta();
            }

            if (this.fileMeta.mime === null) {
              this.fileMeta.mime = getMimeFromURL(this.url);
            }

            this.content = new Blob([ stringToArrayBuffer(this.xhr.response) ], { type: this.fileMeta.mime });
          } else {
            throw new Error('This browser does not support Blob');
          }
          break;

        case LoaderBase.typeJSON:

          this.content = JSON.parse(this.xhr.response);
          break;

        case LoaderBase.typeDocument:

          // this needs some work pretty sure there's a better way to handle this
          this.content = this.xhr.response;
          break;

      }
    }
  }
318010
function writeResolved(info, res, statusCode){
    statusCode = statusCode || 200;
    if (info.type === 'json'){

      res.setHeader('Content-Type', 'application/json');
      res.writeHead(statusCode);
      res.end(JSON.stringify(info.data));

      return true;
    } else if (info.type === 'file') {
      // content || assets
      sendFile(res, info.filename);

      return true;
    } else if (info.type === 'files') {
      // content with mutiple files
      if (info.files.length === 1){
        //res.setHeader('Content-Type', mime.lookup( info.files[0].filename) );
        sendFile(res, info.files[0].filename);
        return true;
      } else {
        var bpath = extractBasepath(info.files.map(function(f){ return f.filename; }));

        var relfiles = info.files.map(function(f){
          var fname = f.filename.replace(/\\/ig, '/');
          return fname.replace(bpath, '');
        });

        var htmls = relfiles.filter(function(rf){
          return (/\.html$/i).test(rf);
        });

        // the index HTML
        var ihtml = htmls.filter(function(h){ 
          return /index.htm(l)?/ig.test(h);
        });

        var idxhtml = ihtml.length > 0 ? ihtml[0] : undefined;

        if ( idxhtml === undefined){
          // index.html doesn't exists 
          // any html
          idxhtml = (htmls.length > 0 ? htmls[0] : undefined);
        }

        var route = '/content/' + info.uid;
        if (app.cacheContent[route] === undefined){
          app.cacheContent[route] = {
            path: bpath,
            index: idxhtml
          };
        }
        var r = route;
        var item = app.cacheContent[route];
        if (item.index !== undefined){
          r += '/' + item.index;
        }
        
        res.redirect(r);
        //res.sendFile(idxhtml, {root: bpath });
      }

      return true;
    }

    function sendFile(res, filename){
      var fname = path.basename(filename);
      fname = encodeURIComponent(fname);
      res.setHeader('Content-disposition', 'inline; filename="' + fname + '"');
      res.setHeader('Content-Type', mime.lookup(filename));

      res.sendFile(filename);
    }

    return false;

    function extractBasepath(entries) {

      var dirs = entries.map(function(e){ 
        return path.dirname(e); 
      });

      var sdirs = dirs.map(function(d){ 
        return d.split('\\');
      });

      var idx = 0;
      var curr;
      var root = '';
      var eq;

      var haveFunc = function(sd){ 
        return sd.length > idx; 
      };

      var eqFunc = function(i){
        return curr === i;
      };

      var eqmapFunc = function(a){ 
        return a[idx]; 
      };

      do {

        curr = sdirs[0][idx];

        var have = _.all(sdirs, haveFunc);

        eq = have;
        if (have === true){
          eq = _.all(sdirs.map(eqmapFunc), eqFunc);
        }

        if(eq) {
          root += curr + '/';
        }

        idx++;

      } while(eq === true);

      return root;
    }
  }
11215
function makeRequest(title, cacheHitExpected, next) {
  var start = Date.now();

  request({
    url: 'http://localhost:1337/',
    encoding: null
  }, function(err, data, body) {
    var time = Date.now() - start;

    var receivedImage = new Buffer(body, 'binary');

    console.log(title);
    console.log('  status:', data.statusCode);
    console.log('  sent image length:', IMAGE.length);
    console.log('  received image length  :', receivedImage.length);
    console.log('  time  :', time);
    
    common.verify(function() {
      common.shouldEquals(IMAGE, receivedImage);
    });

    console.log();

    next();
  });
}
924190
def parse(self, request):
        
        if request.method in ('POST', 'PUT', 'PATCH'):
            content_type = self.determine_content(request)
            if content_type:
                split = content_type.split(';', 1)
                if len(split) > 1:
                    content_type = split[0]
                content_type = content_type.strip()

            parser = self._meta.parsers_dict.get(
                content_type, self._meta.default_parser)
            data = parser(self).parse(request)
            return dict() if isinstance(data, basestring) else data
        return dict()
1208598
@Override
    public FileModel resolvePayload(GraphRewrite event, EvaluationContext context, WindupVertexFrame payload)
    {
        checkVariableName(event, context);
        if (payload instanceof FileReferenceModel)
        {
            return ((FileReferenceModel) payload).getFile();
        }
        if (payload instanceof FileModel)
        {
            return (FileModel) payload;
        }
        return null;
    }
487258
function parseBody()
    {
        $result = array(
            'data'=>array(),
            'files'=>array(),
            );

         // read incoming data
        $input = Instance::get('BODY');

        // grab multipart boundary from content type header
        preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches);

        // content type is probably regular form-encoded
        if (!count($matches)) {
            // we expect regular puts to containt a query string containing data
            parse_str($input, $result['data']);
        } else {
            $boundary = $matches[1];
            // split content by boundary and get rid of last -- element
            $a_blocks = preg_split("/-+$boundary/", $input);
            array_pop($a_blocks);

            // loop data blocks
            foreach ($a_blocks as $id => $block) {
                if (empty($block))
                    continue;
                // you'll have to var_dump $block to understand this and maybe replace \n or \r with a visibile char
                // parse uploaded files
                if (strpos($block, 'application/octet-stream') !== FALSE) {
                    // match "name", then everything after "stream" (optional) except for prepending newlines
                    // preg_match("/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s", $block, $matches);
                    // $a_data['files'][$matches[1]] = isset($matches[2])?$matches[2]:null;
                }
                // parse all other fields
                else {
                    // match "name" and optional value in between newline sequences
                    if (strpos($block, 'filename="')===false) {
                        preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
                        $result['data'][$matches[1]] = isset($matches[2])?$matches[2]:null;
                    } else {
                        preg_match('/; name=\"([^\"]*)\"; filename=\"([^\"]*)\"\s*Content\-Type: ([\w\/]+)[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
                        $result['files'][$matches[1]] = array(
                            'name' => $matches[2],
                            'type' => $matches[3],
                            'tmp_name' => tempnam( ini_get( 'upload_tmp_dir' ), 'php' ),
                            'error' => UPLOAD_ERR_OK,
                            'size' => 0);
                        $result['files'][$matches[1]]['size'] = file_put_contents($result['files'][$matches[1]]['tmp_name'], $matches[4]);
                        $result['files'][$matches[1]]['size']!==false || $result['files'][$matches[1]]['error'] = UPLOAD_ERR_CANT_WRITE;
                    }
                }
            }
        }

        return $result;
    }
1175971
function processGithubFile (options, callback) {
  var item = options.item
  var key = options.key
  var json = options.json

  function respond (content) {
    if (isFeatureCollection(content)) {
      content.name = key
      content.updated_at = json.updated_at
      return content
    }
    return false
  }

  if (item.truncated) {
    return request({
      url: item.raw_url
    }, function (err, content) {
      if (err) return callback(err)

      callback(null, respond(content))
    })
  }

  try {
    var content = JSON.parse(item.content)
  } catch (e) {
    var msg = 'could not parse file contents of ' + key + ': ' + e.message
    return callback(new Error(msg))
  }

  callback(null, respond(content))
}
951106
function (file) {
      return $.Deferred(function (deferred) {
        $.extend(new FileReader(), {
          onload: function (e) {
            var dataURL = e.target.result;
            deferred.resolve(dataURL);
          },
          onerror: function () {
            deferred.reject(this);
          }
        }).readAsDataURL(file);
      }).promise();
    }