Copy from tornado.web.StaticFileHandler
429904
def write_file(self, file_path, mime_type=None):
        
        if not os.path.exists(file_path):
            raise HTTPError(404)
        if not os.path.isfile(file_path):
            raise HTTPError(403, "%s is not a file", file_path)

        stat_result = os.stat(file_path)
        modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])

        self.set_header("Last-Modified", modified)

        if not mime_type:
            mime_type, _encoding = mimetypes.guess_type(file_path)
        if mime_type:
            self.set_header("Content-Type", mime_type)

        # Check the If-Modified-Since, and don't send the result if the
        # content has not been modified
        ims_value = self.request.headers.get("If-Modified-Since")
        if ims_value is not None:
            date_tuple = email.utils.parsedate(ims_value)
            if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
            if if_since >= modified:
                self.set_status(304)
                return

        with open(file_path, "rb") as file:
            data = file.read()
            hasher = hashlib.sha1()
            hasher.update(data)
            self.set_header("Etag", '"%s"' % hasher.hexdigest())
            self.write(data)
1155491
function copyReadmeFiles() {

    const resolvedSrcReadmePaths = path.resolve(rootDir, srcReadmePaths);

    dryRun ? console.log(`In ${destDir}, this script would...`) : console.log(`In ${destDir}...`);

    fs.readdir('packages', (err, files) => {
        totalDocsCount = files.length;
    });

    createDirectory(destDir);
    glob(resolvedSrcReadmePaths, {realpath:true}, function(error, srcFiles) {
        
        srcFiles.forEach((srcReadmePath) => {    
            createDestReadme(srcReadmePath);
            const srcDirPath = path.dirname(srcReadmePath);
            const lastSrcDir = srcDirPath.split(path.sep).pop();
            sidebarEntries.push(`en/packages/${lastSrcDir}/index`);
        });

        console.log(chalk.green(`${updatedDocsCount} of ${totalDocsCount} package readme.md files updated`));
        updateSidebar();
       
    });

}
960426
static void copyFromWarToFolder(VirtualFile virtualFileOrFolder, File targetFolder) throws IOException {
        if (virtualFileOrFolder.isDirectory() && !virtualFileOrFolder.getName().contains(".")) {
            if (targetFolder.getName().equalsIgnoreCase(virtualFileOrFolder.getName())) {
                for (VirtualFile innerFileOrFolder : virtualFileOrFolder.getChildren()) {
                    copyFromWarToFolder(innerFileOrFolder, targetFolder);
                }
            } else {
                File innerTargetFolder = new File(targetFolder, virtualFileOrFolder.getName());
                innerTargetFolder.mkdir();
                for (VirtualFile innerFileOrFolder : virtualFileOrFolder.getChildren()) {
                    copyFromWarToFolder(innerFileOrFolder, innerTargetFolder);
                }
            }
        } else {
            File targetFile = new File(targetFolder, virtualFileOrFolder.getName());
            if (!targetFile.exists() || targetFile.length() != virtualFileOrFolder.getSize()) {
                FileUtils.copyURLToFile(virtualFileOrFolder.asFileURL(), targetFile);
            }
        }
    }
573581
public com.google.appengine.v1.StaticFilesHandlerOrBuilder getStaticFilesOrBuilder() {
    if (handlerTypeCase_ == 2) {
       return (com.google.appengine.v1.StaticFilesHandler) handlerType_;
    }
    return com.google.appengine.v1.StaticFilesHandler.getDefaultInstance();
  }
379932
function copyFile (src, dest, ncpOpts, callback) {
  var orchestrator = new Orchestrator();
  var parts = dest.split(path.sep);
  var fileName = parts.pop();
  var destDir = parts.join(path.sep);
  var destFile = path.resolve(destDir, fileName);
  orchestrator.add('ensureDir', function (done) {
    mkdirp(destDir, function (err) {
      done(err);
    });
  });
  orchestrator.add('copyFile', ['ensureDir'], function (done) {
    ncp(src, destFile, ncpOpts, function (err) {
      done(err);
    });
  });
  orchestrator.start('copyFile', function (err) {
    callback(err);
  });
}
572831
static void copyFileFromResources(String sourcePath, String destPath) throws IOException {
        LOGGER.entering(new Object[] { sourcePath, destPath });

        File downloadFile = new File(destPath);

        if (!downloadFile.exists()) {
            InputStream stream = JarSpawner.class.getResourceAsStream(sourcePath);
            FileUtils.copyInputStreamToFile(stream, downloadFile);
            LOGGER.fine("File copied to " + destPath);
        }
        LOGGER.exiting();
    }
802172
def run_with_tornado(self):
        
        from zengine.tornado_server.server import runserver
        runserver(self.manager.args.addr, int(self.manager.args.port))
856693
public static void performCopy(String filename, SarlConfiguration configuration) {
		if (filename.isEmpty()) {
			return;
		}

		try {
			final DocFile fromfile = DocFile.createFileForInput(configuration, filename);
			final DocPath path = DocPath.create(fromfile.getName());
			final DocFile toFile = DocFile.createFileForOutput(configuration, path);
			if (toFile.isSameFile(fromfile)) {
				return;
			}
			configuration.message.notice((SourcePosition) null,
					"doclet.Copying_File_0_To_File_1", //$NON-NLS-1$
					fromfile.toString(), path.getPath());
			toFile.copyFile(fromfile);
		} catch (IOException exc) {
			configuration.message.error((SourcePosition) null,
					"doclet.perform_copy_exception_encountered", //$NON-NLS-1$
					exc.toString());
			throw new DocletAbortException(exc);
		}
	}
418861
def download(self, project, filename, targetfilename, loadmetadata=None):
        """"""
        if loadmetadata is None: loadmetadata = self.loadmetadata
        f = clam.common.data.CLAMOutputFile(self.url + project,  filename, loadmetadata, self)
        f.copy(targetfilename)
1137586
private FilePath copyClassWorldsFile(FilePath ws, URL resource) {
        try {
            FilePath remoteClassworlds =
                    ws.createTextTempFile("classworlds", "conf", "");
            remoteClassworlds.copyFrom(resource);
            return remoteClassworlds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
1015714
public com.google.appengine.v1.StaticFilesHandler getStaticFiles() {
    if (handlerTypeCase_ == 2) {
       return (com.google.appengine.v1.StaticFilesHandler) handlerType_;
    }
    return com.google.appengine.v1.StaticFilesHandler.getDefaultInstance();
  }
792545
@Override
    public void onCopiedFrom(Item src) {
        super.onCopiedFrom(src);

        //noinspection unchecked
        TemplateDrivenMultiBranchProject<P, B> projectSrc = (TemplateDrivenMultiBranchProject<P, B>) src;

        /*
         * onLoad should have been invoked already, so there should be an
         * empty template.  Just update by XML and that's it.
         */
        try {
            template.updateByXml((Source) new StreamSource(projectSrc.getTemplate().getConfigFile().readRaw()));
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Failed to copy template from " + src.getName() + " into " + getName(), e);
        }
    }
6327
def getinputfiles(self, outputfile, loadmetadata=True, client=None,requiremetadata=False):
        """"""
        if isinstance(outputfile, CLAMOutputFile):
            outputfilename = str(outputfile).replace(os.path.join(self.projectpath,'output/'),'')
        else:
            outputfilename = outputfile
        outputtemplate, inputfiles = self[outputfilename]
        for inputfilename, inputtemplate in inputfiles.items():
            yield CLAMInputFile(self.projectpath, inputfilename, loadmetadata,client,requiremetadata), inputtemplate
1154404
@SuppressWarnings("resource")
  static void handleStaticResources(String handler, HttpServletResponse response)
      throws IOException {
    Resource resource = RESOURCES.get(handler);
    if (resource == null) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }
    if (resource.getRedirect() != null) {
      response.sendRedirect(resource.getRedirect());
      return;
    }
    response.setContentType(resource.getContentType());
    response.setHeader("Cache-Control", "public; max-age=300");
    try {
      InputStream resourceStream = MapReduceServlet.class.getResourceAsStream(
          "/com/google/appengine/tools/mapreduce/" + resource.getFilename());
      if (resourceStream == null) {
        resourceStream = MapReduceServlet.class.getResourceAsStream(
            "/third_party/java_src/appengine_mapreduce2/static/" + resource.getFilename());
      }
      if (resourceStream == null) {
        throw new RuntimeException("Missing MapReduce static file " + resource.getFilename());
      }
      OutputStream responseStream = response.getOutputStream();
      byte[] buffer = new byte[1024];
      while (true) {
        int bytesRead = resourceStream.read(buffer);
        if (bytesRead < 0) {
          break;
        }
        responseStream.write(buffer, 0, bytesRead);
      }
      responseStream.flush();
    } catch (IOException e) {
      throw new RuntimeException("Couldn't read static file for MapReduce library", e);
    }
  }
383869
private void copyObject(WebContext ctx, Bucket bucket, String id, String copy) throws IOException {
        StoredObject object = bucket.getObject(id);
        if (!copy.contains(PATH_DELIMITER)) {
            signalObjectError(ctx, HttpResponseStatus.BAD_REQUEST, "Source must contain '/'");
            return;
        }
        String srcBucketName = copy.substring(1, copy.lastIndexOf(PATH_DELIMITER));
        String srcId = copy.substring(copy.lastIndexOf(PATH_DELIMITER) + 1);
        Bucket srcBucket = storage.getBucket(srcBucketName);
        if (!srcBucket.exists()) {
            signalObjectError(ctx, HttpResponseStatus.BAD_REQUEST, "Source bucket does not exist");
            return;
        }
        StoredObject src = srcBucket.getObject(srcId);
        if (!src.exists()) {
            signalObjectError(ctx, HttpResponseStatus.BAD_REQUEST, "Source object does not exist");
            return;
        }
        Files.copy(src.getFile(), object.getFile());
        if (src.getPropertiesFile().exists()) {
            Files.copy(src.getPropertiesFile(), object.getPropertiesFile());
        }
        HashCode hash = Files.hash(object.getFile(), Hashing.md5());
        String etag = BaseEncoding.base16().encode(hash.asBytes());

        XMLStructuredOutput structuredOutput = ctx.respondWith().addHeader(HTTP_HEADER_NAME_ETAG, etag(etag)).xml();
        structuredOutput.beginOutput("CopyObjectResult");
        structuredOutput.beginObject("LastModified");
        structuredOutput.text(RFC822_INSTANT.format(object.getLastModifiedInstant()));
        structuredOutput.endObject();
        structuredOutput.beginObject(HTTP_HEADER_NAME_ETAG);
        structuredOutput.text(etag(etag));
        structuredOutput.endObject();
        structuredOutput.endOutput();
        signalObjectSuccess(ctx);
    }
1003915
private void copyScaffolding(File targetFile) throws IOException {
    String resourcePrefix = "com/carrotsearch/ant/tasks/junit4/templates/json/";

    File parent = targetFile.getParentFile();

    // Handle index.html substitutitons.
    ClassLoader cl = this.getClass().getClassLoader();
    String index = 
        Resources.toString(
            cl.getResource(resourcePrefix + "index.html"), Charsets.UTF_8);
    index = index.replaceAll(Pattern.quote("tests-output.jsonp"),
        removeExtension(targetFile.getName()) + ".jsonp");

    Files.write(index.getBytes(Charsets.UTF_8), targetFile);
    
    // Copy over the remaining files. This is hard coded but scanning a JAR seems like an overkill.
    String [] resources = {
        "js/jquery-1.7.1.min.js",
        "js/script.js",
        "js/jquery.pathchange.js",
        "img/pass.png",
        "img/error.png",
        "img/stderr.png",
        "img/arrow-up.png",
        "img/stdout.png",
        "img/indicator.png",
        "img/failure.png",
        "img/omited.png",
        "img/arrow-down.png",
        "css/style.css"
    };

    for (String resource : resources) {
      File target = new File(parent, resource);
      if (!target.getParentFile().exists()) {
        target.getParentFile().mkdirs();
      }
      URL res = cl.getResource(resourcePrefix + resource);
      if (res == null) {
        throw new IOException("Could not find the required report resource: " + resource);
      }
      Files.write(Resources.toByteArray(res), target); 
    }
  }
544906
def statichttp(container = None):
    ""
    def decorator(func):
        @functools.wraps(func)
        def handler(event):
            return _handler(container, event, func)
        if hasattr(func, '__self__'):
            handler.__self__ = func.__self__
        return handler
    return decorator