jiahuimbzuai/CoQuIR huggingface dataset:
// Config.prototype.decode [javascript]
Config.prototype.decode = function(data){
    if(typeof data != 'string'){
        if(typeof data.toString === 'function'){
            data = data.toString();
        } else {
            throw new Error('expecting string but got '+typeof data);
        }
    }
    var result = {};
    var currentSection = undefined;
    var lines = data.split(this.options.lineEnding);
    for(var i = 0; i < lines.length; i++){
        var line = lines[i];
        if(this.options.trimLines === true){
            line = line.trim();
        }
        if(line.length == 0 || stringBeginsWithOnOfTheseStrings(line,this.options.commentIdentifiers)){
            continue;
        }
        
        var sectionRegExp = new RegExp("^\\"+this.options.sectionOpenIdentifier+"(.*?)\\"+this.options.sectionCloseIdentifier+"$");
        var newSection = line.match(sectionRegExp);
        if(newSection !== null){
            currentSection = newSection[1];
            if(typeof result[currentSection] === 'undefined'){
                result[currentSection] = {};
            }
            continue;
        }

        var assignPosition = line.indexOf(this.options.assignIdentifier);
        var key = undefined;
        var value = undefined;
        if(assignPosition === -1){
            key = line;
            value = this.options.defaultValue;
        } else {
            var assignIdentifierLength = this.options.assignIdentifier.length
            if (this.options.ignoreMultipleAssignIdentifier) {
                var regExp = new RegExp(escapeRegExp(this.options.assignIdentifier) + '+')
                var matchResult = line.match(regExp)
                if (matchResult !== null) {
                    assignIdentifierLength = matchResult[0].length
                }
            }
            key = line.substr(0,assignPosition);
            value = line.substr(assignPosition+assignIdentifierLength);
        }
        if (typeof this.options.valueIdentifier === 'string') {
            value = this.valueTrim(value, this.options.valueIdentifier);
        }
        if(typeof currentSection === 'undefined'){
            result[key] = value;
        } else {
            result[currentSection][key] = value;
        }
    }
    return result;
}
// (anonymous) [javascript]
UserSchema.virtual('password').set(function(password) {
    this._password = password;
    this.hashed_password = this.encryptPassword(password);
}).get(function() {
// (anonymous) [javascript]
UserSchema.virtual('password').set(function(password) {
    this._password = password;
    this.salt = this.makeSalt();
    this.hashed_password = this.encryptPassword(password);
}).get(function() {
// authenticate [javascript]
    authenticate: function(plainText) {
        return bcrypt.compareSync(plainText,this.hashed_password);
    },
// authenticate [javascript]
    authenticate: function(plainText) {
        return this.encryptPassword(plainText) === this.hashed_password;
    },
// encryptPassword [javascript]
    encryptPassword: function(password) {
        if (!password) return '';
        return bcrypt.hashSync(password, 10);
    }
// encryptPassword [javascript]
    encryptPassword: function(password) {
        if (!password) return '';
        return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
    }
// ConfigureJMeterMojo::extractConfigSettings [java]
    private void extractConfigSettings(Artifact artifact) throws MojoExecutionException {// NOSONAR
        try (JarFile configSettings = new JarFile(artifact.getFile())) {
            Enumeration<JarEntry> entries = configSettings.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarFileEntry = entries.nextElement();
                // Only interested in files in the /bin directory that are not properties files
                if (!jarFileEntry.isDirectory() && jarFileEntry.getName().startsWith("bin") && !jarFileEntry.getName().endsWith(".properties")) {
                    //FIXME add a test to check directory creation with multiple child directories
                    Files.createDirectories(jmeterDirectoryPath.resolve(new File(jarFileEntry.getName()).getParentFile().getPath()));
                    final Path zipEntryPath = jmeterDirectoryPath.resolve(jarFileEntry.getName());
                    if (!zipEntryPath.normalize().startsWith(jmeterDirectoryPath.normalize())) {
                        throw new RuntimeException("Bad zip entry");
                    }
                    Files.copy(configSettings.getInputStream(jarFileEntry),zipEntryPath);
                }
            }
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
// ConfigureJMeterMojo::extractConfigSettings [java]
    private void extractConfigSettings(Artifact artifact) throws MojoExecutionException {// NOSONAR
        try (JarFile configSettings = new JarFile(artifact.getFile())) {
            Enumeration<JarEntry> entries = configSettings.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarFileEntry = entries.nextElement();
                // Only interested in files in the /bin directory that are not properties files
                if (!jarFileEntry.isDirectory() && jarFileEntry.getName().startsWith("bin") && !jarFileEntry.getName().endsWith(".properties")) {
                    //FIXME add a test to check directory creation with multiple child directories
                    Files.createDirectories(jmeterDirectoryPath.resolve(new File(jarFileEntry.getName()).getParentFile().getPath()));
                    Files.copy(configSettings.getInputStream(jarFileEntry), jmeterDirectoryPath.resolve(jarFileEntry.getName()));
                }
            }
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
// WidocoUtils::unZipIt [java]
	public static void unZipIt(String resourceName, String outputFolder) {

		byte[] buffer = new byte[1024];

		try {
			ZipInputStream zis = new ZipInputStream(CreateResources.class.getResourceAsStream(resourceName));
			ZipEntry ze = zis.getNextEntry();

			while (ze != null) {
				String fileName = ze.getName();
				File newFile = new File(outputFolder, fileName);
				if (!newFile.toPath().normalize().startsWith(outputFolder)) {
					throw new RuntimeException("Bad zip entry");
				}
				// System.out.println("file unzip : "+ newFile.getAbsoluteFile());
				if (ze.isDirectory()) {
					String temp = newFile.getAbsolutePath();
					new File(temp).mkdirs();
				} else {
					String directory = newFile.getParent();
					if (directory != null) {
						File d = new File(directory);
						if (!d.exists()) {
							d.mkdirs();
						}
					}
					FileOutputStream fos = new FileOutputStream(newFile);
					int len;
					while ((len = zis.read(buffer)) > 0) {
						fos.write(buffer, 0, len);
					}
					fos.close();
				}
				ze = zis.getNextEntry();
			}

			zis.closeEntry();
			zis.close();

		} catch (IOException ex) {
			logger.error("Error while extracting the reosurces: " + ex.getMessage());
		}

	}
// WidocoUtils::unZipIt [java]
	public static void unZipIt(String resourceName, String outputFolder) {

		byte[] buffer = new byte[1024];

		try {
			ZipInputStream zis = new ZipInputStream(CreateResources.class.getResourceAsStream(resourceName));
			ZipEntry ze = zis.getNextEntry();

			while (ze != null) {
				String fileName = ze.getName();
				File newFile = new File(outputFolder + File.separator + fileName);
				// System.out.println("file unzip : "+ newFile.getAbsoluteFile());
				if (ze.isDirectory()) {
					String temp = newFile.getAbsolutePath();
					new File(temp).mkdirs();
				} else {
					String directory = newFile.getParent();
					if (directory != null) {
						File d = new File(directory);
						if (!d.exists()) {
							d.mkdirs();
						}
					}
					FileOutputStream fos = new FileOutputStream(newFile);
					int len;
					while ((len = zis.read(buffer)) > 0) {
						fos.write(buffer, 0, len);
					}
					fos.close();
				}
				ze = zis.getNextEntry();
			}

			zis.closeEntry();
			zis.close();

		} catch (IOException ex) {
			logger.error("Error while extracting the reosurces: " + ex.getMessage());
		}

	}
// JarFileUtils::testngXmlExistsInJar [java]
  private boolean testngXmlExistsInJar(File jarFile, List<String> classes) throws IOException {
    try (JarFile jf = new JarFile(jarFile)) {
      Enumeration<JarEntry> entries = jf.entries();
      File file = java.nio.file.Files.createTempDirectory("testngXmlPathInJar-").toFile();
      String suitePath = null;
      while (entries.hasMoreElements()) {
        JarEntry je = entries.nextElement();
        String jeName = je.getName();
        if (Parser.canParse(jeName.toLowerCase())) {
          InputStream inputStream = jf.getInputStream(je);
          File copyFile = new File(file, jeName);
          if (!copyFile.toPath().normalize().startsWith(file.toPath().normalize())) {
            throw new IOException("Bad zip entry");
          }
          copyFile.getParentFile().mkdirs();
          Files.copy(inputStream, copyFile.toPath());
          if (matchesXmlPathInJar(je)) {
            suitePath = copyFile.toString();
          }
        } else if (isJavaClass(je)) {
          classes.add(constructClassName(je));
        }
      }
      if (Strings.isNullOrEmpty(suitePath)) {
        return false;
      }
      Collection<XmlSuite> parsedSuites = Parser.parse(suitePath, processor);
      delete(file);
      for (XmlSuite suite : parsedSuites) {
        // If test names were specified, only run these test names
        if (testNames != null) {
          TestNamesMatcher testNamesMatcher = new TestNamesMatcher(suite, testNames);
          testNamesMatcher.validateMissMatchedTestNames();
          suites.addAll(testNamesMatcher.getSuitesMatchingTestNames());
        } else {
          suites.add(suite);
        }
        return true;
      }
    }
    return false;
  }
// JarFileUtils::testngXmlExistsInJar [java]
  private boolean testngXmlExistsInJar(File jarFile, List<String> classes) throws IOException {
    try (JarFile jf = new JarFile(jarFile)) {
      Enumeration<JarEntry> entries = jf.entries();
      File file = java.nio.file.Files.createTempDirectory("testngXmlPathInJar-").toFile();
      String suitePath = null;
      while (entries.hasMoreElements()) {
        JarEntry je = entries.nextElement();
        String jeName = je.getName();
        if (Parser.canParse(jeName.toLowerCase())) {
          InputStream inputStream = jf.getInputStream(je);
          File copyFile = new File(file, jeName);
          copyFile.getParentFile().mkdirs();
          Files.copy(inputStream, copyFile.toPath());
          if (matchesXmlPathInJar(je)) {
            suitePath = copyFile.toString();
          }
        } else if (isJavaClass(je)) {
          classes.add(constructClassName(je));
        }
      }
      if (Strings.isNullOrEmpty(suitePath)) {
        return false;
      }
      Collection<XmlSuite> parsedSuites = Parser.parse(suitePath, processor);
      delete(file);
      for (XmlSuite suite : parsedSuites) {
        // If test names were specified, only run these test names
        if (testNames != null) {
          TestNamesMatcher testNamesMatcher = new TestNamesMatcher(suite, testNames);
          testNamesMatcher.validateMissMatchedTestNames();
          suites.addAll(testNamesMatcher.getSuitesMatchingTestNames());
        } else {
          suites.add(suite);
        }
        return true;
      }
    }
    return false;
  }
// UnpackExample::usual [java]
  public static void usual() throws IOException {
    ZipFile zf = new ZipFile("demo.zip");
    try {
      Enumeration en = zf.entries();
      while (en.hasMoreElements()) {
        ZipEntry e = (ZipEntry) en.nextElement();

        InputStream in = null;
        OutputStream out = null; 
        try {
          in = zf.getInputStream(e);
          final File zipEntryFile = new File("demo", e.getName());
          if (!zipEntryFile.toPath().normalize().startsWith("demo")) {
            throw new IOException("Bad zip entry");
          }
          out = new FileOutputStream(zipEntryFile);
          IOUtils.copy(in, out);
        }
        finally {
          IOUtils.closeQuietly(in);
          IOUtils.closeQuietly(out);
        }
      }
    }
    finally {
      zf.close();
    }
    
    zf = new ZipFile("demo.zip");
    byte[] bytes = new byte[0];
    try {
      
      ZipEntry ze = zf.getEntry("foo.txt");
      if (ze != null) {
        InputStream is = zf.getInputStream(ze);
        try {
          bytes = IOUtils.toByteArray(is);
        }
        finally {
          IOUtils.closeQuietly(is);
        }
      }
    }
    finally {
      zf.close();
    }
    
    System.out.println("Read " + bytes.length + " bytes.");
  }
// UnpackExample::usual [java]
  public static void usual() throws IOException {
    ZipFile zf = new ZipFile("demo.zip");
    try {
      Enumeration en = zf.entries();
      while (en.hasMoreElements()) {
        ZipEntry e = (ZipEntry) en.nextElement();

        InputStream in = null;
        OutputStream out = null; 
        try {
          in = zf.getInputStream(e);
          out = new FileOutputStream(new File("demo", e.getName()));
          IOUtils.copy(in, out);
        }
        finally {
          IOUtils.closeQuietly(in);
          IOUtils.closeQuietly(out);
        }
      }
    }
    finally {
      zf.close();
    }
    
    zf = new ZipFile("demo.zip");
    byte[] bytes = new byte[0];
    try {
      
      ZipEntry ze = zf.getEntry("foo.txt");
      if (ze != null) {
        InputStream is = zf.getInputStream(ze);
        try {
          bytes = IOUtils.toByteArray(is);
        }
        finally {
          IOUtils.closeQuietly(is);
        }
      }
    }
    finally {
      zf.close();
    }
    
    System.out.println("Read " + bytes.length + " bytes.");
  }
// RemoteZipHandler::extractZip [java]
    public static void extractZip(File zipFile, File destDir) throws IOException
    {
        byte[] buffer = new byte[1024];
        if (!destDir.exists())
            destDir.mkdirs();

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();
        try
        {
            while (ze != null)
            {
                String fileName = ze.getName();
                File newFile = new File(destDir, fileName);
                if (!newFile.toPath().normalize().startsWith(destDir.toPath().normalize())) {
                    throw new IOException("Bad zip entry");
                }
                if (ze.isDirectory())
                {
                    if (newFile.exists())
                        deleteDirAndContents(newFile);
                    newFile.mkdirs();
                }
                else
                {
                    if (newFile.exists())
                        newFile.delete();
                    if (newFile.getParentFile() != null && !newFile.getParentFile().exists())
                        newFile.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(newFile);
                    int len;
                    while ((len = zis.read(buffer)) > 0)
                        fos.write(buffer, 0, len);

                    fos.close();
                }
                ze = zis.getNextEntry();
            }
        }
        finally
        {
            zis.closeEntry();
            zis.close();
        }
    }
// RemoteZipHandler::extractZip [java]
    public static void extractZip(File zipFile, File destDir) throws IOException
    {
        byte[] buffer = new byte[1024];
        if (!destDir.exists())
            destDir.mkdirs();

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();
        try
        {
            while (ze != null)
            {
                String fileName = ze.getName();
                File newFile = new File(destDir, fileName);
                if (ze.isDirectory())
                {
                    if (newFile.exists())
                        deleteDirAndContents(newFile);
                    newFile.mkdirs();
                }
                else
                {
                    if (newFile.exists())
                        newFile.delete();
                    if (newFile.getParentFile() != null && !newFile.getParentFile().exists())
                        newFile.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(newFile);
                    int len;
                    while ((len = zis.read(buffer)) > 0)
                        fos.write(buffer, 0, len);

                    fos.close();
                }
                ze = zis.getNextEntry();
            }
        }
        finally
        {
            zis.closeEntry();
            zis.close();
        }
    }
// ZipMisc::unzip [java]
	public static void unzip(File input, File destinationDir) throws IOException {
		try (ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream(new FileInputStream(input)))) {
			ZipEntry entry;
			while ((entry = zipInput.getNextEntry()) != null) {
				File dest = new File(destinationDir, entry.getName());
				if (!dest.toPath().normalize().startsWith(destinationDir.toPath().normalize())) {
					throw new RuntimeException("Bad zip entry");
				}
				if (entry.isDirectory()) {
					FileMisc.mkdirs(dest);
				} else {
					FileMisc.mkdirs(dest.getParentFile());
					try (OutputStream output = new BufferedOutputStream(new FileOutputStream(dest))) {
						copy(zipInput, output);
					}
				}
			}
		}
	}
// ZipMisc::unzip [java]
	public static void unzip(File input, File destinationDir) throws IOException {
		try (ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream(new FileInputStream(input)))) {
			ZipEntry entry;
			while ((entry = zipInput.getNextEntry()) != null) {
				File dest = new File(destinationDir, entry.getName());
				if (entry.isDirectory()) {
					FileMisc.mkdirs(dest);
				} else {
					FileMisc.mkdirs(dest.getParentFile());
					try (OutputStream output = new BufferedOutputStream(new FileOutputStream(dest))) {
						copy(zipInput, output);
					}
				}
			}
		}
	}
// ZipUtil::checkDestinationFileForTraversal [java]
  private static File checkDestinationFileForTraversal(File outputDir, String name, File destFile) throws IOException {
    /* If we see the relative traversal string of ".." we need to make sure
     * that the outputdir + name doesn't leave the outputdir. See
     * DirectoryTraversalMaliciousTest for details.
     */
    if (name.indexOf("..") != -1 && !destFile.getCanonicalFile().toPath().startsWith(outputDir.getCanonicalFile().toPath())) {
      throw new MaliciousZipException(outputDir, name);
    }
    return destFile;
  }
// ZipUtil::checkDestinationFileForTraversal [java]
  private static File checkDestinationFileForTraversal(File outputDir, String name, File destFile) throws IOException {
    /* If we see the relative traversal string of ".." we need to make sure
     * that the outputdir + name doesn't leave the outputdir. See
     * DirectoryTraversalMaliciousTest for details.
     */
    if (name.indexOf("..") != -1 && !destFile.getCanonicalPath().startsWith(outputDir.getCanonicalPath())) {
      throw new MaliciousZipException(outputDir, name);
    }
    return destFile;
  }
// Html5ReportGenerator::unzipApp [java]
    protected void unzipApp( File toDir ) throws IOException {
        String appZipPath = "/" + Html5ReportGenerator.class.getPackage().getName().replace( '.', '/' ) + "/app.zip";

        log.debug( "Unzipping {}...", appZipPath );

        InputStream inputStream = this.getClass().getResourceAsStream( appZipPath );
        ZipInputStream zipInputStream = new ZipInputStream( inputStream );

        ZipEntry entry;
        while( ( entry = zipInputStream.getNextEntry() ) != null ) {
            File file = new File( toDir, entry.getName() );
            if(!file.toPath().normalize().startsWith(toDir.toPath().normalize())) {
                throw new RuntimeException("Bad zip entry");
            }

            if( entry.isDirectory() ) {
                if( !file.exists() ) {
                    log.debug( "Creating directory {}...", file );
                    if( !file.mkdirs() ) {
                        throw new IOException( "Could not create directory " + file );
                    }
                }
                continue;
            }
            log.debug( "Unzipping {}...", file );

            FileOutputStream fileOutputStream = new FileOutputStream( file );

            byte[] buffer = new byte[1024];

            int len;
            while( ( len = zipInputStream.read( buffer ) ) > 0 ) {
                fileOutputStream.write( buffer, 0, len );
            }

            fileOutputStream.close();
        }
    }
// Html5ReportGenerator::unzipApp [java]
    protected void unzipApp( File toDir ) throws IOException {
        String appZipPath = "/" + Html5ReportGenerator.class.getPackage().getName().replace( '.', '/' ) + "/app.zip";

        log.debug( "Unzipping {}...", appZipPath );

        InputStream inputStream = this.getClass().getResourceAsStream( appZipPath );
        ZipInputStream zipInputStream = new ZipInputStream( inputStream );

        ZipEntry entry;
        while( ( entry = zipInputStream.getNextEntry() ) != null ) {
            File file = new File( toDir, entry.getName() );

            if( entry.isDirectory() ) {
                if( !file.exists() ) {
                    log.debug( "Creating directory {}...", file );
                    if( !file.mkdirs() ) {
                        throw new IOException( "Could not create directory " + file );
                    }
                }
                continue;
            }
            log.debug( "Unzipping {}...", file );

            FileOutputStream fileOutputStream = new FileOutputStream( file );

            byte[] buffer = new byte[1024];

            int len;
            while( ( len = zipInputStream.read( buffer ) ) > 0 ) {
                fileOutputStream.write( buffer, 0, len );
            }

            fileOutputStream.close();
        }
    }
// FileUtil::unzip [java]
    public static void unzip(String zipFilePath, String targetPath, boolean safeUnzip) throws IOException {
        targetPath = getCanonicalPath(new File(targetPath));
        ZipFile zipFile = new ZipFile(zipFilePath);
        try {
            Enumeration<?> entryEnum = zipFile.entries();
            while (entryEnum.hasMoreElements()) {
                OutputStream os = null;
                InputStream is = null;
                try {
                    ZipEntry zipEntry = (ZipEntry) entryEnum.nextElement();
                    if (!zipEntry.isDirectory()) {
                        if (safeUnzip && isNotSafeFile(zipEntry.getName())) {
                            //Unsafe
                            continue;
                        }

                        File targetFile = new File(targetPath, zipEntry.getName());

                        if (!targetFile.toPath().normalize().startsWith(targetPath)) {
                            throw new RuntimeException("Bad zip entry");
                        }
                        if (safeUnzip && !getCanonicalPath(targetFile).startsWith(targetPath)) {
                            //Unsafe
                            continue;
                        }

                        if (!targetFile.getParentFile().exists()) {
                            targetFile.getParentFile().mkdirs();
                        }
                        os = new BufferedOutputStream(new FileOutputStream(targetFile));
                        is = zipFile.getInputStream(zipEntry);
                        byte[] buffer = new byte[4096];
                        int readLen = 0;
                        while ((readLen = is.read(buffer, 0, 4096)) > 0) {
                            os.write(buffer, 0, readLen);
                        }
                    }
                } finally {
                    close(is, os);
                }
            }
        } finally {
            close(zipFile);
        }
    }
// FileUtil::unzip [java]
    public static void unzip(String zipFilePath, String targetPath, boolean safeUnzip) throws IOException {
        targetPath = getCanonicalPath(new File(targetPath));
        ZipFile zipFile = new ZipFile(zipFilePath);
        try {
            Enumeration<?> entryEnum = zipFile.entries();
            while (entryEnum.hasMoreElements()) {
                OutputStream os = null;
                InputStream is = null;
                try {
                    ZipEntry zipEntry = (ZipEntry) entryEnum.nextElement();
                    if (!zipEntry.isDirectory()) {
                        if (safeUnzip && isNotSafeFile(zipEntry.getName())) {
                            //Unsafe
                            continue;
                        }

                        File targetFile = new File(targetPath + File.separator + zipEntry.getName());
                        if (safeUnzip && !getCanonicalPath(targetFile).startsWith(targetPath)) {
                            //Unsafe
                            continue;
                        }

                        if (!targetFile.getParentFile().exists()) {
                            targetFile.getParentFile().mkdirs();
                        }
                        os = new BufferedOutputStream(new FileOutputStream(targetFile));
                        is = zipFile.getInputStream(zipEntry);
                        byte[] buffer = new byte[4096];
                        int readLen = 0;
                        while ((readLen = is.read(buffer, 0, 4096)) > 0) {
                            os.write(buffer, 0, readLen);
                        }
                    }
                } finally {
                    close(is, os);
                }
            }
        } finally {
            close(zipFile);
        }
    }
// JUtil::unpackJar [java]
   public static void unpackJar(File fjar, File fout) throws IOException {
    
      JarFile jf = new JarFile(fjar);
      Enumeration<JarEntry> en = jf.entries();

      while (en.hasMoreElements()) {
         JarEntry je = en.nextElement();
         java.io.File f = new File(fout,  je.getName());
							if (!f.toPath().normalize().startsWith(fout.toPath().normalize())) {
								throw new RuntimeException("Bad zip entry");
							}
         if (je.isDirectory()) {
            f.mkdirs();
            continue;

         } else {
            // f.getParentFile().mkdirs();

            if (f.getPath().indexOf("META-INF") >= 0) {
               // skip it
            } else {
            f.getParentFile().mkdirs();
            java.io.InputStream is = jf.getInputStream(je);
            java.io.FileOutputStream fos = new FileOutputStream(f);

            // EFF - buffering, file channels??
            while (is.available() > 0) {
               fos.write(is.read());
            }
            fos.close();
            is.close();
         }
         }
      }

    //  E.info("unpacked jar to " + fout);

       
   }
// JUtil::unpackJar [java]
   public static void unpackJar(File fjar, File fout) throws IOException {
    
      JarFile jf = new JarFile(fjar);
      Enumeration<JarEntry> en = jf.entries();

      while (en.hasMoreElements()) {
         JarEntry je = en.nextElement();
         java.io.File f = new File(fout,  je.getName());
         if (je.isDirectory()) {
            f.mkdirs();
            continue;

         } else {
            // f.getParentFile().mkdirs();

            if (f.getPath().indexOf("META-INF") >= 0) {
               // skip it
            } else {
            f.getParentFile().mkdirs();
            java.io.InputStream is = jf.getInputStream(je);
            java.io.FileOutputStream fos = new FileOutputStream(f);

            // EFF - buffering, file channels??
            while (is.available() > 0) {
               fos.write(is.read());
            }
            fos.close();
            is.close();
         }
         }
      }

    //  E.info("unpacked jar to " + fout);

       
   }
// (anonymous) [javascript]
	hserver = require('http').createServer(function(req,res){
		console.log('Serving: %s',req.url);
		var rs = fs.createReadStream(__dirname+path.normalize(req.url).replace(/^(\.\.[\/\\])+/, ''),{
			flags: 'r',
			autoClose: true
		});
		rs.on('open',function(){
			rs.pipe(res);
		});
		rs.on('error',function(e){
			res.end(e+'');
		});
	}),
// (anonymous) [javascript]
	hserver = require('http').createServer(function(req,res){
		console.log('Serving: %s',req.url);
		var rs = fs.createReadStream(__dirname+req.url,{
			flags: 'r',
			autoClose: true
		});
		rs.on('open',function(){
			rs.pipe(res);
		});
		rs.on('error',function(e){
			res.end(e+'');
		});
	}),
// (anonymous) [javascript]
  server((req, res) => {
    const decodePathname = decodeURI(url.parse(req.url).pathname);
    const pathname = path.normalize(decodePathname).replace(/^(\.\.(\/|\\|$))+/, '');
    res.setHeader('access-control-allow-origin', '*');
    if (reload && pathname === '/livereload') return serveReload(res);
    if (!isRouteRequest(pathname)) return serveStaticFile(res, pathname);
    return serveRoute(res, pathname);
  }).listen(parseInt(port, 10));
// (anonymous) [javascript]
  server((req, res) => {
    const pathname = decodeURI(url.parse(req.url).pathname);
    res.setHeader('access-control-allow-origin', '*');
    if (reload && pathname === '/livereload') return serveReload(res);
    if (!isRouteRequest(pathname)) return serveStaticFile(res, pathname);
    return serveRoute(res, pathname);
  }).listen(parseInt(port, 10));
// (anonymous) [javascript]
process.on('uncaughtException',function(e){
	console.error(e);
	console.trace(e.stack);
});
// (anonymous) [javascript]
    app.get('/static/*', function(req, res)
    { 
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/.." +
                                    req.url.replace(/\./g, '').split("?")[0]);
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });
// (anonymous) [javascript]
    app.get('/static/*', function(req, res)
    { 
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/.." + req.url.split("?")[0]);
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });
// (anonymous) [javascript]
app.post("/db/:db/:name", function(req, res) {
  var db = req.params.db;
  var name = req.params.name;
  var obj = req.body.obj;
  var msg = "db:"+db+" name:"+name+"\n"+obj;
  c.log(msg);
  var filename = path.join(dbRoot, db, 'md', name);
  if (filename.indexOf(dbRoot) !== 0) { // 檢查是否穿越dbRoot 參考：https://en.wikipedia.org/wiki/Directory_traversal_attack
    return response(res, 403, 'traversing root path forbidden!');
  }

  fs.writeFile(filename, obj, function(err) {
    if (err)
      response(res, 500, 'write fail!');
    else
      response(res, 200, 'write success!');
  })
});
// (anonymous) [javascript]
  fs.writeFile(dbRoot+"/"+db+"/md/"+name, obj, function(err) {
    if (err)
      response(res, 500, 'write fail!');
    else
      response(res, 200, 'write success!');
  })
// build_path [python]
def build_path(root_dir, path):
    absolute_path = Path(root_dir) / path

    if ".." in absolute_path.parts:
        raise ValueError(f"Attempted directory traversal: {path}")

    return absolute_path
// build_path [python]
def build_path(root_dir, path):
    resolved_path = (Path(root_dir) / path).resolve()

    if not resolved_path.is_relative_to(root_dir):
        raise ValueError(f"Attempted directory traversal: {path}")

    return resolved_path
// __parse_jeos_images [python]
    def __parse_jeos_images(self):
        log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
        config_urls = self.configuration['jeos_config']
        for url in config_urls:
            filehandle = urlopen(url)
            line = filehandle.readline().strip()

            while line:
                # Lines that start with '#' are a comment
                if line[0] == "#":
                    pass
                # Lines that are zero length are whitespace
                if len(line) == 0:
                    pass
                image_detail = line.split(":")
                if len(image_detail) >= 6:
                    self.__add_jeos_image(image_detail)
                else:
                    log.warning("Found unparsable line in JEOS config (%s)" % url)

                line = filehandle.readline()
// __parse_jeos_images [python]
    def __parse_jeos_images(self):
        log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
        # Loop through all JEOS configuration files to populate our jeos_images dictionary
        config_path = self.configuration['jeos_config']
        listing = os.listdir(config_path)
        for infile in listing:
            fileIN = open(config_path + infile, "r")
            line = fileIN.readline()

            while line:
                if line[0] == "#":
                    # Comment
                    pass
                if len(line.strip()) == 0:
                    # Whitespace
                    pass
                image_detail = line.split(":")
                if len(image_detail) >= 6:
                    self.__add_jeos_image(image_detail)
                else:
                    log.warning("Found unparsable JEOS config line in (%s)" % (config_path + infile))

                line = fileIN.readline()
// job_browse [python]
@gui.route("/job/<int:job_id>/browse", defaults={"path": ""})
@gui.route("/job/<int:job_id>/browse/<path:path>")
@login_required
def job_browse(job_id: int, path):
    """
    Browse directory of the job.
    :param job_id: int
    :param path: str
    """

    try:
        # Query job information
        job_info = query_internal_api(f"/internal/jobs/{job_id}", "get")

        # Base directory of the job
        job_base_dir = os.path.dirname(os.path.dirname(job_info["outputdir"]))

    except Exception as err:
        # Display error on the GUI
        flash(str(err), "danger")
        return redirect(url_for("job_page", job_id=job_id))

    # Join the base and the requested path
    abs_path = safe_join(job_base_dir, path)

    # URL path variable for going back
    back_path = os.path.dirname(abs_path).replace(job_base_dir, "")

    # If path doesn't exist
    if not os.path.exists(abs_path):
        flash("Directory for this job does not exist.", "warning")
        return redirect(url_for("job_page", job_id=job_id))

    # Check if path is a file and send
    if os.path.isfile(abs_path):
        return send_file(abs_path)

    files_info = []

    # Show directory contents
    files = os.listdir(abs_path)

    # Store directory information
    for file in files:
        files_info.append({
            "file": file,
            "directory": os.path.isdir(os.path.join(abs_path, file))
        })

    return render_template('job_dir.html', title=f"Job {job_id} Directory",
                           job_id=job_id,
                           abs_path=abs_path,
                           files_info=files_info,
                           back_path=back_path)
// job_browse [python]
@gui.route("/job/<int:job_id>/browse", defaults={"path": ""})
@gui.route("/job/<int:job_id>/browse/<path:path>")
@login_required
def job_browse(job_id: int, path):
    """
    Browse directory of the job.
    :param job_id: int
    :param path: str
    """

    try:
        # Query job information
        job_info = query_internal_api(f"/internal/jobs/{job_id}", "get")

        # Base directory of the job
        job_base_dir = os.path.dirname(os.path.dirname(job_info["outputdir"]))

    except Exception as err:
        # Display error on the GUI
        flash(str(err), "danger")
        return redirect(url_for("job_page", job_id=job_id))

    # Join the base and the requested path
    abs_path = os.path.join(job_base_dir, path)

    # URL path variable for going back
    back_path = os.path.dirname(abs_path).replace(job_base_dir, "")

    # If path doesn't exist
    if not os.path.exists(abs_path):
        flash("Directory for this job does not exist.", "warning")
        return redirect(url_for("job_page", job_id=job_id))

    # Check if path is a file and send
    if os.path.isfile(abs_path):
        return send_file(abs_path)

    files_info = []

    # Show directory contents
    files = os.listdir(abs_path)

    # Store directory information
    for file in files:
        files_info.append({
            "file": file,
            "directory": os.path.isdir(os.path.join(abs_path, file))
        })

    return render_template('job_dir.html', title=f"Job {job_id} Directory",
                           job_id=job_id,
                           abs_path=abs_path,
                           files_info=files_info,
                           back_path=back_path)
// archive_directory [python]
def archive_directory(top_dir, subdir, tmpdir):
    """
    .. function:: archive_directory(top_dir, subdir, tmpdir)

    Given a sub-directory name under the root directory to be archived, archive the contents of the sub-directory
    to a temporary directory. Then return the full path to the temporary directory.
    :param top_dir: The root path that will be archived and uploaded to Glacier.
    :param subdir: The path to the subdirectory that is being archived here, relative to `top_dir`
    :param tmpdir: The path to the temporary directory to store archives in until they are uploaded to Glacier
    :return: If the subdirectory contains files, then the full path to the temporary archives; otherwise, None
    """
    # We're only archiving the *files* in this directory, not the subdirectories.

    files = []
    full_backup_path = os.path.join(top_dir, subdir)
    dir_contents = os.listdir(full_backup_path)

    # Only add files to 'files' list, not subdirs
    for c in dir_contents:
        fpath = os.path.join(full_backup_path, c)
        if os.path.isfile(fpath) and not fpath.endswith(".ini"):
            # logger.info("Adding to archive list: {0}".format(c))
            files.append(fpath)

    if not files:
        # No point creating empty archives!
        return None

    os.makedirs(os.path.join(tmpdir, subdir))
    archive_file_path = os.path.join(tmpdir, subdir) + ".zip"

    logger.info("Archiving %s to %s" % (subdir, archive_file_path))

    # with open(os.devnull, "w") as devnull:

    devnull = open(os.devnull, "wb")

    try:
        with zipfile.ZipFile(archive_file_path, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as arch_zip:
            for f in files:
                logger.debug("Adding {0} to archive {1}".format(f, archive_file_path))
                arch_zip.write(f, os.path.basename(f))
            return archive_file_path

    except Exception, e:
        logging.error("Failed to create archive {0}: {1}".format(archive_file_path, e.message))
        logging.debug("Error args: {0}".format(e.args))
        return None
// archive_directory [python]
def archive_directory(top_dir, subdir, tmpdir):
    """
    .. function:: archive_directory(top_dir, subdir, tmpdir)

    Given a sub-directory name under the root directory to be archived, archive the contents of the sub-directory
    to a temporary directory. Then return the full path to the temporary directory.
    :param top_dir: The root path that will be archived and uploaded to Glacier.
    :param subdir: The path to the subdirectory that is being archived here, relative to `top_dir`
    :param tmpdir: The path to the temporary directory to store archives in until they are uploaded to Glacier
    :return: If the subdirectory contains files, then the full path to the temporary archives; otherwise, None
    """
    # We're only archiving the *files* in this directory, not the subdirectories.

    files = []
    full_backup_path = os.path.join(top_dir, subdir)
    dir_contents = os.listdir(full_backup_path)

    # Only add files to 'files' list, not subdirs
    for c in dir_contents:
        fpath = os.path.join(top_dir, subdir, c)
        if os.path.isfile(fpath) and not fpath.endswith(".ini"):
            # logger.info("Adding to archive list: {0}".format(c))
            files.append(fpath)

    if not files:
        # No point creating empty archives!
        return None

    os.makedirs(os.path.join(tmpdir, subdir))
    archive_file_path = os.path.join(tmpdir, subdir) + ".zip"

    logger.info("Archiving %s to %s" % (subdir, archive_file_path))

    # with open(os.devnull, "w") as devnull:

    devnull = open(os.devnull, "wb")
    file_list = []
    for p in os.listdir(full_backup_path):
        if os.path.isfile(os.path.join(full_backup_path, p)):
            file_list.append(os.path.join(full_backup_path, p))

    try:
        with zipfile.ZipFile(archive_file_path, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as arch_zip:
            for f in file_list:
                logger.debug("Adding {0} to archive {1}".format(f, archive_file_path))
                arch_zip.write(f, os.path.basename(f))
                return archive_file_path

    except Exception, e:
        logging.error("Failed to create archive {0}: {1}".format(archive_file_path, e.message))
        logging.debug("Error args: {0}".format(e.args))
        return None
// check_max_open_files [python]
def check_max_open_files(opts):
    '''
    Check the number of max allowed open files and adjust if needed
    '''
    mof_c = opts.get('max_open_files', 100000)
    if sys.platform.startswith('win'):
        # Check the Windows API for more detail on this
        # http://msdn.microsoft.com/en-us/library/xt874334(v=vs.71).aspx
        # and the python binding http://timgolden.me.uk/pywin32-docs/win32file.html
        mof_s = mof_h = win32file._getmaxstdio()
    else:
        mof_s, mof_h = resource.getrlimit(resource.RLIMIT_NOFILE)

    accepted_keys_dir = os.path.join(opts.get('pki_dir'), 'minions')
    accepted_count = sum(1 for _ in os.listdir(accepted_keys_dir))

    log.debug(
        'This salt-master instance has accepted {0} minion keys.'.format(
            accepted_count
        )
    )

    level = logging.INFO

    if (accepted_count * 4) <= mof_s:
        # We check for the soft value of max open files here because that's the
        # value the user chose to raise to.
        #
        # The number of accepted keys multiplied by four(4) is lower than the
        # soft value, everything should be OK
        return

    msg = (
        'The number of accepted minion keys({0}) should be lower than 1/4 '
        'of the max open files soft setting({1}). '.format(
            accepted_count, mof_s
        )
    )

    if accepted_count >= mof_s:
        # This should never occur, it might have already crashed
        msg += 'salt-master will crash pretty soon! '
        level = logging.CRITICAL
    elif (accepted_count * 2) >= mof_s:
        # This is way too low, CRITICAL
        level = logging.CRITICAL
    elif (accepted_count * 3) >= mof_s:
        level = logging.WARNING
        # The accepted count is more than 3 time, WARN
    elif (accepted_count * 4) >= mof_s:
        level = logging.INFO

    if mof_c < mof_h:
        msg += ('According to the system\'s hard limit, there\'s still a '
                'margin of {0} to raise the salt\'s max_open_files '
                'setting. ').format(mof_h - mof_c)

    msg += 'Please consider raising this value.'
    log.log(level=level, msg=msg)
// check_max_open_files [python]
def check_max_open_files(opts):
    '''
    Check the number of max allowed open files and adjust if needed
    '''
    mof_c = opts.get('max_open_files', 100000)
    if sys.platform.startswith('win'):
        # Check the Windows API for more detail on this
        # http://msdn.microsoft.com/en-us/library/xt874334(v=vs.71).aspx
        # and the python binding http://timgolden.me.uk/pywin32-docs/win32file.html
        mof_s = mof_h = win32file._getmaxstdio()
    else:
        mof_s, mof_h = resource.getrlimit(resource.RLIMIT_NOFILE)

    accepted_keys_dir = os.path.join(opts.get('pki_dir'), 'minions')
    accepted_count = len([
        key for key in os.listdir(accepted_keys_dir) if
        os.path.isfile(os.path.join(accepted_keys_dir, key))
    ])

    log.debug(
        'This salt-master instance has accepted {0} minion keys.'.format(
            accepted_count
        )
    )

    level = logging.INFO

    if (accepted_count * 4) <= mof_s:
        # We check for the soft value of max open files here because that's the
        # value the user chose to raise to.
        #
        # The number of accepted keys multiplied by four(4) is lower than the
        # soft value, everything should be OK
        return

    msg = (
        'The number of accepted minion keys({0}) should be lower than 1/4 '
        'of the max open files soft setting({1}). '.format(
            accepted_count, mof_s
        )
    )

    if accepted_count >= mof_s:
        # This should never occur, it might have already crashed
        msg += 'salt-master will crash pretty soon! '
        level = logging.CRITICAL
    elif (accepted_count * 2) >= mof_s:
        # This is way too low, CRITICAL
        level = logging.CRITICAL
    elif (accepted_count * 3) >= mof_s:
        level = logging.WARNING
        # The accepted count is more than 3 time, WARN
    elif (accepted_count * 4) >= mof_s:
        level = logging.INFO

    if mof_c < mof_h:
        msg += ('According to the system\'s hard limit, there\'s still a '
                'margin of {0} to raise the salt\'s max_open_files '
                'setting. ').format(mof_h - mof_c)

    msg += 'Please consider raising this value.'
    log.log(level=level, msg=msg)
// _singleton_init [python]
    def _singleton_init(self, configuration = None):
        super(ApplicationConfiguration, self)._singleton_init()
        self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
        self.jeos_images = { }

        if configuration:
            if not isinstance(configuration, dict):
                raise Exception("ApplicationConfiguration configuration argument must be a dict")
            self.log.debug("ApplicationConfiguration passed a dictionary - ignoring any local config files including JEOS configs")
            self.configuration = configuration
        else:
            self.configuration = self.__parse_arguments()
            self.__parse_jeos_images()

        if not 'debug' in self.configuration:
            if 'nodebug' in self.configuration:
                # Slightly confusing, I know - For daemon mode we have a debug argument with default False
                # For cli, we debug by default and have a nodebug argument with default False
                # Rest of the code assumes a 'debug' value in app_config so set it here
                self.configuration['debug'] = not self.configuration['nodebug']
            else:
                # This most likely means we are being used as a module/library and are not running CLI or daemon
                self.configuration['debug'] = False

        if not 'secondary' in self.configuration:
            # We use this in the non-daemon context so it needs to be set
            # TODO: Something cleaner?
            self.configuration['secondary'] = False