How to use the pykern.pkdebug.pkdc function in pykern

To help you get started, we’ve selected a few pykern examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github radiasoft / sirepo / sirepo / template / srw.py View on Github external
x_range[2] = ar2d.shape[1]
            y_range[2] = ar2d.shape[0]
        except Exception:
            pkdlog('Cannot resize the image - scipy.ndimage.zoom() cannot be imported.')
    # rotate 3D image
    if rotate_angle:
        rotate_reshape = (rotate_reshape == "1")
        try:
            from scipy import ndimage
            pkdc('Size before: {}  Dimensions: {}', ar2d.size, ar2d.shape)
            shape_before = list(ar2d.shape)
            ar2d = ndimage.rotate(ar2d, rotate_angle, reshape = rotate_reshape, mode='constant', order = 3)
            pkdc('Size after rotate: {}  Dimensions: {}', ar2d.size, ar2d.shape)
            shape_rotate = list(ar2d.shape)

            pkdc('x_range and y_range before rotate is [{},{}] and [{},{}]', x_range[0], x_range[1], y_range[0], y_range[1])
            x_range[0] = shape_rotate[0]/shape_before[0]*x_range[0]
            x_range[1] = shape_rotate[0]/shape_before[0]*x_range[1]
            y_range[0] = shape_rotate[1]/shape_before[1]*y_range[0]
            y_range[1] = shape_rotate[1]/shape_before[1]*y_range[1]
            pkdc('x_range and y_range after rotate is [{},{}] and [{},{}]', x_range[0], x_range[1], y_range[0], y_range[1])

            x_range[2] = ar2d.shape[1]
            y_range[2] = ar2d.shape[0]
            if info['title'] != 'Power Density': info['subtitle'] = info['subtitle'] + ' Image Rotate {}^0'.format(rotate_angle)
        except Exception:
            pkdlog('Cannot rotate the image - scipy.ndimage.rotate() cannot be imported.')

    if z_units:
        z_label = u'{} [{}]'.format(z_label, z_units)
    return pkcollections.Dict({
        'x_range': x_range,
github radiasoft / sirepo / sirepo / runner.py View on Github external
def __docker(self, cmd):
        cmd = ['docker'] + cmd
        try:
            pkdc('Running: {}', ' '.join(cmd))
            return subprocess.check_output(
                cmd,
                stdin=open(os.devnull),
                stderr=subprocess.STDOUT,
            ).rstrip()
        except subprocess.CalledProcessError as e:
            pkdlog('{}: failed: exit={} output={}', cmd, e.returncode, e.output)
            return None
github radiasoft / sirepo / sirepo / auth / __init__.py View on Github external
# Force login to this specific method so we can migrate to valid method
            r = 'loginWith'
            p = PKDict({':method': m})
            e = 'forced {}={} uid={}'.format(m, r, p)
    elif s == _STATE_COMPLETE_REGISTRATION:
        if m == METHOD_GUEST:
            pkdc('guest completeRegistration={}', u)
            complete_registration()
            return
        r = 'completeRegistration'
        e = 'uid={} needs to complete registration'.format(u)
    else:
        cookie.reset_state('uid={} state={} invalid, cannot continue'.format(s, u))
        p = PKDict(reload_js=True)
        e = 'invalid cookie state={} uid={}'.format(s, u)
    pkdc('SRException uid={} route={} params={} method={} error={}', u, r, p, m, e)
    raise util.SRException(r, p, 'user not logged in: {}', e)
github radiasoft / sirepo / sirepo / http_reply.py View on Github external
r = sirepo.uri.default_local_route_name(s)
        p = PKDict(reload_js=True)
    if (
        # must be first, to always delete reload_js
        not p.pkdel('reload_js')
        and flask.request.method == 'POST'
        and r not in _RELOAD_JS_ROUTES
    ):
        pkdc('POST response={} route={} params={}', SR_EXCEPTION_STATE, r, p)
        return gen_json(
            PKDict({
                _STATE: SR_EXCEPTION_STATE,
                SR_EXCEPTION_STATE: args,
            }),
        )
    pkdc('redirect to route={} params={}  type={}', r, p, t)
    return gen_redirect_for_local_route(t, route=r, params=p)
github radiasoft / sirepo / sirepo / srunit.py View on Github external
"""
        from pykern.pkdebug import pkdlog, pkdexc, pkdc, pkdp
        import pykern.pkjson
        import sirepo.http_reply
        import sirepo.uri
        import sirepo.util

        redirects = kwargs.setdefault('__redirects', 0) + 1
        assert redirects <= 5
        kwargs['__redirects'] = redirects

        u = None
        r = None
        try:
            u = sirepo.uri.server_route(route_or_uri, params, query)
            pkdc('uri={}', u)
            r = op(u)
            pkdc('status={} data={}', r.status_code, r.data)
            # Emulate code in sirepo.js to deal with redirects
            if r.status_code == 200 and r.mimetype == 'text/html':
                m = _JAVASCRIPT_REDIRECT_RE.search(r.data)
                if m:
                    if m.group(1).endswith('#/error'):
                        raise sirepo.util.Error(
                            PKDict(error='server error uri={}'.format(m.group(1))),
                        )
                    if kwargs.get('redirect', True):
                        # Execute the redirect
                        return self.__req(
                            m.group(1),
                            None,
                            None,
github radiasoft / sirepo / sirepo / srunit.py View on Github external
import pykern.pkjson
        import sirepo.http_reply
        import sirepo.uri
        import sirepo.util

        redirects = kwargs.setdefault('__redirects', 0) + 1
        assert redirects <= 5
        kwargs['__redirects'] = redirects

        u = None
        r = None
        try:
            u = sirepo.uri.server_route(route_or_uri, params, query)
            pkdc('uri={}', u)
            r = op(u)
            pkdc('status={} data={}', r.status_code, r.data)
            # Emulate code in sirepo.js to deal with redirects
            if r.status_code == 200 and r.mimetype == 'text/html':
                m = _JAVASCRIPT_REDIRECT_RE.search(r.data)
                if m:
                    if m.group(1).endswith('#/error'):
                        raise sirepo.util.Error(
                            PKDict(error='server error uri={}'.format(m.group(1))),
                        )
                    if kwargs.get('redirect', True):
                        # Execute the redirect
                        return self.__req(
                            m.group(1),
                            None,
                            None,
                            self.get,
                            raw_response,
github radiasoft / sirepo / sirepo / runner_api.py View on Github external
computeJobHash=s.computeJobHash,
            computeJobStart=t,
            elapsedTime=lambda: int(
                (res.get('lastUpdateTime') or _mtime_or_now(reqd.run_dir)) - t
                if t else 0,
            ),
        )
    if is_processing:
        res.nextRequestSeconds = reqd.sim_data.poll_seconds(reqd.cached_data)
        res.nextRequest = PKDict(
            report=reqd.model_name,
            simulationId=reqd.cached_data.simulationId,
            simulationType=reqd.cached_data.simulationType,
            **reqd.cached_data.models.computeJobCacheKey
        )
    pkdc(
        '{}: processing={} state={} cache_hit={} cached_hash={} data_hash={}',
        reqd.jid,
        is_processing,
        res['state'],
        reqd.cache_hit,
        reqd.cached_hash,
        reqd.req_hash,
    )
    return res
github radiasoft / sirepo / sirepo / template / warpvnd.py View on Github external
electrons[1][i][j+1],
                    electrons[0][i][j+1],
                    electrons[2][i][j+1]
                ]
                if _cull_particle_point(curr, next, prev):
                    cull_count += 1
                    continue
            res['x'].append(curr[0])
            res['y'].append(curr[1])
            res['z'].append(curr[2])
            prev = curr
        count += len(res['x'])
        x_points.append(res['x'])
        y_points.append(res['y'])
        z_points.append(res['z'])
    pkdc('particles: {} paths, {} points {} points culled', len(x_points), count, cull_count)
github radiasoft / sirepo / sirepo / runner_api.py View on Github external
req (dict): parsed simulation data
        quiet (bool): don't write errors to log

    Returns:
        dict: status response
    """
    reqd = _reqd(req)
    in_run_simulation = 'models' in req.req_data
    if in_run_simulation:
        req.req_data.models.computeJobCacheKey = PKDict(
            computeJobHash=reqd.req_hash,
        )
    is_processing = runner.job_is_processing(reqd.jid)
    is_running = reqd.job_status in _RUN_STATES
    res = PKDict(state=reqd.job_status)
    pkdc(
        '{}: is_processing={} is_running={} state={} cached_data={}',
        reqd.jid,
        is_processing,
        is_running,
        reqd.job_status,
        bool(reqd.cached_data),
    )
    if is_processing and not is_running:
        runner.job_race_condition_reap(reqd.jid)
        pkdc('{}: is_processing and not is_running', reqd.jid)
        is_processing = False
    template = sirepo.template.import_module(req.type)
    if is_processing:
        if not reqd.cached_data:
            return _subprocess_error(
                error='input file not found, but job is running',