more than one report -> every report files are put inside a folder and all folders are archieved to zip
329483
@Override
	protected byte[] getData(Attributes attributes) {
        byte[] zip = null;
        Map<String, List<String>> filesMap = new HashMap<String, List<String>>();
        Map<String, List<byte[]>> contentsMap = new HashMap<String, List<byte[]>>();

        for (Report report : reports) {
            String folder = report.getName();
            List<String> files = new ArrayList<String>();
            List<byte[]> contents = new ArrayList<byte[]>();

            if (ReportConstants.NEXT.equals(report.getType())) {
                report = NextUtil.restoreImagesName(report);
                NextContent reportContent = (NextContent) report.getContent();
                files.add(reportContent.getNextFile().getName());
                contents.add(reportContent.getNextFile().getDataProvider().getBytes());
                if (reportContent.getImageFiles() != null) {
                    for (JcrFile entry : reportContent.getImageFiles()) {
                        files.add(entry.getName());
                        contents.add(entry.getDataProvider().getBytes());
                    }
                }
				if (reportContent.getTemplateFile() != null) {
					files.add(reportContent.getTemplateFile().getName());
					contents.add(reportContent.getTemplateFile().getDataProvider().getBytes());
				}

            } else {
                report = JasperUtil.restoreImagesName(report);
                report = JasperUtil.restoreSubreportsInMaster(report);

                JasperContent jrc = (JasperContent) report.getContent();
                List<JcrFile> entries = jrc.getJasperFiles();
                for (JcrFile entry : entries) {
                    files.add(entry.getName());
                    contents.add(entry.getDataProvider().getBytes());
                }

                JcrFile paramEntry = jrc.getParametersFile();
                if (paramEntry != null) {
                    files.add(paramEntry.getName());
                    contents.add(paramEntry.getDataProvider().getBytes());
                }

                if (jrc.getImageFiles() != null) {
                    for (JcrFile entry : jrc.getImageFiles()) {
                        files.add(entry.getName());
                        contents.add(entry.getDataProvider().getBytes());
                    }
                }
            }

            if (reports.size() == 1) {
                try {
                    zip = FileUtil.zip(files, contents);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                filesMap.put(folder, files);
                contentsMap.put(folder, contents);
            }
        }

        if (reports.size() > 1) {
            try {
                zip = FileUtil.zip(filesMap, contentsMap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return zip;
    }
830243
def zipdir(path, ziph, **kwargs):
    
    str_arcroot = ""
    for k, v in kwargs.items():
        if k == 'arcroot':  str_arcroot = v

    for root, dirs, files in os.walk(path):
        for file in files:
            str_arcfile = os.path.join(root, file)
            if len(str_arcroot):
                str_arcname = str_arcroot.split('/')[-1] + str_arcfile.split(str_arcroot)[1]
            else:
                str_arcname = str_arcfile
            try:
                ziph.write(str_arcfile, arcname = str_arcname)
            except:
                print("Skipping %s" % str_arcfile)
175040
public static boolean zipFolder(File folder, String fileName){
		boolean success = false;
		if(!folder.isDirectory()){
			return false;
		}
		
		if(fileName == null){
			fileName = folder.getAbsolutePath()+ZIP_EXT;
		}
		
		ZipArchiveOutputStream zipOutput = null;
		try {
			zipOutput = new ZipArchiveOutputStream(new File(fileName));
			
			success = addFolderContentToZip(folder,zipOutput,"");

			zipOutput.close();
		
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		finally{
			try {
				if(zipOutput != null){
					zipOutput.close();
				}
			} catch (IOException e) {}
		}
		return success;
	}
615437
function getFoldersAndFiles(fpath, folders, files){
	fs.readdirSync(fpath).forEach(function(name){
		var stat = fs.statSync(fpath + name);
		if(stat.isDirectory()){
			folders.push({
				path : fpath,
				name : name
			});
			
			getFoldersAndFiles(fpath + name + '/', folders, files);
		}else{
			files.push({
				path : fpath,
				name : name
			});
		}
	});
}
835896
def _walk_report(self, folder):
        ''''''

        dir_list = {}
        try:
            for dirName, subdirList, fileList in os.walk(folder):
                x = []
                for fname in fileList:
                    x.append(fname)
                dir_list[dirName] = x

            return dir_list
        except Exception as e: # pragma: no cover
            self.logger.exception(e)
            raise Exception("WalkReport Error: Unable to Walk Report")
1030151
function createZip (targetZipPath, currentFolder, filesToInclude, done) {
  const args = ['-FS', targetZipPath].concat(filesToInclude)
  const startTime = Date.now()
  trace(`Calling: zip ${args.join(' ')}`)
  const child = childProcess.spawn('zip', args, {
    cwd: currentFolder,
    stdio: [ 'ignore', 'ignore', 'ignore' ]
  })
  child.on('error', (err) => {
    error(`Error: please verify that <zip> is installed on your system`)
    error(err.toString())
  })
  child.on('close', (code, signal) => {
    const elapsed = Math.floor(Date.now() - startTime)
    debug(`Zip exited with code ${code} in ${elapsed}ms`)
    done(code === 0 ? null : new Error(`Error creating ZIP file ${targetZipPath}`))
  })
}
671784
public static void zip(File[] sources, File target) throws IOException {
		zip(sources, target, null);
	}
70896
def copy_files_to_folder(files, target_folder, overwrite=True):
    
    if not files:
        return []

    for f in files:
        target = os.path.join(target_folder, os.path.split(f)[-1])

        if target == f:
            # both file path are the same!
            return target

        if os.path.exists(target):
            if overwrite:
                # remove the file before copying
                try:
                    os.remove(target)
                except Exception:
                    raise IOError("Failed to remove %s" % f)
                else:
                    shutil.copy(f, target)
            else:
                continue
        else:
            print('Copying %s to %s' % (os.path.split(f)[-1],
                                        os.path.normpath(target_folder)))
            shutil.copy(f, target)

    return [os.path.join(target_folder, os.path.split(f)[-1]) for f in files]
975062
def files_in(directories)
      files = []
      Find.find(*directories) do |path|
        unless File.directory?(path) or File.symlink?(path)
          files << File.expand_path(path)
        end
      end
      files.uniq
    end
1198011
def delete_report(report):
    
    for path in glob.glob(os.path.join(_get_reports_path(), report)):
        shutil.rmtree(path)
804490
def organize_dir(orig_dir):
    ''''''

    tags = [
        (0x10,0x20),    # Subj ID
        (0x8,0x21),     # Date
        (0x8,0x31),     # Time
        (0x8,0x103e)    # Descr
    ]
    orig_dir = orig_dir.rstrip('/')
    files = scan_dir(orig_dir,tags=tags,md5_hash=True)
    dups = find_dups(files)
    for dup in dups:
        nl.notify('Found duplicates of %s...' % dup[0])
        for each_dup in dup[1:]:
            nl.notify('\tdeleting %s' % each_dup)
            try:
                os.remove(each_dup)
            except IOError:
                nl.notify('\t[failed]')
            del(files[each_dup])

    clustered = cluster_files(files)
    output_dir = '%s-sorted' % orig_dir
    for key in clustered:
        if (0x8,0x31) in clustered[key]['info']:
            clustered[key]['info'][(0x8,0x31)] = str(int(float(clustered[key]['info'][(0x8,0x31)])))
        for t in tags:
            if t not in clustered[key]['info']:
                clustered[key]['info'][t] = '_'
        run_name = '-'.join([scrub_fname(str(clustered[key]['info'][x])) for x in tags])+'-%d_images' %len(clustered[key]['files'])
        run_dir = os.path.join(output_dir,run_name)
        nl.notify('Moving files into %s' % run_dir)
        try:
            if not os.path.exists(run_dir):
                os.makedirs(run_dir)
        except IOError:
            nl.notify('Error: failed to create directory %s' % run_dir)
        else:
            for f in clustered[key]['files']:
                try:
                    dset_fname = os.path.split(f)[1]
                    if dset_fname[0]=='.':
                        dset_fname = '_' + dset_fname[1:]
                    os.rename(f,os.path.join(run_dir,dset_fname))
                except (IOError, OSError):
                    pass
    for r,ds,fs in os.walk(output_dir,topdown=False):
        for d in ds:
            dname = os.path.join(r,d)
            if len(os.listdir(dname))==0:
                os.remove(dname)
902825
def create_zip_from_folder(zip_file, fldr, mode="r"):
    
    #print('zip from folder - adding folder : ', fldr)
    zipf = zipfile.ZipFile(zip_file, 'w')
    for root, dirs, files in os.walk(fldr):
        for file in files:
            fullname = os.path.join(root, file)
            #print('zip - adding file : ', fullname)
            zipf.write(fullname)
    
    
    zipf.close()
28851
def add_files(self, files):
        

        if isinstance(files, basestring):
            files = [files]

        zip_file = None
        if self.zip_:
            zip_filename = self._get_zip_filename()
            zip_file = ZipFile(zip_filename, 'w')

        for filename in files:
            if os.path.isdir(filename):
                for dirname, subdirs, filelist in os.walk(filename):
                    if dirname:
                        if self.zip_:
                            zip_file.write(dirname)

                    for fname in filelist:
                        filepath = os.path.join(dirname, fname)
                        if self.zip_:
                            zip_file.write(filepath)

                        else:
                            fmfile = self.get_file_specs(filepath,
                                                         keep_folders=True)
                            if fmfile['totalsize'] > 0:
                                self._files.append(fmfile)

            else:
                if self.zip_:
                    zip_file.write(filename)

                else:
                    fmfile = self.get_file_specs(filename)
                    self._files.append(fmfile)

        if self.zip_:
            zip_file.close()
            filename = zip_filename
            fmfile = self.get_file_specs(filename)
            self._files.append(fmfile)
1098904
def extract_all(zipfile, dest_folder):
    
    z = ZipFile(zipfile)
    print(z)
    z.extract(dest_folder)
400817
def report(options)
      report = HamlLint::Report.new(reporter: options[:reporter], fail_level: options[:fail_level])
      report.start(@files)
      process_files(report)
      report
    end
15866
public static void compress(String folderPath, String zipFilePath) throws IOException {
    File folder = new File(folderPath);
    if (!folder.exists() || !folder.isDirectory()) {
      throw new IOException("Folder " + folderPath + " does't exist or isn't a directory");
    }

    File zipFile = new File(zipFilePath);
    if (!zipFile.exists()) {
      File zipFolder = zipFile.getParentFile();
      if (!zipFolder.exists()) {
        if (!zipFolder.mkdirs()) {
          throw new IOException("Zip folder " + zipFolder.getAbsolutePath() + " not created");
        }
      }
      if (!zipFile.createNewFile()) {
        throw new IOException("Zip file " + zipFilePath + " not created");
      }
    }

    BufferedInputStream bis;
    ZipOutputStream zos = new ZipOutputStream(
        new BufferedOutputStream(new FileOutputStream(zipFile)));
    try {
      final int BUFFER_SIZE = 8 * 1024; // 8K
      byte buffer[] = new byte[BUFFER_SIZE];
      for (String fileName : folder.list()) {
        if (fileName.equals(".") || fileName.equals("..")) {
          continue;
        }

        File file = new File(folder, fileName);
        if (!file.isFile()) {
          continue;
        }

        FileInputStream fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis, BUFFER_SIZE);
        try {
          ZipEntry entry = new ZipEntry(fileName);
          zos.putNextEntry(entry);
          int count;
          while ((count = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
            zos.write(buffer, 0, count);
          }
        } finally {
          try {
            bis.close();
          } catch (IOException e) {
            // Ignore
          }
        }
      }
    } finally {
      try {
        zos.close();
      } catch (IOException e) {
        // Ignore
      }
    }
  }
542280
private void collectFiles(final File folder, final List<File> found) {
		File[] files = folder.listFiles();
		if (files != null) {
			for (File file : files) {
				if (file.isDirectory()) {
					collectFiles(file, found);
				} else if (file.isFile() && file.getPath().endsWith(suffix)) {
					int index = 0;

					for (String text : plainTexts) {
						index = file.getPath().indexOf(text, index);
						if (index == -1) {
							break;
						} else {
							index += text.length();
						}
					}

					if (index >= 0) {
						found.add(file);
					}
				}
			}
		}
	}