示例#1
0
    def run_mcmc_with_pbar(sampler, pos0, N, rstate0=None, lnprob0=None, desc=None,
                           **kwargs):
        """
        Iterate :func:`sample` for ``N`` iterations and return the result while also
        showing a progress bar

        Parameters
        ----------
        pos0:
            The initial position vector.  Can also be None to resume from
            where :func:``run_mcmc`` left off the last time it executed.

        N:
            The number of steps to run.

        lnprob0: (optional)
            The log posterior probability at position ``p0``. If ``lnprob``
            is not provided, the initial value is calculated.

        rstate0: (optional)
            The state of the random number generator. See the
            :func:`random_state` property for details.

        desc: str (optional)
            title of the progress bar

        kwargs: (optional)
            Other parameters that are directly passed to :func:`sample`.

        Returns
        -------
        t: tuple
            This returns the results of the final sample in whatever form
            :func:`sample` yields.  Usually, that's: ``pos``, ``lnprob``,
            ``rstate``, ``blobs`` (blobs optional)
        """
        if pos0 is None:
            if sampler._last_run_mcmc_result is None:
                raise ValueError("Cannot have pos0=None if run_mcmc has never "
                                 "been called.")
            pos0 = sampler._last_run_mcmc_result[0]
            if lnprob0 is None:
                rstate0 = sampler._last_run_mcmc_result[1]
            if rstate0 is None:
                rstate0 = sampler._last_run_mcmc_result[2]

        with Pbar(maxval=N, desc=desc) as pb:
            k = 0
            for results in sampler.sample(pos0, lnprob0, rstate0, iterations=N,
                                          **kwargs):
                k += 1
                pb.update(k)

        # store so that the ``pos0=None`` case will work.  We throw out the blob
        # if it's there because we don't need it
        sampler._last_run_mcmc_result = results[:3]

        return results
示例#2
0
def debug():
    global bar,F
    bar=Pbar(speed=20,info_len=50)
    port_server=8001
    host_forward='192.168.8.203'
    #host_forward='127.0.0.1'
    port_forward=8001
    forwarder_num=5

    func_file='./dynamic_replacement/login_live_com.py'
    func_util=pyfunc_util(func_file,'def process_*:')
    #outprocess_func='process_out'

    #outfunc=pyfunc_util(func_file,'def '+outprocess_func+'*:').get_func(outprocess_func)


    F=ProxyForward(host_forward=host_forward, port_forward=port_forward,port_server=port_server,bar=None,debug=False)

    F.set_out_processer(func_util.get_func('process_out_head')[3],func_util.get_func('process_out_body')[3])
    F.set_in_processer(func_util.get_func('process_in_head')[3],func_util.get_func('process_in_body')[3])

    F.server(forwarder_num=forwarder_num,waitting=False)
    F.waitting_server_end()
示例#3
0
        set_func = False
        if func_file != '':
            if os.path.exists(func_file):
                U = pyfunc_util(func_file, 'def *:*')
                out_head = U.get_func('out_head')
                out_body = U.get_func('out_body')
                in_head = U.get_func('in_head')
                in_body = U.get_func('in_body')
                set_func = True
            else:
                print('[!]文件不存在')
    except Exception as ex:
        print('[!]input format error')
        exit(0)

    bar = Pbar(info_len=50)
    F = ProxyForward(host_forward=host_forward,
                     port_forward=port_forward,
                     port_server=port_server,
                     bar=bar,
                     debug=debug)
    F.save_log = log
    #F.codec=codec
    if set_func:
        F.set_out_processer(out_head, out_body)
        F.set_in_processer(in_head, in_body)
    while 1:
        try:
            F.server(forwarder_num=forwarder_num, waitting=True)
            break
        except Exception as ex:
示例#4
0
def GetFileMd5(filename):
    bar = Pbar(info_len=35, allow_skip_frame=True)
    bar.start_bar()

    if not os.path.exists(filename):
        bar.print('file not found -> ' + filename)
        bar.clear(True)
        return False
    bar.set_rate(10, 'checking file...')
    if not os.path.isfile(filename):
        bar.print('not a file -> ' + filename)
        bar.clear(True)
        return False
    bar.set_rate(20, 'checking file...done')
    myhash = hashlib.md5()

    file_size = os.path.getsize(filename) // 1024  #kb

    f = open(filename, 'rb')
    bar.set_rate(30, '0/{}k reading file...'.format(file_size))

    persent = file_size // 100

    next_show = persent
    readed = 0
    while True:
        b = f.read(8096)
        if not b:
            break
        readed += 8
        if readed > next_show:
            next_show += persent
            bar.set_rate(
                int(readed / file_size * 70) + 30,
                '{}/{}k reading file...'.format(readed, file_size))

        myhash.update(b)
    f.close()
    bar.set_rate(100, 'reading file...done')
    bar.clear()
    return myhash.hexdigest()
    def download_ext(self):
        num = len(self._download_list)
        down_num = 0
        bar = Pbar(speed=30, bar_fill='#', bar_moving='>>>>>', move_mode='ll')
        bar.start_bar()
        bar.set_rate(None, 'checking extra lib...')
        for s in self._download_list:
            if os.path.exists(s['filepath']):
                down_num += 1
                #bar.set_speed((100-i)//3+60)
                bar.set_rate(int(100 / num * down_num),
                             'checking extra lib...')
                continue
            bar.print('warnning:leak extra lib...downloading')
            bar.set_rate(None, 'downloading...')

            self._call_downloader(self._get_downloader(s['downloader_name']))
            down_num += 1

            bar.set_rate(int(100 / num * down_num), 'checking extra lib...')
            self._move_file(s)
            bar.print('info:success download extra lib ' + s['file_name'])
        bar.set_rate(100, 'extar lib check pass')
        bar.clear(True)
示例#6
0
import requests
import os, sys
if sys.platform == 'linux':
    import readline
path = os.path.abspath('.')
if 'tools' in path.replace('\\', '/').split('/'):  #这里是为了便于开发调试
    path = path.split('tools', maxsplit=1)[0] + 'Library/utils'
else:
    path = path + '/Library/utils'
if not path in (p.replace('\\', '/') for p in sys.path):
    sys.path.append(path)

from pbar import Pbar

bar = Pbar(info_len=25, allow_skip_frame=True)


def Is64Windows():
    return 'PROGRAMFILES(X86)' in os.environ


path = os.path.abspath('.') + '/Library/yafu1.34'
exe = ''
if Is64Windows():
    exe = 'yafu-x64.exe'
else:
    exe = 'yafu-Win32.exe'

print('此程序用于分解RSA公钥,用到了factordb和yafu')
print('factordb : http://factordb.com/index.php')
示例#7
0
 def ensure(self, pipname):
     '''保证指定的pip已经安装,字符串或列表'''
     if isinstance(pipname, str):
         if pipname not in self._pip_list:
             fd = self._install(pipname)
             if fd == False:
                 print('[!]错误:pip软件包' + pipname + '安装失败')
                 exit(1)
     elif isinstance(pipname, tuple) or isinstance(pipname, list):
         #开进度条
         bar = Pbar(show_percent_num=False,
                    smooth=True,
                    allow_skip_frame=False,
                    vsync=True)
         pnum = len(pipname) + 1
         for i, p in enumerate(pipname):
             bar.set_rate(int(i + 1 // pnum * 100), 'check ' + p + '...')
             if p not in self._pip_list:
                 fd = self._install(p)
                 if fd == False:
                     bar.print('[!]错误:pip软件包' + pipname + '安装失败')
                     bar.clear(True)
                     exit(1)
         bar.set_rate(100, 'all done')
         bar.clear(True)
     else:
         print('[!]错误:不支持的参数类型')
         exit(1)
示例#8
0
        return None


def fake_delay_bar(bar, t=10, info=''):
    def delay_thread(bar, t, info):
        bar.set_rate(0, info)
        for i in range(int(t)):
            bar.set_rate(int(i / int(t) * 100))
            time.sleep(1)
        bar.set_rate(100)

    threading.Thread(target=delay_thread, args=(bar, t, info)).start()


if __name__ == "__main__":
    b = Pbar(speed=15, )
    b.start_bar()
    fake_delay_bar(b, 30, '正在获取ip...')
    ip = get_router_ip()

    if ip == None or len(ip.split('.')) != 4:
        b.print('获取ip失败')
        b.clear(True)
        exit(0)

    b.print('ip:' + ip)
    b.clear(True)

    b.start_bar()

    L = NoRootIPdelayMonitor(ip)
示例#9
0
    ngen, npop, ndim = 100, 100, 2
    limits = [[-5, 5]] * ndim

    # iterations to make a plot
    fn_list = (rosenbrock_fn, sphere_fn, ackley_fn, styblinski_fn)

    for en, fn in enumerate(fn_list):
        ax = plt.subplot(2, 2, en + 1)
        pop = np.zeros([ngen, npop, ndim])
        loc = np.zeros([ngen, ndim])
        de = DiffEvolOptimizer(fn, limits, npop)

        de(ngen)

        for i, res in Pbar(ngen).iterover(enumerate(de(ngen))):
            pop[i, :, :] = de.population.copy()
            loc[i, :] = de.location.copy()

        vals = np.ravel(list(map(fn, zip(pop[:, :, 0], pop[:, :, 1]))))

        print(fn.__name__, de.location, de.value)

        ax.scatter(pop[:, :, 0].ravel(),
                   pop[:, :, 1].ravel(),
                   c=np.log10(vals + 1e-20),
                   alpha=0.2,
                   edgecolor='None')
        plt.plot(loc[:, 0], loc[:, 1], 'k.-')
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
示例#10
0
        img, tag = imgparts[-1].split(':')
    except ValueError:
        img = imgparts[-1]
# Docker client doesn't seem to consider the first element as a potential registry unless there is a '.' or ':'
if len(imgparts) > 1 and ('.' in imgparts[0] or ':' in imgparts[0]):
    registry = imgparts[0]
    repo = '/'.join(imgparts[1:-1])
else:
    registry = 'registry-1.docker.io'
    if len(imgparts[:-1]) != 0:
        repo = '/'.join(imgparts[:-1])
    else:
        repo = 'library'
repository = '{}/{}'.format(repo, img)

bar = Pbar(move_mode='ll', show_percent_num=True, info_len=50)
bar.start_bar()

bar.set_rate(20, 'Get Docker authentication endpoint')
# Get Docker authentication endpoint when it is required
auth_url = 'https://auth.docker.io/token'
reg_service = 'registry.docker.io'
resp = requests.get('https://{}/v2/'.format(registry), verify=False)
if resp.status_code == 401:
    auth_url = resp.headers['WWW-Authenticate'].split('"')[1]
    try:
        reg_service = resp.headers['WWW-Authenticate'].split('"')[3]
    except IndexError:
        reg_service = ""

示例#11
0
        return None


def fake_delay_bar(bar, t=10, info=''):
    def delay_thread(bar, t, info):
        bar.set_rate(0, info)
        for i in range(int(t)):
            bar.set_rate(int(i / int(t) * 100))
            time.sleep(1)
        bar.set_rate(100)

    threading.Thread(target=delay_thread, args=(bar, t, info)).start()


if __name__ == "__main__":
    b = Pbar(speed=15, info_len=20, bar_len=50)
    b.start_bar()
    fake_delay_bar(b, 30, '正在获取ip...')
    ip = get_router_ip()

    if ip == None or len(ip.split('.')) != 4:
        b.print('获取ip失败')
        b.clear(True)
        exit(0)

    b.print('ip:' + ip)
    b.clear(True)

    b.start_bar()

    L = NoRootIPdelayMonitor(ip)