download and extract libzmq
760891
def fetch_libzmq(savedir):
    """"""
    dest = pjoin(savedir, 'zeromq')
    if os.path.exists(dest):
        info("already have %s" % dest)
        return
    path = fetch_archive(savedir, libzmq_url, fname=libzmq, checksum=libzmq_checksum)
    tf = tarfile.open(path)
    with_version = pjoin(savedir, tf.firstmember.path)
    tf.extractall(savedir)
    tf.close()

    # remove version suffix:
    shutil.move(with_version, dest)
1253639
def run(self):
        
        os.system("cp python-bugzilla.spec /tmp")
        try:
            os.system("rm -rf python-bugzilla-%s" % get_version())
            self.run_command('sdist')
            os.system('rpmbuild -ta --clean dist/python-bugzilla-%s.tar.gz' %
                      get_version())
        finally:
            os.system("mv /tmp/python-bugzilla.spec .")
530278
def zmq_recv_data(socket, flags=0, copy=True, track=False):
    """"""

    data = dict()

    msg = socket.recv_multipart(flags=flags, copy=copy, track=track)

    headers = json.loads(msg[0].decode('ascii'))

    if len(headers) == 0:
        raise StopIteration

    for header, payload in zip(headers, msg[1:]):
        data[header['key']] = np.frombuffer(buffer(payload),
                                            dtype=header['dtype'])
        data[header['key']].shape = header['shape']
        if six.PY2:
            # Legacy python won't let us preserve alignment, skip this step
            continue
        data[header['key']].flags['ALIGNED'] = header['aligned']

    return data
1254525
def pull(self):
        
        sock = self.__sock(zmq.PULL)
        return self.__recv_generator(sock)
120614
def extract_native_client_tarball(dir):
    
    '''
    assert_valid_dir(dir)

    target_tarball = os.path.join(dir, 'native_client.tar.xz')
    if os.path.isfile(target_tarball) and os.stat(target_tarball).st_size == 0:
        return

    subprocess.check_call(['pixz', '-d', 'native_client.tar.xz'], cwd=dir)
    subprocess.check_call(['tar', 'xf', 'native_client.tar'], cwd=dir)
    os.unlink(os.path.join(dir, 'native_client.tar'))
    open(target_tarball, 'w').close()
1132559
def from_memdb_file(path):
        """"""
        path = to_bytes(path)
        return View._from_ptr(rustcall(_lib.lsm_view_from_memdb_file, path))
1082053
function downloadRepo(config, tmpFolder, callback) {

  console.log('Downloading repo...'.magenta);

  // Keep track if the request fails to prevent the continuation of the install
  var requestFailed = false;

  var repoRequest = request(config.baseGit + '/generate-repo.zip');

  repoRequest
    .on('response', function (response) {
      // If we fail, set it as failing and remove zip file
      if (response.statusCode !== 200) {
        requestFailed = true;
        fs.unlinkSync('repo.zip');
        callback(true);
      }
    })
    .pipe(fs.createWriteStream('repo.zip'))
    .on('close', function () {
      if (requestFailed) return;

      console.log('Extracting Files...'.magenta);
      // Unzip into temporary file
      var zip = new Zip('repo.zip');
      zip.extractAllTo(tmpFolder);
      fs.unlinkSync('repo.zip');
      callback(null, tmpFolder + '/' + fs.readdirSync(tmpFolder)[0]);
    });
}
560367
def download(self, module):
        '''
        '''

        import_r = '^[ |\t]+import[ |\t]+([a-zA-Z0-9-]+)[ |\t]+[;{][ |\t]*$'
        include_r = '^[ |\t]+include[ |\t]+([a-zA-Z0-9-]+)[ |\t]*[;{][ |\t]*$'

        logger.debug('Downloading {}.yang...'.format(module))
        try:
            from .device import ModelDevice
            reply = super(ModelDevice, self.device) \
                    .execute(operations.retrieve.GetSchema, module)
        except operations.rpc.RPCError:
            logger.warning("Module or submodule '{}' cannot be downloaded" \
                           .format(module))
            return
        if reply.ok:
            fname = self.dir_yang + '/' + module + '.yang'
            with open(fname, 'w') as f:
                f.write(reply.data)
            self.downloaded.add(module)
            imports = set()
            includes = set()
            for line in reply.data.splitlines():
                match = re.search(import_r, line)
                if match:
                    imports.add(match.group(1).strip())
                    continue
                match = re.search(include_r, line)
                if match:
                    includes.add(match.group(1).strip())
                    continue
            s = (imports | includes) - self.downloaded - self.to_be_downloaded
            if s:
                logger.info('{} requires submodules: {}' \
                            .format(module, ', '.join(s)))
                self.to_be_downloaded.update(s)
        else:
            logger.warning("module or submodule '{}' cannot be downloaded:\n{}" \
                           .format(module, reply._raw))
568535
def maybe_download_and_extract():
  """"""
  dest_directory = "/tmp/cifar"
  if not os.path.exists(dest_directory):
    os.makedirs(dest_directory)
  filename = DATA_URL.split('/')[-1]
  filepath = os.path.join(dest_directory, filename)
  if not os.path.exists(filepath):
    def _progress(count, block_size, total_size):
      sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename,
          float(count * block_size) / float(total_size) * 100.0))
      sys.stdout.flush()
    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
    print()
    statinfo = os.stat(filepath)
    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
    tarfile.open(filepath, 'r:gz').extractall(dest_directory)
203900
def install_from_zip(pkgpath, install_path, register_func, delete_after_install=False):
    """"""
    logger.debug("%s is a file, attempting to load zip", pkgpath)
    pkgtempdir = tempfile.mkdtemp(prefix="honeycomb_")
    try:
        with zipfile.ZipFile(pkgpath) as pkgzip:
            pkgzip.extractall(pkgtempdir)
    except zipfile.BadZipfile as exc:
        logger.debug(str(exc))
        raise click.ClickException(str(exc))
    if delete_after_install:
        logger.debug("deleting %s", pkgpath)
        os.remove(pkgpath)
    logger.debug("installing from unzipped folder %s", pkgtempdir)
    return install_dir(pkgtempdir, install_path, register_func, delete_after_install=True)
328273
def download_quads(name, bbox, rbox, quiet, dest, limit):
    ''''''
    bbox = bbox or rbox
    cl = clientv1()

    dl = downloader.create(cl, mosaic=True)
    output = downloader_output(dl, disable_ansi=quiet)
    output.start()
    try:
        mosaic, = cl.get_mosaic_by_name(name).items_iter(1)
        items = cl.get_quads(mosaic, bbox).items_iter(limit)
    except Exception as ex:
        output.cancel()
        click_exception(ex)
    # invoke the function within an interrupt handler that will shut everything
    # down properly
    handle_interrupt(dl.shutdown, dl.download, items, [], dest)
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()
851402
def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    cmdlist = [cmd, '-d', '-k']
    if verbosity > 1:
        cmdlist.append('-v')
    outfile = util.get_single_outfile(outdir, archive)
    cmdlist.extend(["-o", outfile, archive])
    return cmdlist
1059024
def start(self):
        '''
        
        '''
        zmq_uri = '{protocol}://{address}:{port}'.format(
                       protocol=self.protocol,
                       address=self.address,
                       port=self.port
                   ) if self.port else\
                   '{protocol}://{address}'.format(  # noqa
                       protocol=self.protocol,
                       address=self.address
                   )
        log.debug('ZMQ URI: %s', zmq_uri)
        self.ctx = zmq.Context()
        if hasattr(zmq, self.type):
            skt_type = getattr(zmq, self.type)
        else:
            skt_type = zmq.PULL
        self.sub = self.ctx.socket(skt_type)
        self.sub.connect(zmq_uri)
        if self.hwm is not None:
            try:
                self.sub.setsockopt(zmq.HWM, self.hwm)
            except AttributeError:
                self.sub.setsockopt(zmq.RCVHWM, self.hwm)
        if self.recvtimeout is not None:
            log.debug('Setting RCVTIMEO to %d', self.recvtimeout)
            self.sub.setsockopt(zmq.RCVTIMEO, self.recvtimeout)
        if self.keepalive is not None:
            log.debug('Setting TCP_KEEPALIVE to %d', self.keepalive)
            self.sub.setsockopt(zmq.TCP_KEEPALIVE, self.keepalive)
        if self.keepalive_idle is not None:
            log.debug('Setting TCP_KEEPALIVE_IDLE to %d', self.keepalive_idle)
            self.sub.setsockopt(zmq.TCP_KEEPALIVE_IDLE, self.keepalive_idle)
        if self.keepalive_interval is not None:
            log.debug('Setting TCP_KEEPALIVE_INTVL to %d', self.keepalive_interval)
            self.sub.setsockopt(zmq.TCP_KEEPALIVE_INTVL, self.keepalive_interval)
971960
def _qvm_run(self, quil_program, classical_addresses, trials,
                 measurement_noise, gate_noise, random_seed) -> np.ndarray:
        
        payload = qvm_run_payload(quil_program, classical_addresses, trials,
                                  measurement_noise, gate_noise, random_seed)
        response = post_json(self.session, self.sync_endpoint + "/qvm", payload)

        ram = response.json()

        for k in ram.keys():
            ram[k] = np.array(ram[k])

        return ram
826513
def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    return _extract(archive, compression, cmd, 'alone', verbosity, outdir)
1199740
def download(ui, repo, clname, **opts):
	
	if codereview_disabled:
		raise hg_util.Abort(codereview_disabled)

	cl, vers, patch, err = DownloadCL(ui, repo, clname)
	if err != "":
		return err
	ui.write(cl.EditorText() + "\n")
	ui.write(patch + "\n")
	return