Prepares section for zip output
12214
def sectionOutZip(self,zipcontainer,zipdir='',figtype='png'):
        
        from io import StringIO, BytesIO
        text = self.p if not self.settings['doubleslashnewline'] else self.p.replace('//','\n')
        zipcontainer.writestr(
            zipdir+'section.txt',
            '# {}\n{}'.format(self.title,text).encode()
        )
        c = count(1)
        for ftitle,f in self.figs.items():
            figfile = zipdir+'fig{}_{}.{}'.format(next(c),ftitle.replace(' ','_'),figtype)
            b = BytesIO()
            f.savefig(b,format=figtype,transparent=True)
            b.seek(0)
            zipcontainer.writestr(figfile,b.getvalue())
        c = count(1)
        for ttitle,t in self.tabs.items():
            b = StringIO()
            t.to_csv(b,sep=csvsep,decimal=csvdec)
            b.seek(0)
            zipcontainer.writestr(
                zipdir+'table{}_{}.csv'.format(next(c),ttitle.replace(' ','_')),
                b.read().encode()
            )
        c = count(1)
        for s in self.subs:
            s.sectionOutZip(zipcontainer,'{}s{}_{}/'.format(zipdir,next(c),s.title.replace(' ','_')),figtype=figtype)
1238477
def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    return [cmd, '-d', outdir, archive]
991448
def zip(keys, values):
    
    output = Data()
    for i, k in enumerate(keys):
        if i >= len(values):
            break
        output[k] = values[i]
    return output
1133590
function zip(data, options) {
		var flags = 0,
			level,
			crc, out = [];

		if (!options) {
			options = {};
		}
		level = options.level || DEFAULT_LEVEL;

		if (typeof data === 'string') {
			data = Array.prototype.map.call(data, function (char) {
				return char.charCodeAt(0);
			});
		}

		// magic number marking this file as GZIP
		putByte(ID1, out);
		putByte(ID2, out);

		putByte(compressionMethods['deflate'], out);

		if (options.name) {
			flags |= possibleFlags['FNAME'];
		}

		putByte(flags, out);
		putLong(options.timestamp || parseInt(Date.now() / 1000, 10), out);

		// put deflate args (extra flags)
		if (level === 1) {
			// fastest algorithm
			putByte(4, out);
		} else if (level === 9) {
			// maximum compression (fastest algorithm)
			putByte(2, out);
		} else {
			putByte(0, out);
		}

		// OS identifier
		putByte(osMap[os], out);

		if (options.name) {
			// ignore the directory part
			putString(options.name.substring(options.name.lastIndexOf('/') + 1), out);

			// terminating null
			putByte(0, out);
		}

		deflate.deflate(data, level).forEach(function (byte) {
			putByte(byte, out);
		});

		putLong(parseInt(crc32(data), 16), out);
		putLong(data.length, out);

		return out;
	}
248099
def show_distribution_section(config, title, section_name):
    
    payload = requests.get(config.apps_url).json()
    distributions = sorted(payload.keys(), reverse=True)
    latest_distribution = payload[distributions[0]]
    click.echo("{} {}".format("Release".rjust(7), title))
    click.echo("------- ---------------")
    section = latest_distribution[section_name]
    names = sorted(section.keys())
    for name in names:
        click.echo("{} {}".format(section[name].rjust(7), name))
838010
public void generate(Output out) throws IOException {
        for (Section section : sections) {
            section.generate(out);
            out.lineBreak();
            out.optionalLineBreak();
        }
    }
408029
protected function prepOutputDir()
    {
        if (!is_dir($this->output_dir . $this->prefix)) {
            $this->filesystem->mkdir($this->output_dir . $this->prefix);
        }
    }
1228887
def make_python_zip():
    '''
    
    '''

    if not exists('private'):
        print('No compiled python is present to zip, skipping.')
        return

    global python_files
    d = realpath(join('private', 'lib', 'python2.7'))

    def select(fn):
        if is_blacklist(fn):
            return False
        fn = realpath(fn)
        assert(fn.startswith(d))
        fn = fn[len(d):]
        if (fn.startswith('/site-packages/')
                or fn.startswith('/config/')
                or fn.startswith('/lib-dynload/')
                or fn.startswith('/libpymodules.so')):
            return False
        return fn

    # get a list of all python file
    python_files = [x for x in listfiles(d) if select(x)]

    # create the final zipfile
    zfn = join('private', 'lib', 'python27.zip')
    zf = ZipFile(zfn, 'w')

    # put all the python files in it
    for fn in python_files:
        afn = fn[len(d):]
        zf.write(fn, afn)
    zf.close()
1043818
def WriteFileChunk(self, chunk):
    """"""
    precondition.AssertType(chunk, bytes)

    if not self._stream:
      raise ArchiveAlreadyClosedError(
          "Attempting to write to a ZIP archive that was already closed.")

    self.cur_file_size += len(chunk)
    # TODO(user):pytype: crc32 is not visible outside of zipfile.
    # pytype: disable=module-attr
    self.cur_crc = zipfile.crc32(chunk, self.cur_crc) & 0xffffffff
    # pytype: enable=module-attr

    if self.cur_cmpr:
      chunk = self.cur_cmpr.compress(chunk)
      self.cur_compress_size += len(chunk)

    self._stream.write(chunk)
    return self._stream.GetValueAndReset()
1201673
def zipper(root_dir="", name="", path_name_ext=""):
    
    logger_zips.info("re_zip: name: {}, dir_tmp: {}".format(path_name_ext, root_dir))
    # creates a zip archive in current directory. "somefile.lpd.zip"
    shutil.make_archive(path_name_ext, format='zip', root_dir=root_dir, base_dir=name)
    # drop the .zip extension. only keep .lpd
    os.rename("{}.zip".format(path_name_ext), path_name_ext)
    return
1306627
public function prepareSections()
    {
        // Replace parent sections to show
        preg_match_all('/@parent/', $this->prepared, $matches);

        if(isset($matches[0][0]))
        {
            foreach($matches[0] as $key => $section)
            {
                $this->prepared = trim(str_replace($matches[0][$key], "<?= parent::{explode('::', __METHOD__)[1]}(); ?>", $this->prepared));
            }
        }

        // Replace sections show
        preg_match_all('/@show\(\'([a-zA-Z0-9\.\-]+)\'\)/', $this->prepared, $matches);

        if(isset($matches[1][0]))
        {
            foreach($matches[1] as $key => $section)
            {
                $this->prepared = trim(str_replace($matches[0][$key], "<?= \$this->section('{$matches[1][$key]}'); ?>", $this->prepared));
            }
        }
    }
1056993
def auto_zip_open(filepath, mode):
    """"""
    if filepath.endswith('.gz'):
        outfile = gzip.open(filepath, mode)
    elif filepath.endswith('.bz2'):
        outfile = bz2.BZ2File(filepath, mode)
    else:
        outfile = open(filepath, mode)
    return outfile
991032
def extract_zip(fileobj):
    """"""
    archive = zipfile.ZipFile(fileobj, mode='r')
    filenames = archive.namelist()

    for src_name, dst_name in filter_tzfiles(filenames):
        modified = archive.getinfo(src_name).date_time
        bytes = archive.read(src_name)

        yield dst_name, modified, bytes
1283612
def _comic_archive_write_zipfile(new_filename, tmp_dir):
    """"""
    if Settings.verbose:
        print('Rezipping archive', end='')
    with zipfile.ZipFile(new_filename, 'w',
                         compression=zipfile.ZIP_DEFLATED) as new_zf:
        root_len = len(os.path.abspath(tmp_dir))
        for r_d_f in os.walk(tmp_dir):
            root = r_d_f[0]
            filenames = r_d_f[2]
            archive_root = os.path.abspath(root)[root_len:]
            for fname in filenames:
                fullpath = os.path.join(root, fname)
                archive_name = os.path.join(archive_root, fname)
                if Settings.verbose:
                    print('.', end='')
                new_zf.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)
46311
def _writecheck(self, zinfo):
        """"""
        if zinfo.filename in self.NameToInfo:
            if self.debug:      # Warning for duplicate names
                print "Duplicate name:", zinfo.filename
        if self.mode not in ("w", "a"):
            raise RuntimeError, 'write() requires mode "w" or "a"'
        if not self.fp:
            raise RuntimeError, \
                  "Attempt to write ZIP archive that was already closed"
        if zinfo.compress_type == ZIP_DEFLATED and not zlib:
            raise RuntimeError, \
                  "Compression requires the (missing) zlib module"
        if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED):
            raise RuntimeError, \
                  "That compression method is not supported"
        if zinfo.file_size > ZIP64_LIMIT:
            if not self._allowZip64:
                raise LargeZipFile("Filesize would require ZIP64 extensions")
        if zinfo.header_offset > ZIP64_LIMIT:
            if not self._allowZip64:
                raise LargeZipFile("Zipfile size would require ZIP64 extensions")
1023486
def _prepare_sample(data, run_folder):
    
    want = set(["description", "files", "genome_build", "name", "analysis", "upload", "algorithm"])
    out = {}
    for k, v in data.items():
        if k in want:
            out[k] = _relative_paths(v, run_folder)
    if "algorithm" not in out:
        analysis, algorithm = _select_default_algorithm(out.get("analysis"))
        out["algorithm"] = algorithm
        out["analysis"] = analysis
    description = "%s-%s" % (out["name"], clean_name(out["description"]))
    out["name"] = [out["name"], description]
    out["description"] = description
    return out
35168
def list_zip(archive, compression, cmd, verbosity, interactive):
    """"""
    try:
        with zipfile.ZipFile(archive, "r") as zfile:
            for name in zfile.namelist():
                if verbosity >= 0:
                    print(name)
    except Exception as err:
        msg = "error listing %s: %s" % (archive, err)
        raise util.PatoolError(msg)
    return None