<commit_before>#!/usr/bin/env python

# Copyright (c) 2014 Red Hat, Inc. and/or its affiliates.
# Copyright (c) 2015 Anthony Towns
# Written by Anthony Towns <aj@erisian.com.au>
# See LICENSE file.

from .namespace import HierarchialNS
from .bbexcept import BeanBagException
from .attrdict import AttrDict

import requests

try:
    import json
except ImportError:
    import simplejson as json

__all__ = ['BeanBag', 'Request', 'verb', 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']
__version__ = '2.0.0'

def verb(verbname):
    """Construct a BeanBag compatible verb function

       :param verbname: verb to use (GET, POST, etc)
    """

    def do(url, body=None):
        base, path = ~url
        req = base.encode(body)
        res = base.make_request(path, verbname, req)
        return base.decode(res)

    do.__name__ = verbname
    do.__doc__ = "%s verb function" % (verbname,)
    return do

GET = verb("GET")
HEAD = verb("HEAD")
POST = verb("POST")
PUT = verb("PUT")
PATCH = verb("PATCH")
DELETE = verb("DELETE")

class Request(AttrDict):
    """Request object

       Request objects act as placeholders for the arguments to
       the requests() function of the requests.Session being used.
       They are used as the interface between the encode() and
       make_request() functions, and may also be used by the API
       caller.
    """

    def __init__(self, **kwargs):
        (~AttrDict).__init__(self, dict(**kwargs))

class BeanBag(HierarchialNS):
    mime_json = "application/json"

    def __init__(self, base_url, ext="", session=None, use_attrdict=True):
        """Create a BeanBag referencing a base REST path.

           :param base_url: the base URL prefix for all resources
           :param ext: extension to add to resource URLs, eg ".json"
           :param session: requests.Session instance used for this API. Useful
                  to set an auth procedure, or change verify parameter.
           :param use_attrdict: if true, ``decode()`` will wrap dicts and
                  lists in a ``beanbag.attrdict.AttrDict`` for syntactic
                  sugar.
        """

        if session is None:
            session = requests.Session()

        self.base_url = base_url.rstrip("/") + "/"
        self.ext = ext

        self.session = session
        self.use_attrdict = use_attrdict

    def encode(self, body):
        """Convert a python object into a beanbag.Request object.

           This function converts the user provided body object (or None
           when there is no body) into a requests.Request object, by
           encoding it as JSON string. (Note that the url and method
           members of the Request are provided later by the

           :param body: provided by the API user, usually a dict or None
        """

        if isinstance(body, Request):
            req = body
        elif body is None:
            req = Request(data=None, headers={"Accept": self.mime_json})
        else:
            req = Request(data=json.dumps(body),
                    headers={"Accept": self.mime_json,
                        "Content-Type": self.mime_json})
        return req

    def decode(self, response):
        """Converts a requests.Response object to a python object

           This function converts the REST API's response back into a
           python object by decoding it from JSON (or raises an exception
           if the response indicates an error).

           :param response: requests.Response object
        """

        if response.status_code < 200 or response.status_code >= 300:
            raise BeanBagException(response,
                    "Bad response code: %d" % (response.status_code,))

        if not response.content:
            return None

        res_content = response.headers.get("content-type", None)
        if res_content is None:
            pass
        elif res_content.split(";", 1)[0] == self.mime_json:
            pass
        else:
            raise BeanBagException(response,
                    "Bad content-type in response (Content-Type: %s; wanted %s)"
                                     % (res_content.split(";", 1)[0],
                                         self.mime_json))
        try:
            obj = json.loads(response.text or response.content)
        except:
            raise BeanBagException(response, "Could not decode response")

        if self.use_attrdict:
            if isinstance(obj, dict) or isinstance(obj, list):
                obj = AttrDict(obj)

        return obj

    def baseurl_params(self, path):
        """Construct the base URL of a resource (excluding URL params)"""

        url, params = path
        return ("%s%s%s" % (self.base_url, url, self.ext)), params

    def str(self, path):
        """Obtain the URL of a resource"""

        url, params = self.baseurl_params(path)
        if params:
            url = "%s?%s" % (url, ";".join("%s=%s" % (str(k), str(v))
                        for k, v in params.items() if v is not None))
        return url

    def path(self):
        return ("", {})

    def attr(self, attr):
        """Special processing for attribute access

           This converts ._ to a trailing slash.
        """

        if attr == "_":
            attr = "/"
        return str(attr)

    def _get(self, path, el):
        url, params = path
        el = str(el).lstrip("/")
        if url == "":
            newurl = el
        else:
            newurl = url.rstrip("/") + "/" + el
        return (newurl, params)

    def call(self, path, *args, **kwargs):
        """Set URL parameters"""

        url, params = path
        newparams = params.copy()
        for a in tuple(args) + (kwargs,):
            for k, v in a.items():
                if v is not None:
                    newparams[k] = v
                elif k in newparams:
                    del newparams[k]

        return self.namespace((url, newparams))

    def invert(self, path):
        """Provide access to the base/path via the namespace object

           .. code::

              bb = BeanBag(...)
              base, path = ~bb.foo
              assert isinstance(base, BeanBagBase)

           This is the little bit of glue needed so that it's possible to
           call methods defined in BeanBagBase directly rather than just
           the operators BeanBag supports.
        """

        return self, path

    def make_request(self, path, verb, request):
        """Make a REST request to a resource"""

        url, params = self.baseurl_params(path)

        assert isinstance(request, Request)
        request = +request   # convert to dictionary

        return self.session.request(
                method=verb, url=url, params=params, **request)

<commit_msg>v2: make Request do shallow copies of its kwargs<commit_after>#!/usr/bin/env python

# Copyright (c) 2014 Red Hat, Inc. and/or its affiliates.
# Copyright (c) 2015 Anthony Towns
# Written by Anthony Towns <aj@erisian.com.au>
# See LICENSE file.

from .namespace import HierarchialNS
from .bbexcept import BeanBagException
from .attrdict import AttrDict

import requests

try:
    import json
except ImportError:
    import simplejson as json

__all__ = ['BeanBag', 'Request', 'verb', 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']
__version__ = '2.0.0'

def verb(verbname):
    """Construct a BeanBag compatible verb function

       :param verbname: verb to use (GET, POST, etc)
    """

    def do(url, body=None):
        base, path = ~url
        req = base.encode(body)
        res = base.make_request(path, verbname, req)
        return base.decode(res)

    do.__name__ = verbname
    do.__doc__ = "%s verb function" % (verbname,)
    return do

GET = verb("GET")
HEAD = verb("HEAD")
POST = verb("POST")
PUT = verb("PUT")
PATCH = verb("PATCH")
DELETE = verb("DELETE")

class Request(AttrDict):
    """Request object

       Request objects act as placeholders for the arguments to
       the requests() function of the requests.Session being used.
       They are used as the interface between the encode() and
       make_request() functions, and may also be used by the API
       caller.

       NB: A Request object is only suitable for one use, as it may
       be modified in-place during the request. For this reason,
       __init__ makes a (shallow) copy of all the keyword arguments
       supplied rather than using them directly.
    """

    def __init__(self, **kwargs):
        for badarg in ["method", "url", "params"]:
            if badarg in kwargs:
                raise TypeError("__init__() got forbidden keyword argument '%s'" % (badarg,))

        d = {}
        for k, v in kwargs.items():
            if isinstance(v, list):
                v = v[:]
            elif isinstance(v, dict):
                v = v.copy()
            d[k] = v
        (~AttrDict).__init__(self, d)

class BeanBag(HierarchialNS):
    mime_json = "application/json"

    def __init__(self, base_url, ext="", session=None, use_attrdict=True):
        """Create a BeanBag referencing a base REST path.

           :param base_url: the base URL prefix for all resources
           :param ext: extension to add to resource URLs, eg ".json"
           :param session: requests.Session instance used for this API. Useful
                  to set an auth procedure, or change verify parameter.
           :param use_attrdict: if true, ``decode()`` will wrap dicts and
                  lists in a ``beanbag.attrdict.AttrDict`` for syntactic
                  sugar.
        """

        if session is None:
            session = requests.Session()

        self.base_url = base_url.rstrip("/") + "/"
        self.ext = ext

        self.session = session
        self.use_attrdict = use_attrdict

    def encode(self, body):
        """Convert a python object into a beanbag.Request object.

           This function converts the user provided body object (or None
           when there is no body) into a requests.Request object, by
           encoding it as JSON string. (Note that the url and method
           members of the Request are provided later by the

           :param body: provided by the API user, usually a dict or None
        """

        if isinstance(body, Request):
            req = body
        elif body is None:
            req = Request(data=None, headers={"Accept": self.mime_json})
        else:
            req = Request(data=json.dumps(body),
                    headers={"Accept": self.mime_json,
                        "Content-Type": self.mime_json})
        return req

    def decode(self, response):
        """Converts a requests.Response object to a python object

           This function converts the REST API's response back into a
           python object by decoding it from JSON (or raises an exception
           if the response indicates an error).

           :param response: requests.Response object
        """

        if response.status_code < 200 or response.status_code >= 300:
            raise BeanBagException(response,
                    "Bad response code: %d" % (response.status_code,))

        if not response.content:
            return None

        res_content = response.headers.get("content-type", None)
        if res_content is None:
            pass
        elif res_content.split(";", 1)[0] == self.mime_json:
            pass
        else:
            raise BeanBagException(response,
                    "Bad content-type in response (Content-Type: %s; wanted %s)"
                                     % (res_content.split(";", 1)[0],
                                         self.mime_json))
        try:
            obj = json.loads(response.text or response.content)
        except:
            raise BeanBagException(response, "Could not decode response")

        if self.use_attrdict:
            if isinstance(obj, dict) or isinstance(obj, list):
                obj = AttrDict(obj)

        return obj

    def baseurl_params(self, path):
        """Construct the base URL of a resource (excluding URL params)"""

        url, params = path
        return ("%s%s%s" % (self.base_url, url, self.ext)), params

    def str(self, path):
        """Obtain the URL of a resource"""

        url, params = self.baseurl_params(path)
        if params:
            url = "%s?%s" % (url, ";".join("%s=%s" % (str(k), str(v))
                        for k, v in params.items() if v is not None))
        return url

    def path(self):
        return ("", {})

    def attr(self, attr):
        """Special processing for attribute access

           This converts ._ to a trailing slash.
        """

        if attr == "_":
            attr = "/"
        return str(attr)

    def _get(self, path, el):
        url, params = path
        el = str(el).lstrip("/")
        if url == "":
            newurl = el
        else:
            newurl = url.rstrip("/") + "/" + el
        return (newurl, params)

    def call(self, path, *args, **kwargs):
        """Set URL parameters"""

        url, params = path
        newparams = params.copy()
        for a in tuple(args) + (kwargs,):
            for k, v in a.items():
                if v is not None:
                    newparams[k] = v
                elif k in newparams:
                    del newparams[k]

        return self.namespace((url, newparams))

    def invert(self, path):
        """Provide access to the base/path via the namespace object

           .. code::

              bb = BeanBag(...)
              base, path = ~bb.foo
              assert isinstance(base, BeanBagBase)

           This is the little bit of glue needed so that it's possible to
           call methods defined in BeanBagBase directly rather than just
           the operators BeanBag supports.
        """

        return self, path

    def make_request(self, path, verb, request):
        """Make a REST request to a resource"""

        url, params = self.baseurl_params(path)

        assert isinstance(request, Request)
        request = +request   # convert to dictionary

        return self.session.request(
                method=verb, url=url, params=params, **request)

<|endoftext|>


<commit_before># Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Denis Engemann <denis.engemann@gmail.com>
#          Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#          Eric Larson <larson.eric.d@gmail.com>
#          Cathy Nangini <cnangini@gmail.com>
#          Mainak Jas <mainak@neuro.hut.fi>
#
# License: Simplified BSD

import os.path as op
import warnings

import numpy as np
from numpy.testing import assert_raises

from mne import io, read_events, Epochs, pick_types, read_cov
from mne.channels import read_layout
from mne.utils import slow_test, run_tests_if_main
from mne.viz.evoked import _butterfly_onselect, plot_compare_evoked
from mne.viz.utils import _fake_click

# Set our plotters to test mode
import matplotlib
matplotlib.use('Agg')  # for testing don't use X server

warnings.simplefilter('always')  # enable b/c these tests throw warnings

base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
evoked_fname = op.join(base_dir, 'test-ave.fif')
raw_fname = op.join(base_dir, 'test_raw.fif')
cov_fname = op.join(base_dir, 'test-cov.fif')
event_name = op.join(base_dir, 'test-eve.fif')
event_id, tmin, tmax = 1, -0.1, 0.1
n_chan = 6
layout = read_layout('Vectorview-all')

def _get_raw():
    return io.read_raw_fif(raw_fname, preload=False)

def _get_events():
    return read_events(event_name)

def _get_picks(raw):
    return pick_types(raw.info, meg=True, eeg=False, stim=False,
                      ecg=False, eog=False, exclude='bads')

def _get_epochs():
    raw = _get_raw()
    raw.add_proj([], remove_existing=True)
    events = _get_events()
    picks = _get_picks(raw)
    # Use a subset of channels for plotting speed
    picks = picks[np.round(np.linspace(0, len(picks) - 1, n_chan)).astype(int)]
    picks[0] = 2  # make sure we have a magnetometer
    with warnings.catch_warnings(record=True):  # proj
        epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
                        baseline=(None, 0))
    epochs.info['bads'] = [epochs.ch_names[-1]]
    return epochs

def _get_epochs_delayed_ssp():
    raw = _get_raw()
    events = _get_events()
    picks = _get_picks(raw)
    reject = dict(mag=4e-12)
    epochs_delayed_ssp = Epochs(raw, events[:10], event_id, tmin, tmax,
                                picks=picks, baseline=(None, 0),
                                proj='delayed', reject=reject)
    return epochs_delayed_ssp

@slow_test
def test_plot_evoked():
    """Test plotting of evoked
    """
    import matplotlib.pyplot as plt
    evoked = _get_epochs().average()
    with warnings.catch_warnings(record=True):
        fig = evoked.plot(proj=True, hline=[1], exclude=[], window_title='foo')
        # Test a click
        ax = fig.get_axes()[0]
        line = ax.lines[0]
        _fake_click(fig, ax,
                    [line.get_xdata()[0], line.get_ydata()[0]], 'data')
        _fake_click(fig, ax,
                    [ax.get_xlim()[0], ax.get_ylim()[1]], 'data')
        # plot with bad channels excluded & spatial_colors & zorder
        evoked.plot(exclude='bads')
        evoked.plot(exclude=evoked.info['bads'], spatial_colors=True, gfp=True,
                    zorder='std')

        # test selective updating of dict keys is working.
        evoked.plot(hline=[1], units=dict(mag='femto foo'))
        evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
        evoked_delayed_ssp.plot(proj='interactive')
        evoked_delayed_ssp.apply_proj()
        assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                      proj='interactive')
        evoked_delayed_ssp.info['projs'] = []
        assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                      proj='interactive')
        assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                      proj='interactive', axes='foo')
        plt.close('all')

        # test GFP only
        evoked.plot(gfp='only')
        assert_raises(ValueError, evoked.plot, gfp='foo')

        evoked.plot_image(proj=True)
        # plot with bad channels excluded
        evoked.plot_image(exclude='bads', cmap='interactive')
        evoked.plot_image(exclude=evoked.info['bads'])  # does the same thing
        plt.close('all')

        evoked.plot_topo()  # should auto-find layout
        _butterfly_onselect(0, 200, ['mag', 'grad'], evoked)
        plt.close('all')

        cov = read_cov(cov_fname)
        cov['method'] = 'empirical'
        evoked.plot_white(cov)
        evoked.plot_white([cov, cov])

        # plot_compare_evoked single plot
        plot_compare_evoked(evoked)

        # test condition contrast, CI, color assignment
        colors = dict(red='r', blue='b')
        contrast_1, contrast_2 = evoked.copy(), evoked.copy()
        red.data *= 1.1
        blue.data *= 0.9
        contrast = dict('red/stim'=list(evoked.copy(), red),
                        'blue/stim'=list(evoked.copy(), blue))
        plot_compare_evoked(contrast, colors=colors,
                            picks=evoked.ch_names[0])

        # Hack to test plotting of maxfiltered data
        evoked_sss = evoked.copy()
        evoked_sss.info['proc_history'] = [dict(max_info=None)]
        evoked_sss.plot_white(cov)
        evoked_sss.plot_white(cov_fname)
        plt.close('all')
    evoked.plot_sensors()  # Test plot_sensors
    plt.close('all')

run_tests_if_main()
<commit_msg>Drop py2 support IMO<commit_after># Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Denis Engemann <denis.engemann@gmail.com>
#          Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#          Eric Larson <larson.eric.d@gmail.com>
#          Cathy Nangini <cnangini@gmail.com>
#          Mainak Jas <mainak@neuro.hut.fi>
#
# License: Simplified BSD

import os.path as op
import warnings

import numpy as np
from numpy.testing import assert_raises

from mne import io, read_events, Epochs, pick_types, read_cov
from mne.channels import read_layout
from mne.utils import slow_test, run_tests_if_main
from mne.viz.evoked import _butterfly_onselect, plot_compare_evoked
from mne.viz.utils import _fake_click

# Set our plotters to test mode
import matplotlib
matplotlib.use('Agg')  # for testing don't use X server

warnings.simplefilter('always')  # enable b/c these tests throw warnings

base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
evoked_fname = op.join(base_dir, 'test-ave.fif')
raw_fname = op.join(base_dir, 'test_raw.fif')
cov_fname = op.join(base_dir, 'test-cov.fif')
event_name = op.join(base_dir, 'test-eve.fif')
event_id, tmin, tmax = 1, -0.1, 0.1
n_chan = 6
layout = read_layout('Vectorview-all')

def _get_raw():
    return io.read_raw_fif(raw_fname, preload=False)

def _get_events():
    return read_events(event_name)

def _get_picks(raw):
    return pick_types(raw.info, meg=True, eeg=False, stim=False,
                      ecg=False, eog=False, exclude='bads')

def _get_epochs():
    raw = _get_raw()
    raw.add_proj([], remove_existing=True)
    events = _get_events()
    picks = _get_picks(raw)
    # Use a subset of channels for plotting speed
    picks = picks[np.round(np.linspace(0, len(picks) - 1, n_chan)).astype(int)]
    picks[0] = 2  # make sure we have a magnetometer
    with warnings.catch_warnings(record=True):  # proj
        epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
                        baseline=(None, 0))
    epochs.info['bads'] = [epochs.ch_names[-1]]
    return epochs

def _get_epochs_delayed_ssp():
    raw = _get_raw()
    events = _get_events()
    picks = _get_picks(raw)
    reject = dict(mag=4e-12)
    epochs_delayed_ssp = Epochs(raw, events[:10], event_id, tmin, tmax,
                                picks=picks, baseline=(None, 0),
                                proj='delayed', reject=reject)
    return epochs_delayed_ssp

@slow_test
def test_plot_evoked():
    """Test plotting of evoked
    """
    import matplotlib.pyplot as plt
    evoked = _get_epochs().average()
    with warnings.catch_warnings(record=True):
        fig = evoked.plot(proj=True, hline=[1], exclude=[], window_title='foo')
        # Test a click
        ax = fig.get_axes()[0]
        line = ax.lines[0]
        _fake_click(fig, ax,
                    [line.get_xdata()[0], line.get_ydata()[0]], 'data')
        _fake_click(fig, ax,
                    [ax.get_xlim()[0], ax.get_ylim()[1]], 'data')
        # plot with bad channels excluded & spatial_colors & zorder
        evoked.plot(exclude='bads')
        evoked.plot(exclude=evoked.info['bads'], spatial_colors=True, gfp=True,
                    zorder='std')

        # test selective updating of dict keys is working.
        evoked.plot(hline=[1], units=dict(mag='femto foo'))
        evoked_delayed_ssp = _get_epochs_delayed_ssp().average()
        evoked_delayed_ssp.plot(proj='interactive')
        evoked_delayed_ssp.apply_proj()
        assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                      proj='interactive')
        evoked_delayed_ssp.info['projs'] = []
        assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                      proj='interactive')
        assert_raises(RuntimeError, evoked_delayed_ssp.plot,
                      proj='interactive', axes='foo')
        plt.close('all')

        # test GFP only
        evoked.plot(gfp='only')
        assert_raises(ValueError, evoked.plot, gfp='foo')

        evoked.plot_image(proj=True)
        # plot with bad channels excluded
        evoked.plot_image(exclude='bads', cmap='interactive')
        evoked.plot_image(exclude=evoked.info['bads'])  # does the same thing
        plt.close('all')

        evoked.plot_topo()  # should auto-find layout
        _butterfly_onselect(0, 200, ['mag', 'grad'], evoked)
        plt.close('all')

        cov = read_cov(cov_fname)
        cov['method'] = 'empirical'
        evoked.plot_white(cov)
        evoked.plot_white([cov, cov])

        # plot_compare_evoked single plot
        plot_compare_evoked(evoked)

        # test condition contrast, CI, color assignment
        colors = dict(red='r', blue='b')
        contrast_1, contrast_2 = evoked.copy(), evoked.copy()
        red.data *= 1.1
        blue.data *= 0.9
        contrast = dict()
        dict["red/stim"] = list(evoked.copy(), red),
        dict["blue/stim"] = blue/stim=list(evoked.copy(), blue))
        plot_compare_evoked(contrast, colors=colors,
                            picks=evoked.ch_names[0])

        # Hack to test plotting of maxfiltered data
        evoked_sss = evoked.copy()
        evoked_sss.info['proc_history'] = [dict(max_info=None)]
        evoked_sss.plot_white(cov)
        evoked_sss.plot_white(cov_fname)
        plt.close('all')
    evoked.plot_sensors()  # Test plot_sensors
    plt.close('all')

run_tests_if_main()
<|endoftext|>


<commit_before>import explorerhat, signal, time
import cherrypy
import string

#pip install cherrypy
cherrypy.config.update("server.conf")

class RobotServer(object):
    def __init__(self, initialcommand="stop"):
        self.status = "stop"

        #Start listening for the IR sensors to change
        explorerhat.analog.one.changed(self.handle_analog)
        explorerhat.analog.two.changed(self.handle_analog)

        self.do_command(initialcommand)

    @cherrypy.expose
    def forward(self, speed=95):
        explorerhat.motor.one.forward(int(speed))
        explorerhat.motor.two.forward(int(speed))
        self.status = "forward"
        return self.status

    @cherrypy.expose
    def backward(self, speed=95):
        explorerhat.motor.one.backward(int(speed))
        explorerhat.motor.two.backward(int(speed))
        self.status = "backward"
        return self.status

    @cherrypy.expose
    def right(self, speed=95):
        explorerhat.motor.one.forward(int(speed))
        explorerhat.motor.two.backward(int(speed))
        self.status = "right"
        return self.status

    @cherrypy.expose
    def left(self, speed=95):
        explorerhat.motor.one.backward(int(speed))
        explorerhat.motor.two.forward(int(speed))
        self.status = "left"
        return self.status

    @cherrypy.expose
    def stop(self):
        explorerhat.motor.one.stop()
        explorerhat.motor.two.stop()
        self.status = "stop"
        return self.status

    @cherrypy.expose
    def index(self):
        return self.status

    def do_command(self, cmd=""):
        if (cmd == "forward"):
            self.forward()
        elif cmd == "backward":
            self.backward()
        elif cmd == "left":
            self.left()
        elif cmd == "right":
            self.right()
        elif cmd == "stop":
            self.stop()
        return self.status

    #Replicate original k9 interface
    @cherrypy.expose
    def k9(self, motor=""):
        return self.do_command(motor)

    def handle_analog(self, pin, value):
        if (value > 2):
            self.oldstatus = self.status
            self.status = "danger"
            explorerhat.motor.one.stop()
            explorerhat.motor.two.stop()
            time.sleep(0.4)
            explorerhat.motor.one.backward()
            explorerhat.motor.two.backward()
            time.sleep(0.7)
            explorerhat.motor.one.forward()
            explorerhat.motor.two.backward()
            time.sleep(0.5)

            self.do_command(self.oldstatus)

if __name__ == '__main__':
    cherrypy.quickstart(RobotServer(), config="app.conf")

<commit_msg>Update robotserver.py<commit_after>import explorerhat, signal, time
import cherrypy
import string

#pip install cherrypy
cherrypy.config.update("server.conf")

class RobotServer(object):
    def __init__(self, initialcommand="stop"):
        self.status = "stop"

        #Start listening for the IR sensors to change
        explorerhat.analog.one.changed(self.handle_analog)
        explorerhat.analog.two.changed(self.handle_analog)

        self.do_command(initialcommand)

    @cherrypy.expose
    def forward(self, speed=95):
        explorerhat.motor.one.forward(int(speed))
        explorerhat.motor.two.forward(int(speed))
        self.status = "forward"
        return self.status

    @cherrypy.expose
    def backward(self, speed=95):
        explorerhat.motor.one.backward(int(speed))
        explorerhat.motor.two.backward(int(speed))
        self.status = "backward"
        return self.status

    @cherrypy.expose
    def right(self, speed=95):
        explorerhat.motor.one.forward(int(speed))
        explorerhat.motor.two.backward(int(speed))
        self.status = "right"
        return self.status

    @cherrypy.expose
    def left(self, speed=95):
        explorerhat.motor.one.backward(int(speed))
        explorerhat.motor.two.forward(int(speed))
        self.status = "left"
        return self.status

    @cherrypy.expose
    def stop(self):
        explorerhat.motor.one.stop()
        explorerhat.motor.two.stop()
        self.status = "stop"
        return self.status

    @cherrypy.expose
    def index(self):
        return self.status

    def do_command(self, cmd=""):
        if (cmd == "forward"):
            self.forward()
        elif cmd == "backward":
            self.backward()
        elif cmd == "left":
            self.left()
        elif cmd == "right":
            self.right()
        elif cmd == "stop":
            self.stop()
        return self.status

    #Replicate original k9 interface
    @cherrypy.expose
    def k9(self, motor=""):
        return self.do_command(motor)

    def handle_analog(self, pin, value):
        print (pin.name, value)
        if (value > 2):
            self.oldstatus = self.status
            self.status = "danger"
            explorerhat.motor.one.stop()
            explorerhat.motor.two.stop()
            time.sleep(0.4)
            explorerhat.motor.one.backward()
            explorerhat.motor.two.backward()
            time.sleep(0.7)
            explorerhat.motor.one.forward()
            explorerhat.motor.two.backward()
            time.sleep(0.5)

            self.do_command(self.oldstatus)

if __name__ == '__main__':
    cherrypy.quickstart(RobotServer(), config="app.conf")

<|endoftext|>


<commit_before>import argparse
from functools import wraps
from io import StringIO
import logging
import os
import os.path as op
import shutil
from subprocess import check_output
from tempfile import mkstemp, mkdtemp
try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

import boto3
import botocore

logger = logging.getLogger('ob-pipelines')

s3 = boto3.client('s3')
s3_resource = boto3.resource('s3')

SCRATCH_DIR = os.environ.get('SCRATCH_DIR') or '/tmp'

def csv_to_s3(df, s3_path):
    """Write pandas DataFrame to S3 object"""

    # Write dataframe to buffer
    csv_buffer = StringIO()
    df.to_csv(csv_buffer)

    # Upload CSV to S3
    bucket, key = path_to_bucket_and_key(s3_path)
    s3_resource.Object(bucket, key).put(Body=csv_buffer.getvalue())

def create_tmp_from_key(key):
    """Create local temp file or folder depending on key path"""
    if key.endswith('/'):
        local_tmp = mkdtemp(
            prefix=op.basename(key.rstrip('/')) + '_',
            dir=SCRATCH_DIR)
        local_tmp = local_tmp if local_tmp.endswith('/') else local_tmp + '/'
    else:
        fname = op.basename(key)
        base, ext = op.splitext(fname)
        _, local_tmp = mkstemp(prefix=base + '_',
                               suffix=ext,
                               dir=SCRATCH_DIR)
    return local_tmp

def path_to_bucket_and_key(path):
    (scheme, netloc, path, params, query, fragment) = urlparse(path)
    path_without_initial_slash = path[1:]
    return netloc, path_without_initial_slash

def key_exists(bucket, key):
    """Check for existence of S3 key"""
    try:
        if key.endswith('/'):
            return 'Contents' in s3.list_objects(Bucket=bucket, Prefix=key)
        else:
            s3_resource.Object(bucket, key).load()
            return True
    except botocore.exceptions.ClientError as e:
            return False

def download_folder(bucket, prefix, folder):
    response = s3.list_objects(
        Bucket=bucket,
        Prefix=prefix,
        Delimiter='/'
    )
    if 'Contents' not in response and response['HTTPStatusCode'] == 200:
        raise botocore.exceptions.ClientError
    for key_dict in response['Contents']:
        key = key_dict['Key']
        fpath = op.join(folder, op.basename(key))
        s3.download_file(bucket, key, fpath)

def upload_folder(folder, bucket, prefix):
    # Upload directory
    for fname in os.listdir(folder):
        fpath = op.join(folder, fname)
        key = prefix + fname
        s3.upload_file(fpath, bucket, key)

def download_file_or_folder(s3_path, local_path):
    """Dispatch S3 download depending on key path"""
    bucket, key = path_to_bucket_and_key(s3_path)
    if key.endswith('/'):
        download_folder(bucket, key, local_path)
    else:
        s3.download_file(bucket, key, local_path)

def upload_file_or_folder(s3_path, local_path):
    """Dispatch S3 upload depending on local path"""
    bucket, key = path_to_bucket_and_key(s3_path)
    if op.isfile(local_path):
        s3.upload_file(local_path, bucket, key)
    elif op.isdir(local_path):
        upload_folder(local_path, bucket, key)

def remove_file_or_folder(fpath):
    if op.isdir(fpath):
        shutil.rmtree(fpath)
    else:
        os.remove(fpath)

def swap_args(args, rm_local_outpath=False):
    """Swap S3 paths in arguments with local paths

    If the S3 path exists, it's an input, download first and swap the arg
    with a temporary filepath. Otherwise, it's an output, save for upload
    after the command.

    Returns:
        tuple of (local_args, s3_downloads, s3_uploads)

        where new_args contains the new argument list with local paths,
        and s3_outputs is a dict mapping local filepaths to s3 paths to
        transfer after execution.
    """
    s3_uploads = {}
    s3_downloads = {}
    local_args = []
    for arg in args:
        if not arg.startswith('s3://'):
            local_args.append(arg)
            continue

        src_bucket, src_key = path_to_bucket_and_key(arg)
        local_tmp = create_tmp_from_key(src_key)

        # If key exists, add path to downloads, otherwise add path to
        # uploads and remove the file or folder
        if key_exists(src_bucket, src_key):
            s3_downloads[arg] = local_tmp
        else:
            s3_uploads[arg] = local_tmp
            if rm_local_outpath:
                remove_file_or_folder(local_tmp)

        local_args.append(local_tmp)

    return local_args, s3_downloads, s3_uploads

def s3args(rm_local_outpath=False):
    """Sync S3 path arguments with behind-the-scenes S3 transfers

    When decorating a function, s3args downloads all arguments that
    look like S3 paths to temporary files and swaps the local temp
    filepath as the new argument. If the S3 path does not exist, it
    is assumed to be an output, and s3args uploads the tempfile
    back to S3 after the command is complete.

    This works great with Luigi, which checks for existence of inputs
    and non-existence of outputs before running a Task.

    Keyword args are passed directly without syncing, for now.
    """
    def s3args_decorator(f):
        @wraps(f)
        def local_fn(*args, **kwargs):

            # Swap the S3 path arguments for local temporary files/folders
            local_args, s3_downloads, s3_uploads = swap_args(args, rm_local_outpath=rm_local_outpath)

            # Download inputs
            logger.info('syncing from S3')
            for s3_path, local_path in s3_downloads.items():
                download_file_or_folder(s3_path, local_path)

            # Run command and save output
            out = f(*local_args, **kwargs)

            # Upload outputs
            logger.info('uploading to S3')
            for s3_path, local_path in s3_uploads.items():
                upload_file_or_folder(s3_path, local_path)

            # Remove local files
            local_paths = list(s3_downloads.values()) + list(s3_uploads.values())
            for local_path in local_paths:
                remove_file_or_folder(local_path)

            return out

        return local_fn
    return s3args_decorator

def s3wrap():
    parser = argparse.ArgumentParser(description='Swap S3 commands for temporary local paths and download')
    parser.add_argument('--rm-local-outpath', '-r', action='store_true', help='Remove local tmp output file/folder before executing command')
    parser.add_argument('command', nargs=argparse.REMAINDER)
    args = parser.parse_args()

    @s3args(rm_local_outpath=args.rm_local_outpath)
    def sync_and_run(*cmds):
        print('Running:\n{}'.format(' '.join(cmds)))
        return check_output(cmds)

    out = sync_and_run(*args.command)
    print(out.decode())

<commit_msg>Download BAM indexes from S3 automatically if they exist<commit_after>import argparse
from functools import wraps
from io import StringIO
import logging
import os
import os.path as op
import shutil
from subprocess import check_output
from tempfile import mkstemp, mkdtemp
try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

import boto3
import botocore

logger = logging.getLogger('ob-pipelines')

s3 = boto3.client('s3')
s3_resource = boto3.resource('s3')

SCRATCH_DIR = os.environ.get('SCRATCH_DIR') or '/tmp'

def csv_to_s3(df, s3_path):
    """Write pandas DataFrame to S3 object"""

    # Write dataframe to buffer
    csv_buffer = StringIO()
    df.to_csv(csv_buffer)

    # Upload CSV to S3
    bucket, key = path_to_bucket_and_key(s3_path)
    s3_resource.Object(bucket, key).put(Body=csv_buffer.getvalue())

def create_tmp_from_key(key):
    """Create local temp file or folder depending on key path"""
    if key.endswith('/'):
        local_tmp = mkdtemp(
            prefix=op.basename(key.rstrip('/')) + '_',
            dir=SCRATCH_DIR)
        local_tmp = local_tmp if local_tmp.endswith('/') else local_tmp + '/'
    else:
        fname = op.basename(key)
        base, ext = op.splitext(fname)
        _, local_tmp = mkstemp(prefix=base + '_',
                               suffix=ext,
                               dir=SCRATCH_DIR)
    return local_tmp

def path_to_bucket_and_key(path):
    (scheme, netloc, path, params, query, fragment) = urlparse(path)
    path_without_initial_slash = path[1:]
    return netloc, path_without_initial_slash

def key_exists(bucket, key):
    """Check for existence of S3 key"""
    try:
        if key.endswith('/'):
            return 'Contents' in s3.list_objects(Bucket=bucket, Prefix=key)
        else:
            s3_resource.Object(bucket, key).load()
            return True
    except botocore.exceptions.ClientError as e:
            return False

def download_folder(bucket, prefix, folder):
    response = s3.list_objects(
        Bucket=bucket,
        Prefix=prefix,
        Delimiter='/'
    )
    if 'Contents' not in response and response['HTTPStatusCode'] == 200:
        raise botocore.exceptions.ClientError
    for key_dict in response['Contents']:
        key = key_dict['Key']
        fpath = op.join(folder, op.basename(key))
        s3.download_file(bucket, key, fpath)

def upload_folder(folder, bucket, prefix):
    # Upload directory
    for fname in os.listdir(folder):
        fpath = op.join(folder, fname)
        key = prefix + fname
        s3.upload_file(fpath, bucket, key)

def download_file_or_folder(s3_path, local_path):
    """Dispatch S3 download depending on key path"""
    bucket, key = path_to_bucket_and_key(s3_path)
    if key.endswith('/'):
        download_folder(bucket, key, local_path)
    else:
        s3.download_file(bucket, key, local_path)
        if key.endswith('.bam'):
            # Always download a BAM index if it exists
            possible_index_keys = [key + '.bai', key.replace('.bam', '.bai')]
            for index_key in possible_index_keys:
                if key_exists(bucket, index_key):
                    s3.download_file(bucket, index_key, local_path + '.bai')

def upload_file_or_folder(s3_path, local_path):
    """Dispatch S3 upload depending on local path"""
    bucket, key = path_to_bucket_and_key(s3_path)
    if op.isfile(local_path):
        s3.upload_file(local_path, bucket, key)
    elif op.isdir(local_path):
        upload_folder(local_path, bucket, key)

def remove_file_or_folder(fpath):
    if op.isdir(fpath):
        shutil.rmtree(fpath)
    else:
        os.remove(fpath)

def swap_args(args, rm_local_outpath=False):
    """Swap S3 paths in arguments with local paths

    If the S3 path exists, it's an input, download first and swap the arg
    with a temporary filepath. Otherwise, it's an output, save for upload
    after the command.

    Returns:
        tuple of (local_args, s3_downloads, s3_uploads)

        where new_args contains the new argument list with local paths,
        and s3_outputs is a dict mapping local filepaths to s3 paths to
        transfer after execution.
    """
    s3_uploads = {}
    s3_downloads = {}
    local_args = []
    for arg in args:
        if not arg.startswith('s3://'):
            local_args.append(arg)
            continue

        src_bucket, src_key = path_to_bucket_and_key(arg)
        local_tmp = create_tmp_from_key(src_key)

        # If key exists, add path to downloads, otherwise add path to
        # uploads and remove the file or folder
        if key_exists(src_bucket, src_key):
            s3_downloads[arg] = local_tmp
        else:
            s3_uploads[arg] = local_tmp
            if rm_local_outpath:
                remove_file_or_folder(local_tmp)

        local_args.append(local_tmp)

    return local_args, s3_downloads, s3_uploads

def s3args(rm_local_outpath=False):
    """Sync S3 path arguments with behind-the-scenes S3 transfers

    When decorating a function, s3args downloads all arguments that
    look like S3 paths to temporary files and swaps the local temp
    filepath as the new argument. If the S3 path does not exist, it
    is assumed to be an output, and s3args uploads the tempfile
    back to S3 after the command is complete.

    This works great with Luigi, which checks for existence of inputs
    and non-existence of outputs before running a Task.

    Keyword args are passed directly without syncing, for now.
    """
    def s3args_decorator(f):
        @wraps(f)
        def local_fn(*args, **kwargs):

            # Swap the S3 path arguments for local temporary files/folders
            local_args, s3_downloads, s3_uploads = swap_args(args, rm_local_outpath=rm_local_outpath)

            # Download inputs
            logger.info('syncing from S3')
            for s3_path, local_path in s3_downloads.items():
                download_file_or_folder(s3_path, local_path)

            # Run command and save output
            out = f(*local_args, **kwargs)

            # Upload outputs
            logger.info('uploading to S3')
            for s3_path, local_path in s3_uploads.items():
                upload_file_or_folder(s3_path, local_path)

            # Remove local files
            local_paths = list(s3_downloads.values()) + list(s3_uploads.values())
            for local_path in local_paths:
                remove_file_or_folder(local_path)

            return out

        return local_fn
    return s3args_decorator

def s3wrap():
    parser = argparse.ArgumentParser(description='Swap S3 commands for temporary local paths and download')
    parser.add_argument('--rm-local-outpath', '-r', action='store_true', help='Remove local tmp output file/folder before executing command')
    parser.add_argument('command', nargs=argparse.REMAINDER)
    args = parser.parse_args()

    @s3args(rm_local_outpath=args.rm_local_outpath)
    def sync_and_run(*cmds):
        print('Running:\n{}'.format(' '.join(cmds)))
        return check_output(cmds)

    out = sync_and_run(*args.command)
    print(out.decode())

<|endoftext|>


<commit_before>#!/usr/bin/env python
"""beanstalkc - A beanstalkd Client Library for Python"""

__license__ = '''
Copyright (C) 2008-2012 Andreas Bolka

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

__version__ = '0.3.0'

import logging
import socket

DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 11300
DEFAULT_PRIORITY = 2 ** 31
DEFAULT_TTR = 120

class BeanstalkcException(Exception): pass
class UnexpectedResponse(BeanstalkcException): pass
class CommandFailed(BeanstalkcException): pass
class DeadlineSoon(BeanstalkcException): pass

class SocketError(BeanstalkcException):
    @staticmethod
    def wrap(wrapped_function, *args, **kwargs):
        try:
            return wrapped_function(*args, **kwargs)
        except socket.error, err:
            raise SocketError(err)

class Connection(object):
    def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT, parse_yaml=True,
                 connect_timeout=socket.getdefaulttimeout()):
        if parse_yaml is True:
            try:
                parse_yaml = __import__('yaml').load
            except ImportError:
                logging.error('Failed to load PyYAML, will not parse YAML')
                parse_yaml = False
        self._connect_timeout = connect_timeout
        self._parse_yaml = parse_yaml or (lambda x: x)
        self.host = host
        self.port = port
        self.connect()

    def connect(self):
        """Connect to beanstalkd server."""
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._socket.settimeout(self._connect_timeout)
        SocketError.wrap(self._socket.connect, (self.host, self.port))
        self._socket.settimeout(None)
        self._socket_file = self._socket.makefile('rb')

    def close(self):
        """Close connection to server."""
        try:
            self._socket.sendall('quit\r\n')
            self._socket.close()
        except socket.error:
            pass

    def reconnect(self):
        """Re-connect to server."""
        self.close()
        self.connect()

    def _interact(self, command, expected_ok, expected_err=[]):
        SocketError.wrap(self._socket.sendall, command)
        status, results = self._read_response()
        if status in expected_ok:
            return results
        elif status in expected_err:
            raise CommandFailed(command.split()[0], status, results)
        else:
            raise UnexpectedResponse(command.split()[0], status, results)

    def _read_response(self):
        line = SocketError.wrap(self._socket_file.readline)
        if not line:
            raise SocketError()
        response = line.split()
        return response[0], response[1:]

    def _read_body(self, size):
        body = SocketError.wrap(self._socket_file.read, size)
        SocketError.wrap(self._socket_file.read, 2)  # trailing crlf
        if size > 0 and not body:
            raise SocketError()
        return body

    def _interact_value(self, command, expected_ok, expected_err=[]):
        return self._interact(command, expected_ok, expected_err)[0]

    def _interact_job(self, command, expected_ok, expected_err, reserved=True):
        jid, size = self._interact(command, expected_ok, expected_err)
        body = self._read_body(int(size))
        return Job(self, int(jid), body, reserved)

    def _interact_yaml(self, command, expected_ok, expected_err=[]):
        size, = self._interact(command, expected_ok, expected_err)
        body = self._read_body(int(size))
        return self._parse_yaml(body)

    def _interact_peek(self, command):
        try:
            return self._interact_job(command, ['FOUND'], ['NOT_FOUND'], False)
        except CommandFailed, (_, _status, _results):
            return None

    # -- public interface --

    def put(self, body, priority=DEFAULT_PRIORITY, delay=0, ttr=DEFAULT_TTR):
        """Put a job into the current tube. Returns job id."""
        assert isinstance(body, str), 'Job body must be a str instance'
        jid = self._interact_value(
                'put %d %d %d %d\r\n%s\r\n' %
                    (priority, delay, ttr, len(body), body),
                ['INSERTED', 'BURIED'], ['JOB_TOO_BIG'])
        return int(jid)

    def reserve(self, timeout=None):
        """Reserve a job from one of the watched tubes, with optional timeout
        in seconds. Returns a Job object, or None if the request times out."""
        if timeout is not None:
            command = 'reserve-with-timeout %d\r\n' % timeout
        else:
            command = 'reserve\r\n'
        try:
            return self._interact_job(command,
                                      ['RESERVED'],
                                      ['DEADLINE_SOON', 'TIMED_OUT'])
        except CommandFailed, (_, status, results):
            if status == 'TIMED_OUT':
                return None
            elif status == 'DEADLINE_SOON':
                raise DeadlineSoon(results)

    def kick(self, bound=1):
        """Kick at most bound jobs into the ready queue."""
        return int(self._interact_value('kick %d\r\n' % bound, ['KICKED']))

    def kick_job(self, jid):
        """Kick a specific job into the ready queue."""
        self._interact('kick-job %d\r\n' % jid, ['KICKED'], ['NOT_FOUND'])

    def peek(self, jid):
        """Peek at a job. Returns a Job, or None."""
        return self._interact_peek('peek %d\r\n' % jid)

    def peek_ready(self):
        """Peek at next ready job. Returns a Job, or None."""
        return self._interact_peek('peek-ready\r\n')

    def peek_delayed(self):
        """Peek at next delayed job. Returns a Job, or None."""
        return self._interact_peek('peek-delayed\r\n')

    def peek_buried(self):
        """Peek at next buried job. Returns a Job, or None."""
        return self._interact_peek('peek-buried\r\n')

    def tubes(self):
        """Return a list of all existing tubes."""
        return self._interact_yaml('list-tubes\r\n', ['OK'])

    def using(self):
        """Return the tube currently being used."""
        return self._interact_value('list-tube-used\r\n', ['USING'])

    def use(self, name):
        """Use a given tube."""
        return self._interact_value('use %s\r\n' % name, ['USING'])

    def watching(self):
        """Return a list of all tubes being watched."""
        return self._interact_yaml('list-tubes-watched\r\n', ['OK'])

    def watch(self, name):
        """Watch a given tube."""
        return int(self._interact_value('watch %s\r\n' % name, ['WATCHING']))

    def ignore(self, name):
        """Stop watching a given tube."""
        try:
            return int(self._interact_value('ignore %s\r\n' % name,
                                            ['WATCHING'],
                                            ['NOT_IGNORED']))
        except CommandFailed:
            return 1

    def stats(self):
        """Return a dict of beanstalkd statistics."""
        return self._interact_yaml('stats\r\n', ['OK'])

    def stats_tube(self, name):
        """Return a dict of stats about a given tube."""
        return self._interact_yaml('stats-tube %s\r\n' % name,
                                   ['OK'],
                                   ['NOT_FOUND'])

    def pause_tube(self, name, delay):
        """Pause a tube for a given delay time, in seconds."""
        self._interact('pause-tube %s %d\r\n' % (name, delay),
                       ['PAUSED'],
                       ['NOT_FOUND'])

    # -- job interactors --

    def delete(self, jid):
        """Delete a job, by job id."""
        self._interact('delete %d\r\n' % jid, ['DELETED'], ['NOT_FOUND'])

    def release(self, jid, priority=DEFAULT_PRIORITY, delay=0):
        """Release a reserved job back into the ready queue."""
        self._interact('release %d %d %d\r\n' % (jid, priority, delay),
                       ['RELEASED', 'BURIED'],
                       ['NOT_FOUND'])

    def bury(self, jid, priority=DEFAULT_PRIORITY):
        """Bury a job, by job id."""
        self._interact('bury %d %d\r\n' % (jid, priority),
                       ['BURIED'],
                       ['NOT_FOUND'])

    def touch(self, jid):
        """Touch a job, by job id, requesting more time to work on a reserved
        job before it expires."""
        self._interact('touch %d\r\n' % jid, ['TOUCHED'], ['NOT_FOUND'])

    def stats_job(self, jid):
        """Return a dict of stats about a job, by job id."""
        return self._interact_yaml('stats-job %d\r\n' % jid,
                                   ['OK'],
                                   ['NOT_FOUND'])

class Job(object):
    def __init__(self, conn, jid, body, reserved=True):
        self.conn = conn
        self.jid = jid
        self.body = body
        self.reserved = reserved

    def _priority(self):
        stats = self.stats()
        if isinstance(stats, dict):
            return stats['pri']
        return DEFAULT_PRIORITY

    # -- public interface --

    def delete(self):
        """Delete this job."""
        self.conn.delete(self.jid)
        self.reserved = False

    def release(self, priority=None, delay=0):
        """Release this job back into the ready queue."""
        if self.reserved:
            self.conn.release(self.jid, priority or self._priority(), delay)
            self.reserved = False

    def bury(self, priority=None):
        """Bury this job."""
        if self.reserved:
            self.conn.bury(self.jid, priority or self._priority())
            self.reserved = False

    def kick(self):
        """Kick this job alive."""
        self.conn.kick_job(self.jid)

    def touch(self):
        """Touch this reserved job, requesting more time to work on it before
        it expires."""
        if self.reserved:
            self.conn.touch(self.jid)

    def stats(self):
        """Return a dict of stats about this job."""
        return self.conn.stats_job(self.jid)

if __name__ == '__main__':
    import nose
    nose.main(argv=['nosetests', '-c', '.nose.cfg'])
<commit_msg>Wrapped _socket.close in its own try-except. Fixes the bug described in Issue #34 in beanstalkc: https://github.com/earl/beanstalkc/issues/34<commit_after>#!/usr/bin/env python
"""beanstalkc - A beanstalkd Client Library for Python"""

__license__ = '''
Copyright (C) 2008-2012 Andreas Bolka

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

__version__ = '0.3.0'

import logging
import socket

DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 11300
DEFAULT_PRIORITY = 2 ** 31
DEFAULT_TTR = 120

class BeanstalkcException(Exception): pass
class UnexpectedResponse(BeanstalkcException): pass
class CommandFailed(BeanstalkcException): pass
class DeadlineSoon(BeanstalkcException): pass

class SocketError(BeanstalkcException):
    @staticmethod
    def wrap(wrapped_function, *args, **kwargs):
        try:
            return wrapped_function(*args, **kwargs)
        except socket.error, err:
            raise SocketError(err)

class Connection(object):
    def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT, parse_yaml=True,
                 connect_timeout=socket.getdefaulttimeout()):
        if parse_yaml is True:
            try:
                parse_yaml = __import__('yaml').load
            except ImportError:
                logging.error('Failed to load PyYAML, will not parse YAML')
                parse_yaml = False
        self._connect_timeout = connect_timeout
        self._parse_yaml = parse_yaml or (lambda x: x)
        self.host = host
        self.port = port
        self.connect()

    def connect(self):
        """Connect to beanstalkd server."""
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._socket.settimeout(self._connect_timeout)
        SocketError.wrap(self._socket.connect, (self.host, self.port))
        self._socket.settimeout(None)
        self._socket_file = self._socket.makefile('rb')

    def close(self):
        """Close connection to server."""
        try:
            self._socket.sendall('quit\r\n')
        except socket.error:
            pass
        try:
            self._socket.close()
        except socket.error:
            pass

    def reconnect(self):
        """Re-connect to server."""
        self.close()
        self.connect()

    def _interact(self, command, expected_ok, expected_err=[]):
        SocketError.wrap(self._socket.sendall, command)
        status, results = self._read_response()
        if status in expected_ok:
            return results
        elif status in expected_err:
            raise CommandFailed(command.split()[0], status, results)
        else:
            raise UnexpectedResponse(command.split()[0], status, results)

    def _read_response(self):
        line = SocketError.wrap(self._socket_file.readline)
        if not line:
            raise SocketError()
        response = line.split()
        return response[0], response[1:]

    def _read_body(self, size):
        body = SocketError.wrap(self._socket_file.read, size)
        SocketError.wrap(self._socket_file.read, 2)  # trailing crlf
        if size > 0 and not body:
            raise SocketError()
        return body

    def _interact_value(self, command, expected_ok, expected_err=[]):
        return self._interact(command, expected_ok, expected_err)[0]

    def _interact_job(self, command, expected_ok, expected_err, reserved=True):
        jid, size = self._interact(command, expected_ok, expected_err)
        body = self._read_body(int(size))
        return Job(self, int(jid), body, reserved)

    def _interact_yaml(self, command, expected_ok, expected_err=[]):
        size, = self._interact(command, expected_ok, expected_err)
        body = self._read_body(int(size))
        return self._parse_yaml(body)

    def _interact_peek(self, command):
        try:
            return self._interact_job(command, ['FOUND'], ['NOT_FOUND'], False)
        except CommandFailed, (_, _status, _results):
            return None

    # -- public interface --

    def put(self, body, priority=DEFAULT_PRIORITY, delay=0, ttr=DEFAULT_TTR):
        """Put a job into the current tube. Returns job id."""
        assert isinstance(body, str), 'Job body must be a str instance'
        jid = self._interact_value(
                'put %d %d %d %d\r\n%s\r\n' %
                    (priority, delay, ttr, len(body), body),
                ['INSERTED', 'BURIED'], ['JOB_TOO_BIG'])
        return int(jid)

    def reserve(self, timeout=None):
        """Reserve a job from one of the watched tubes, with optional timeout
        in seconds. Returns a Job object, or None if the request times out."""
        if timeout is not None:
            command = 'reserve-with-timeout %d\r\n' % timeout
        else:
            command = 'reserve\r\n'
        try:
            return self._interact_job(command,
                                      ['RESERVED'],
                                      ['DEADLINE_SOON', 'TIMED_OUT'])
        except CommandFailed, (_, status, results):
            if status == 'TIMED_OUT':
                return None
            elif status == 'DEADLINE_SOON':
                raise DeadlineSoon(results)

    def kick(self, bound=1):
        """Kick at most bound jobs into the ready queue."""
        return int(self._interact_value('kick %d\r\n' % bound, ['KICKED']))

    def kick_job(self, jid):
        """Kick a specific job into the ready queue."""
        self._interact('kick-job %d\r\n' % jid, ['KICKED'], ['NOT_FOUND'])

    def peek(self, jid):
        """Peek at a job. Returns a Job, or None."""
        return self._interact_peek('peek %d\r\n' % jid)

    def peek_ready(self):
        """Peek at next ready job. Returns a Job, or None."""
        return self._interact_peek('peek-ready\r\n')

    def peek_delayed(self):
        """Peek at next delayed job. Returns a Job, or None."""
        return self._interact_peek('peek-delayed\r\n')

    def peek_buried(self):
        """Peek at next buried job. Returns a Job, or None."""
        return self._interact_peek('peek-buried\r\n')

    def tubes(self):
        """Return a list of all existing tubes."""
        return self._interact_yaml('list-tubes\r\n', ['OK'])

    def using(self):
        """Return the tube currently being used."""
        return self._interact_value('list-tube-used\r\n', ['USING'])

    def use(self, name):
        """Use a given tube."""
        return self._interact_value('use %s\r\n' % name, ['USING'])

    def watching(self):
        """Return a list of all tubes being watched."""
        return self._interact_yaml('list-tubes-watched\r\n', ['OK'])

    def watch(self, name):
        """Watch a given tube."""
        return int(self._interact_value('watch %s\r\n' % name, ['WATCHING']))

    def ignore(self, name):
        """Stop watching a given tube."""
        try:
            return int(self._interact_value('ignore %s\r\n' % name,
                                            ['WATCHING'],
                                            ['NOT_IGNORED']))
        except CommandFailed:
            return 1

    def stats(self):
        """Return a dict of beanstalkd statistics."""
        return self._interact_yaml('stats\r\n', ['OK'])

    def stats_tube(self, name):
        """Return a dict of stats about a given tube."""
        return self._interact_yaml('stats-tube %s\r\n' % name,
                                   ['OK'],
                                   ['NOT_FOUND'])

    def pause_tube(self, name, delay):
        """Pause a tube for a given delay time, in seconds."""
        self._interact('pause-tube %s %d\r\n' % (name, delay),
                       ['PAUSED'],
                       ['NOT_FOUND'])

    # -- job interactors --

    def delete(self, jid):
        """Delete a job, by job id."""
        self._interact('delete %d\r\n' % jid, ['DELETED'], ['NOT_FOUND'])

    def release(self, jid, priority=DEFAULT_PRIORITY, delay=0):
        """Release a reserved job back into the ready queue."""
        self._interact('release %d %d %d\r\n' % (jid, priority, delay),
                       ['RELEASED', 'BURIED'],
                       ['NOT_FOUND'])

    def bury(self, jid, priority=DEFAULT_PRIORITY):
        """Bury a job, by job id."""
        self._interact('bury %d %d\r\n' % (jid, priority),
                       ['BURIED'],
                       ['NOT_FOUND'])

    def touch(self, jid):
        """Touch a job, by job id, requesting more time to work on a reserved
        job before it expires."""
        self._interact('touch %d\r\n' % jid, ['TOUCHED'], ['NOT_FOUND'])

    def stats_job(self, jid):
        """Return a dict of stats about a job, by job id."""
        return self._interact_yaml('stats-job %d\r\n' % jid,
                                   ['OK'],
                                   ['NOT_FOUND'])

class Job(object):
    def __init__(self, conn, jid, body, reserved=True):
        self.conn = conn
        self.jid = jid
        self.body = body
        self.reserved = reserved

    def _priority(self):
        stats = self.stats()
        if isinstance(stats, dict):
            return stats['pri']
        return DEFAULT_PRIORITY

    # -- public interface --

    def delete(self):
        """Delete this job."""
        self.conn.delete(self.jid)
        self.reserved = False

    def release(self, priority=None, delay=0):
        """Release this job back into the ready queue."""
        if self.reserved:
            self.conn.release(self.jid, priority or self._priority(), delay)
            self.reserved = False

    def bury(self, priority=None):
        """Bury this job."""
        if self.reserved:
            self.conn.bury(self.jid, priority or self._priority())
            self.reserved = False

    def kick(self):
        """Kick this job alive."""
        self.conn.kick_job(self.jid)

    def touch(self):
        """Touch this reserved job, requesting more time to work on it before
        it expires."""
        if self.reserved:
            self.conn.touch(self.jid)

    def stats(self):
        """Return a dict of stats about this job."""
        return self.conn.stats_job(self.jid)

if __name__ == '__main__':
    import nose
    nose.main(argv=['nosetests', '-c', '.nose.cfg'])
<|endoftext|>


<commit_before>from subprocess import check_output, check_call
from sys import stdout, stderr, exit, argv, platform
from os import path, chdir, environ
import copy

PYTHONBUILD_DIR = path.dirname(path.realpath(__file__))

def python_build(*args):
    # Get a copy of system environment vars, so it can be modified accordingly and passed on.
    environment_vars = copy.copy(environ)

    # Mac OS special config from https://github.com/yyuu/pyenv/wiki/Common-build-problems
    if platform == "darwin":
        osx_version = check_output(["sw_vers", "-productVersion"]).decode('utf8').replace('\n', '')
        if osx_version in ["10.9", "10.10"]:
            sdk_path = check_output(["xcrun", "--show-sdk-path"]).decode('utf8').replace('\n', '')
            environment_vars.update({"CFLAGS": "-I{}/usr/include".format(sdk_path)})

    # Get the full path to the python-build executable
    pyenv_build_bin = path.join(PYTHONBUILD_DIR, "bin", "python-build")

    # Pass on environment vars and args to pyenv build script
    check_call([pyenv_build_bin] + list(args), env=environment_vars)

def run():
    python_build(*argv[1:])
<commit_msg>BUG : Fixed problem on yosemite where version reporte was 10.10.x and the environment variable was not set properly.<commit_after>from subprocess import check_output, check_call
from sys import stdout, stderr, exit, argv, platform
from os import path, chdir, environ
import copy

PYTHONBUILD_DIR = path.dirname(path.realpath(__file__))

def python_build(*args):
    # Get a copy of system environment vars, so it can be modified accordingly and passed on.
    environment_vars = copy.copy(environ)

    # Mac OS special config from https://github.com/yyuu/pyenv/wiki/Common-build-problems
    if platform == "darwin":
        osx_version = check_output(["sw_vers", "-productVersion"]).decode('utf8').replace('\n', '')
        if "10.9" in osx_version or "10.10" in osx_version:
            sdk_path = check_output(["xcrun", "--show-sdk-path"]).decode('utf8').replace('\n', '')
            environment_vars.update({"CFLAGS": "-I{}/usr/include".format(sdk_path)})

    # Get the full path to the python-build executable
    pyenv_build_bin = path.join(PYTHONBUILD_DIR, "bin", "python-build")

    # Pass on environment vars and args to pyenv build script
    check_call([pyenv_build_bin] + list(args), env=environment_vars)

def run():
    python_build(*argv[1:])
<|endoftext|>


<commit_before>import warnings

import numpy as np
import pandas as pd

import pymc3 as pm
import pymc3.stats

def trace_to_dataframe(trace, model=None, varnames=None,
                       include_transformed=False, log_post=False):
    """
    Convert a PyMC3 trace to a Pandas DataFrame

    To add: Compute logp for each point using model.logp().
    """
    df = pm.trace_to_dataframe(trace, chains=[0])
    for stat in trace.stat_names:
        if stat in df.columns:
            warnings.warn('`' + stat + '` is in the variable names.`'
                          + ' Not adding this statistic.')
        else:
            df[stat] = trace.get_sampler_stats(stat, chains=[0])
    if 'chain' in df.columns:
        warnings.warn('`chain` is in the variable name.`'
                          + ' Not adding this statistic.')
    else:
        df['chain'] = np.array([0]*len(df), dtype=int)

    if len(trace.chains) == 1:
        return df

    for chain in trace.chains[1:]:
        df_app = pm.trace_to_dataframe(trace, chains=[chain])
        for stat in trace.stat_names:
            if stat not in df_app.columns:
                df_app[stat] = trace.get_sampler_stats(stat, chains=[chain])
        if 'chain' not in df_app.columns:
            df_app['chain'] = np.array([chain]*len(df_app))

        df = df.append(df_app, ignore_index=True)

    if log_post:
        # Extract the model from context if necessary
        model = pm.modelcontext(model)

        logp = pymc3.stats._log_post_trace(trace, model).sum(axis=1)
        df['log_posterior'] = logp

    return df

def Jeffreys(name, lower=None, upper=None, shape=None):
    """
    Create a Jeffreys prior for a scale parameter.

    Parameters
    ----------
    name : str
        Name of the variable.
    lower : float, > 0
        Minimum value the variable can take.
    upper : float, > `lower`
        Maximum value the variable can take.
    shape: int or tuple of ints, default 1
        Shape of array of variables. If 1, then a single scalar.

    Returns
    -------
    output : pymc3 distribution
        Distribution for Jeffreys prior.
    """
    # Check inputs
    if type(name) != str:
        raise RuntimeError('`name` must be a string.')
    if lower is None or upper is None:
        raise RuntimeError('`lower` and `upper` must be provided.')
    if lower <= 0:
        raise RuntimeError('`lower` must be > 0.')
    if upper <= lower:
        raise RuntimeError('`upper` must be > `lower`.')

    # Set up Jeffreys prior
    if shape is None:
        log_var = pm.Uniform('log_' + name,
                             lower=np.log(lower),
                             upper=np.log(upper))
    else:
        log_var = pm.Uniform('log_' + name,
                             lower=np.log(lower),
                             upper=np.log(upper),
                             shape=shape)
    var = pm.Deterministic(name, pm.math.exp(log_var))

    return var

def ReparametrizedNormal(name, mu=None, sd=None, shape=1):
    """
    Create a reparametrized Normally distributed random variable.

    Parameters
    ----------
    name : str
        Name of the variable.
    mu : float
        Mean of Normal distribution.
    sd : float, > 0
        Standard deviation of Normal distribution.
    shape: int or tuple of ints, default 1
        Shape of array of variables. If 1, then a single scalar.

    Returns
    -------
    output : pymc3 distribution
        Distribution for a reparametrized Normal distribution.

    Notes
    -----
    .. The reparametrization procedure allows the sampler to sample
       a standard normal distribution, and then do a deterministic
       reparametrization to achieve sampling of the original desired
       Normal distribution.
    """
    # Check inputs
    if type(name) != str:
        raise RuntimeError('`name` must be a string.')
    if mu is None or sd is None:
        raise RuntimeError('`mu` and `sd` must be provided.')

    var_reparam = pm.Normal(name + '_reparam', mu=0, sd=1, shape=shape)
    var = pm.Deterministic(name, mu + var_reparam * sd)

    return var

def ReparametrizedCauchy(name, alpha=None, beta=None, shape=1):
    """
    Create a reparametrized Cauchy distributed random variable.

    Parameters
    ----------
    name : str
        Name of the variable.
    alpha : float
        Mode of Cauchy distribution.
    beta : float, > 0
        Scale parameter of Cauchy distribution
    shape: int or tuple of ints, default 1
        Shape of array of variables. If 1, then a single scalar.

    Returns
    -------
    output : pymc3 distribution
        Reparametrized Cauchy distribution.

    Notes
    -----
    .. The reparametrization procedure allows the sampler to sample
       a Cauchy distribution with alpha = 0 and beta = 1, and then do a
       deterministic reparametrization to achieve sampling of the
       original desired Cauchy distribution.
    """
    # Check inputs
    if type(name) != str:
        raise RuntimeError('`name` must be a string.')
    if alpha is None or beta is None:
        raise RuntimeError('`alpha` and `beta` must be provided.')

    var_reparam = pm.Cauchy(name + '_reparam', alpha=0, beta=1, shape=shape)
    var = pm.Deterministic(name, alpha + var_reparam * beta)

    return var
<commit_msg>Added cholesky to covariance converter.<commit_after>import warnings

import numpy as np
import pandas as pd

import pymc3 as pm
import pymc3.stats

def trace_to_dataframe(trace, model=None, varnames=None,
                       include_transformed=False, log_post=False):
    """
    Convert a PyMC3 trace to a Pandas DataFrame

    To add: Compute logp for each point using model.logp().
    """
    df = pm.trace_to_dataframe(trace, chains=[0])
    for stat in trace.stat_names:
        if stat in df.columns:
            warnings.warn('`' + stat + '` is in the variable names.`'
                          + ' Not adding this statistic.')
        else:
            df[stat] = trace.get_sampler_stats(stat, chains=[0])
    if 'chain' in df.columns:
        warnings.warn('`chain` is in the variable name.`'
                          + ' Not adding this statistic.')
    else:
        df['chain'] = np.array([0]*len(df), dtype=int)

    if len(trace.chains) == 1:
        return df

    for chain in trace.chains[1:]:
        df_app = pm.trace_to_dataframe(trace, chains=[chain])
        for stat in trace.stat_names:
            if stat not in df_app.columns:
                df_app[stat] = trace.get_sampler_stats(stat, chains=[chain])
        if 'chain' not in df_app.columns:
            df_app['chain'] = np.array([chain]*len(df_app))

        df = df.append(df_app, ignore_index=True)

    if log_post:
        # Extract the model from context if necessary
        model = pm.modelcontext(model)

        logp = pymc3.stats._log_post_trace(trace, model).sum(axis=1)
        df['log_posterior'] = logp

    return df

class Jeffreys(pm.Continuous):
   """
    Jeffreys prior for a scale parameter.

    Parameters
    ----------
    lower : float, > 0
        Minimum value the variable can take.
    upper : float, > `lower`
        Maximum value the variable can take.

    Returns
    -------
    output : pymc3 distribution
        Distribution for Jeffreys prior.
    """

    def __init__(self, lower=None, upper=None, transform='interval',
                 *args, **kwargs):
        # Check inputs
        if lower is None or upper is None:
            raise RuntimeError('`lower` and `upper` must be provided.')
        if lower <= 0:
            raise RuntimeError('`lower` must be > 0.')
        if upper <= lower:
            raise RuntimeError('`upper` must be > `lower`.')

        if transform == 'interval':
            transform = pm.distributions.transforms.interval(lower, upper)
        super(Jeffreys, self).__init__(transform=transform, *args, **kwargs)
        self.lower = lower = pm.theanof.floatX(tt.as_tensor_variable(lower))
        self.upper = upper = pm.theanof.floatX(tt.as_tensor_variable(upper))

        self.mean = (upper - lower) / tt.log(upper/lower)
        self.median = tt.sqrt(lower * upper)
        self.mode = lower

    def logp(self, value):
        lower = self.lower
        upper = self.upper
        return pm.distributions.dist_math.bound(
                    -tt.log(tt.log(upper/lower)) - tt.log(value),
                    value >= lower, value <= upper)

# def Jeffreys(name, lower=None, upper=None, shape=None):
#     """
#     Create a Jeffreys prior for a scale parameter.

#     Parameters
#     ----------
#     name : str
#         Name of the variable.
#     lower : float, > 0
#         Minimum value the variable can take.
#     upper : float, > `lower`
#         Maximum value the variable can take.
#     shape: int or tuple of ints, default 1
#         Shape of array of variables. If 1, then a single scalar.

#     Returns
#     -------
#     output : pymc3 distribution
#         Distribution for Jeffreys prior.
#     """
#     # Check inputs
#     if type(name) != str:
#         raise RuntimeError('`name` must be a string.')
#     if lower is None or upper is None:
#         raise RuntimeError('`lower` and `upper` must be provided.')
#     if lower <= 0:
#         raise RuntimeError('`lower` must be > 0.')
#     if upper <= lower:
#         raise RuntimeError('`upper` must be > `lower`.')

#     # Set up Jeffreys prior
#     if shape is None:
#         log_var = pm.Uniform('log_' + name,
#                              lower=np.log(lower),
#                              upper=np.log(upper))
#     else:
#         log_var = pm.Uniform('log_' + name,
#                              lower=np.log(lower),
#                              upper=np.log(upper),
#                              shape=shape)
#     var = pm.Deterministic(name, pm.math.exp(log_var))

#     return var

def ReparametrizedNormal(name, mu=None, sd=None, shape=1):
    """
    Create a reparametrized Normally distributed random variable.

    Parameters
    ----------
    name : str
        Name of the variable.
    mu : float
        Mean of Normal distribution.
    sd : float, > 0
        Standard deviation of Normal distribution.
    shape: int or tuple of ints, default 1
        Shape of array of variables. If 1, then a single scalar.

    Returns
    -------
    output : pymc3 distribution
        Distribution for a reparametrized Normal distribution.

    Notes
    -----
    .. The reparametrization procedure allows the sampler to sample
       a standard normal distribution, and then do a deterministic
       reparametrization to achieve sampling of the original desired
       Normal distribution.
    """
    # Check inputs
    if type(name) != str:
        raise RuntimeError('`name` must be a string.')
    if mu is None or sd is None:
        raise RuntimeError('`mu` and `sd` must be provided.')

    var_reparam = pm.Normal(name + '_reparam', mu=0, sd=1, shape=shape)
    var = pm.Deterministic(name, mu + var_reparam * sd)

    return var

def ReparametrizedCauchy(name, alpha=None, beta=None, shape=1):
    """
    Create a reparametrized Cauchy distributed random variable.

    Parameters
    ----------
    name : str
        Name of the variable.
    alpha : float
        Mode of Cauchy distribution.
    beta : float, > 0
        Scale parameter of Cauchy distribution
    shape: int or tuple of ints, default 1
        Shape of array of variables. If 1, then a single scalar.

    Returns
    -------
    output : pymc3 distribution
        Reparametrized Cauchy distribution.

    Notes
    -----
    .. The reparametrization procedure allows the sampler to sample
       a Cauchy distribution with alpha = 0 and beta = 1, and then do a
       deterministic reparametrization to achieve sampling of the
       original desired Cauchy distribution.
    """
    # Check inputs
    if type(name) != str:
        raise RuntimeError('`name` must be a string.')
    if alpha is None or beta is None:
        raise RuntimeError('`alpha` and `beta` must be provided.')

    var_reparam = pm.Cauchy(name + '_reparam', alpha=0, beta=1, shape=shape)
    var = pm.Deterministic(name, alpha + var_reparam * beta)

    return var

def chol_to_cov(chol, cov_prefix):
    """
    Convert flattened Cholesky matrix to covariance.
    """
    n = int(np.round((-1 + np.sqrt(8*chol.shape[1] + 1)) / 2))
    sigma = np.zeros_like(chol)
    inds = np.tril_indices(n)
    for i, r in enumerate(chol):
        L =  np.zeros((n, n))
        L[inds] = r
        sig = np.dot(L, L.T)
        sigma[i] = sig[inds]

    cols = ['{0:s}__{1:d}__{2:d}'.format(cov_prefix, i, j)
                for i, j in zip(*inds)]
    return pd.DataFrame(columns=cols, data=sigma)
<|endoftext|>


<commit_before>"""
The *sudoku* module offers three objects building a sudoku solver:

- the *Sudoku* class modelling the sudoku board and sudoku rules,

- the *stack_assumptions* generic backtracking algorithm. The function
  takes a list of generator functions as argument,

- the *make_generators* function returning a list of
  generator functions suited for manipulating a sudoku and compatible
  with the bactracking algorithm.

"""

import array
from contextlib import contextmanager

class Sudoku(object):
    """The *Sudoku* board class has the methods for reading the start
    state of a sudoku board, for representing a board. It also has the
    methods for setting and freeing a digit in a slot of the board,
    according to the rules of the sudoku game."""

    def __init__(self, problem):
        newarray = lambda: array.array('i', [0] * 9)
        # helper of initialisation of the data structures

        # Private bitfield presence sets
        self._lines   = newarray()  # Lines, columns and
        self._columns = newarray()  # square are bitfields of length 9.
        self._squares = newarray()  # When bit 3 is set in lines[5], 3
                                    # is present in the fifth line.

        self.board  = [newarray() for i in range(9)]
        # a 9x9 matrix of of ints between 1 and 9, an empty position
        # is represented by a false value.

        # Reading the problem
        k=0
        for i in range(9):
            for j in range(9):
                if int(problem[k]) != 0:
                    self.set(i, j, int(problem[k]))
                k+=1

    _one  = lambda self, val, index: val |   1 << index - 1
    _zero = lambda self, val, index: val & ~(1 << index - 1)
    _get  = lambda self, val, index: (val >>  index - 1) & 1
    # Bitfield manipulation

    def set(self, i, j, val):
        """Sets a new digit on the board in position i,j. This only
        updates the board *without* checking first if the rules of the
        sudo game are respected"""

        self.board[i][j]   = val

        # Not only update the board but also the lines, columns and
        # squares arrays
        self._lines[i]   = self._one(self._lines[i],   val)
        self._columns[j] = self._one(self._columns[j], val)
        self._squares[(j/3)*3+i/3] = self._one(
            self._squares[(j/3)*3+i/3], val)

    def free(self, i, j):
        """Frees the slot in position i,j"""

        # The value to be removed from the lines, columns and square
        # presence set is found in the *board* member attribute
        val, self.board[i][j] = self.board[i][j], 0

        # Also update the line, column and square presence sets.
        self._lines[i]   = self._zero(self._lines[i],   val)
        self._columns[j] = self._zero(self._columns[j], val)
        self._squares[(j/3)*3+i/3] = self._zero(
            self._squares[(j/3)*3+i/3], val)

    @contextmanager
    def attempt(self, col, row, candidate):
       """A context manager which sets the value of the board at
        position: *col*, *line* on entering the context and which
        frees the position on exiting the context."""

       self.set(col, row, candidate)
       yield
       self.free(col, row)

    def candidates(self, col, row):

        """Returns the list of possible values for the slot specified by
        the arguments, according to the current state of the sudoku
        board and according to the rules of the sudoku game.

        The sudoku rules states that the candidates are the numbers
        which are not present neither in the column *col*, neither in
        the line *row*, neither in the square identified by *col* and
        *row*."""

        return filter(
            lambda val: all( not self._get(bf, val) for bf in (
                    self._lines[col],
                    self._columns[row],
                    self._squares[(row/3)*3+col/3])),
            range(1,10))

    def __str__(self):

        # The matrix is transformed into a list of characters
        l = [str(self.board[i][j]) if self.board[i][j] else ' '
                    for i in range(9) for j in range(9)]

        l = ['\n   '+e if i%9 ==0 else e for (i,e) in enumerate(l)] # 1.
        l = ['  '+e    if i%3 ==0 else e for (i,e) in enumerate(l)] # 2.
        l = ['\n'+e    if i%27==0 else e for (i,e) in enumerate(l)] # 3.

        # 1.   New lines every 9 elements
        # 2,3. Squares are represented by extra spaces and another
        #      newline

        return ' '.join(l)

def make_generators(sudoku):

    """Returns a list of candidate generators for use with the
    backtrack algorithm stack_assumptions.  The sudoku argument must
    provide two functions: *candidates(i,j)*, and *attempt(col, row,
    candidate)* and a member attribute called *board*, which is a 9x9
    matrix.

    There are as many generator functions than there are slots on the
    sudoku board, they are stored in a list. Each generator function
    is specific to a slot: it actually *contains* the coordinates of
    the slot, like a closure.

    When called for the first time, the generator computes the list of
    candidate numbers for the slot, according to the current sudoku
    board. The list of candidates depends on the state of the board at
    the time the generator is called for the first time."""

    generators = []
    for i in range(9):
        for j in range(9):
            def gen_func(col=i,row=j):
                if sudoku.board[col][row] != 0:
                    yield
                else:
                    for candidate in sudoku.candidates(col, row):
                        with sudoku.attempt(col, row, candidate):
                            yield
            generators.append(gen_func)
    return generators

def stack_assumptions(generators, i=0):

    """Takes a list of generators. This list is assumed to manipulate
    a shared representation of the problem. When this algorithm
    yields, a solution has been found and can be printed.

    The algorithm works by calling the generator at the *nth* position
    of the list, and pulls the *next()* method on the iterator
    returned:

    #. either *next()* returns, in which case, the algorithm
       instantiates the generator from position **n+1** of the input
       list function and tries to pull its *next()* method,

    #. or the method raises a StopIteration, in which case, the
       algorithm trigger *next()* on the generator at position **n-1**,

    This algorithm yields whenever every generator of the list has
    yielded, at this point, every position of the board is filled with
    a digit according to the sudoku rules: a solution has been
    reached and the board can be printed.

    When a generator has yielded, this means that a suitable candidate
    could be found and was set in the board's slot and that an
    assumption can be tried on the next slot, with generator i+1.

    When a generator raises a StopIteration, then a dead-end was
    met. A wrong assumption must have been taken somewhere along the
    stack of the previous recursion: the algorithm backtracks at the
    previous recursion, another assumption can be attempted."""

    if i >= len(generators):
        yield
    else:
        for _ in generators[i]():
            for _ in stack_assumptions(generators, i+1):
                yield

if __name__=="__main__":

    data=('006007403'
          '000906020'
          '500304006'
          '740000010'
          '809000304'
          '010000057'
          '200603005'
          '030208000'
          '405700200')

    sudoku = Sudoku(data)

    for _ in stack_assumptions(make_generators(sudoku)):
        print sum([sudoku.board[0][i] for i in range(3)])
<commit_msg>Removed main part of sudoku module<commit_after>"""
The *sudoku* module offers three objects building a sudoku solver:

- the *Sudoku* class modelling the sudoku board and sudoku rules,

- the *stack_assumptions* generic backtracking algorithm. The function
  takes a list of generator functions as argument,

- the *make_generators* function returning a list of
  generator functions suited for manipulating a sudoku and compatible
  with the bactracking algorithm.

"""

import array
from contextlib import contextmanager

class Sudoku(object):
    """The *Sudoku* board class has the methods for reading the start
    state of a sudoku board, for representing a board. It also has the
    methods for setting and freeing a digit in a slot of the board,
    according to the rules of the sudoku game."""

    def __init__(self, problem):
        newarray = lambda: array.array('i', [0] * 9)
        # helper of initialisation of the data structures

        # Private bitfield presence sets
        self._lines   = newarray()  # Lines, columns and
        self._columns = newarray()  # square are bitfields of length 9.
        self._squares = newarray()  # When bit 3 is set in lines[5], 3
                                    # is present in the fifth line.

        self.board  = [newarray() for i in range(9)]
        # a 9x9 matrix of of ints between 1 and 9, an empty position
        # is represented by a false value.

        # Reading the problem
        k=0
        for i in range(9):
            for j in range(9):
                if int(problem[k]) != 0:
                    self.set(i, j, int(problem[k]))
                k+=1

    _one  = lambda self, val, index: val |   1 << index - 1
    _zero = lambda self, val, index: val & ~(1 << index - 1)
    _get  = lambda self, val, index: (val >>  index - 1) & 1
    # Bitfield manipulation

    def set(self, i, j, val):
        """Sets a new digit on the board in position i,j. This only
        updates the board *without* checking first if the rules of the
        sudo game are respected"""

        self.board[i][j]   = val

        # Not only update the board but also the lines, columns and
        # squares arrays
        self._lines[i]   = self._one(self._lines[i],   val)
        self._columns[j] = self._one(self._columns[j], val)
        self._squares[(j/3)*3+i/3] = self._one(
            self._squares[(j/3)*3+i/3], val)

    def free(self, i, j):
        """Frees the slot in position i,j"""

        # The value to be removed from the lines, columns and square
        # presence set is found in the *board* member attribute
        val, self.board[i][j] = self.board[i][j], 0

        # Also update the line, column and square presence sets.
        self._lines[i]   = self._zero(self._lines[i],   val)
        self._columns[j] = self._zero(self._columns[j], val)
        self._squares[(j/3)*3+i/3] = self._zero(
            self._squares[(j/3)*3+i/3], val)

    @contextmanager
    def attempt(self, col, row, candidate):
       """A context manager which sets the value of the board at
        position: *col*, *line* on entering the context and which
        frees the position on exiting the context."""

       self.set(col, row, candidate)
       yield
       self.free(col, row)

    def candidates(self, col, row):

        """Returns the list of possible values for the slot specified by
        the arguments, according to the current state of the sudoku
        board and according to the rules of the sudoku game.

        The sudoku rules states that the candidates are the numbers
        which are not present neither in the column *col*, neither in
        the line *row*, neither in the square identified by *col* and
        *row*."""

        return filter(
            lambda val: all( not self._get(bf, val) for bf in (
                    self._lines[col],
                    self._columns[row],
                    self._squares[(row/3)*3+col/3])),
            range(1,10))

    def __str__(self):

        # The matrix is transformed into a list of characters
        l = [str(self.board[i][j]) if self.board[i][j] else ' '
                    for i in range(9) for j in range(9)]

        l = ['\n   '+e if i%9 ==0 else e for (i,e) in enumerate(l)] # 1.
        l = ['  '+e    if i%3 ==0 else e for (i,e) in enumerate(l)] # 2.
        l = ['\n'+e    if i%27==0 else e for (i,e) in enumerate(l)] # 3.

        # 1.   New lines every 9 elements
        # 2,3. Squares are represented by extra spaces and another
        #      newline

        return ' '.join(l)

def make_generators(sudoku):

    """Returns a list of candidate generators for use with the
    backtrack algorithm stack_assumptions.  The sudoku argument must
    provide two functions: *candidates(i,j)*, and *attempt(col, row,
    candidate)* and a member attribute called *board*, which is a 9x9
    matrix.

    There are as many generator functions than there are slots on the
    sudoku board, they are stored in a list. Each generator function
    is specific to a slot: it actually *contains* the coordinates of
    the slot, like a closure.

    When called for the first time, the generator computes the list of
    candidate numbers for the slot, according to the current sudoku
    board. The list of candidates depends on the state of the board at
    the time the generator is called for the first time."""

    generators = []
    for i in range(9):
        for j in range(9):
            def gen_func(col=i,row=j):
                if sudoku.board[col][row] != 0:
                    yield
                else:
                    for candidate in sudoku.candidates(col, row):
                        with sudoku.attempt(col, row, candidate):
                            yield
            generators.append(gen_func)
    return generators

def stack_assumptions(generators, i=0):

    """Takes a list of generators. This list is assumed to manipulate
    a shared representation of the problem. When this algorithm
    yields, a solution has been found and can be printed.

    The algorithm works by calling the generator at the *nth* position
    of the list, and pulls the *next()* method on the iterator
    returned:

    #. either *next()* returns, in which case, the algorithm
       instantiates the generator from position **n+1** of the input
       list function and tries to pull its *next()* method,

    #. or the method raises a StopIteration, in which case, the
       algorithm trigger *next()* on the generator at position **n-1**,

    This algorithm yields whenever every generator of the list has
    yielded, at this point, every position of the board is filled with
    a digit according to the sudoku rules: a solution has been
    reached and the board can be printed.

    When a generator has yielded, this means that a suitable candidate
    could be found and was set in the board's slot and that an
    assumption can be tried on the next slot, with generator i+1.

    When a generator raises a StopIteration, then a dead-end was
    met. A wrong assumption must have been taken somewhere along the
    stack of the previous recursion: the algorithm backtracks at the
    previous recursion, another assumption can be attempted."""

    if i >= len(generators):
        yield
    else:
        for _ in generators[i]():
            for _ in stack_assumptions(generators, i+1):
                yield
<|endoftext|>