Truns a python object into a ZIP file.
425168
def format(collection, **params):
    """"""
    binary = io.BytesIO()
    with zipfile.ZipFile(binary, 'w') as zip_:
        now = datetime.datetime.utcnow().timetuple()
        for filename, content in collection:
            content_type, encoding = mimetypes.guess_type(filename)
            content = content_types.get(content_type).parse(content, **params)
            content = content_encodings.get(encoding).decode(content)
            zip_info = zipfile.ZipInfo(filename, now)
            zip_info.file_size = len(content)
            zip_.writestr(zip_info, content)
    binary.seek(0)
    return binary.read()
347689
def from_zip(cls, src='/tmp/app.zip', dest='/app'):
    
    try:
      zf = zipfile.ZipFile(src, 'r')
    except FileNotFoundError:
      raise errors.InvalidPathError(src)
    except zipfile.BadZipFile:
      raise errors.InvalidZipFileError(src)
    [zf.extract(file, dest) for file in zf.namelist()]
    zf.close()
    return cls.from_path(dest)
501813
def compress(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if ('gzip' in bottle.request.headers.get('Accept-Encoding', '') and
                isinstance(result, string_type) and
                len(result) > 1024):
            if isinstance(result, unicode):
                result = result.encode('utf-8')
            tmp_fo = BytesIO()
            with gzip.GzipFile(mode='wb', fileobj=tmp_fo) as gzip_fo:
                gzip_fo.write(result)
            result = tmp_fo.getvalue()
            bottle.response.add_header('Content-Encoding', 'gzip')
        return result
    return wrapper
921607
def py(self, output):
        """"""
        import pprint
        pprint.pprint(output, stream=self.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
794593
def to_python(self, value):
        """"""
        if isinstance(value, FileDescriptor):
            return value
        elif isinstance(value, str):
            return FileDescriptor(value)
        elif isinstance(value, dict):
            try:
                path = value['file']
            except KeyError:
                raise ValidationError("dictionary must contain a 'file' element")

            if not isinstance(path, str):
                raise ValidationError("field's file element must be a string")

            size = value.get('size', None)
            if size is not None and not isinstance(size, int):
                raise ValidationError("field's size element must be an integer")

            total_size = value.get('total_size', None)
            if total_size is not None and not isinstance(total_size, int):
                raise ValidationError("field's total_size element must be an integer")

            is_remote = value.get('is_remote', None)
            if is_remote is not None and not isinstance(is_remote, bool):
                raise ValidationError("field's is_remote element must be a boolean")

            file_temp = value.get('file_temp', None)
            if file_temp is not None and not isinstance(file_temp, str):
                raise ValidationError("field's file_temp element must be a string")

            refs = value.get('refs', None)
            if refs is not None and not isinstance(refs, list):
                # TODO: Validate that all refs are strings.
                raise ValidationError("field's refs element must be a list of strings")

            return FileDescriptor(
                path,
                size=size,
                total_size=total_size,
                is_remote=is_remote,
                file_temp=file_temp,
                refs=refs,
            )
        elif not isinstance(value, None):
            raise ValidationError("field must be a FileDescriptor, string or a dict")
228277
function zip(keys, values) {
  if (keys.length !== values.length) {
    throw Error(`Incorrect number of arguments, expected: ${keys.length}, arguments received: ${values.join(', ')}`)
  }

  return keys.reduce((all, key, idx) => ({...all, [key]: values[idx]}), {})
}
257594
def current_zipfile():
    """"""
    if zipfile.is_zipfile(sys.argv[0]):
        fd = open(sys.argv[0], "rb")
        return zipfile.ZipFile(fd)
567286
def zlib_compress(data):
    
    if PY3K:
        if isinstance(data, str):
            return zlib.compress(bytes(data, 'utf-8'))
        return zlib.compress(data)
    return zlib.compress(data)
607015
def pack_gzip(params, ctxt, scope, stream, coord):
    
    if len(params) == 0:
        raise errors.InvalidArguments(coord, "{} args".format(len(params)), "at least one argument")
    
    built = utils.binary("")
    for param in params:
        if isinstance(param, pfp.fields.Field):
            built += param._pfp__build()
        else:
            built += param
    
    return zlib.compress(built)
519524
def unzip_file(zip_fname):
    """""" 
    print("Unzipping {}".format(zip_fname))
    with zipfile.ZipFile(zip_fname) as zf:
        zf.extractall()
906085
def open_zip(path, *args, **kwargs):
  """"""
  with contextlib.closing(PermPreservingZipFile(path, *args, **kwargs)) as zip:
    yield zip
290612
def to_blob(self, repo):
        """"""
        return Blob(repo, self.binsha, self.mode, self.path)
1250016
def unzip_file(filename, location, flatten=True):
    """"""
    if not os.path.exists(location):
        os.makedirs(location)
    zipfp = open(filename, 'rb')
    try:
        zip = zipfile.ZipFile(zipfp)
        leading = has_leading_dir(zip.namelist()) and flatten
        for name in zip.namelist():
            data = zip.read(name)
            fn = name
            if leading:
                fn = split_leading_dir(name)[1]
            fn = os.path.join(location, fn)
            dir = os.path.dirname(fn)
            if not os.path.exists(dir):
                os.makedirs(dir)
            if fn.endswith('/') or fn.endswith('\\'):
                # A directory
                if not os.path.exists(fn):
                    os.makedirs(fn)
            else:
                fp = open(fn, 'wb')
                try:
                    fp.write(data)
                finally:
                    fp.close()
    finally:
        zipfp.close()
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()
176869
def save_npz(object, handle):
    """"""
    # there is a bug where savez doesn't actually accept a file handle.
    log.warning("Saving npz files currently only works locally. :/")
    path = handle.name
    handle.close()
    if type(object) is dict:
        np.savez(path, **object)
    elif type(object) is list:
        np.savez(path, *object)
    else:
        log.warning("Saving non dict or list as npz file, did you maybe want npy?")
        np.savez(path, object)
657114
def build(cls, path):
        
        with zipfile.ZipFile(path) as zfile:
            items = (
                (
                    name.replace('/', os.sep),
                    zfile.getinfo(name),
                )
                for name in zfile.namelist()
            )
            return dict(items)