<commit_before>#!/usr/bin/python

import os, sys
from SimpleCV import *
from nose.tools import with_setup

testimage = "sampleimages/9dots4lines.png"
testimage2 = "sampleimages/aerospace.jpg"
testimageclr = "sampleimages/statue_liberty.jpg"
testbarcode = "sampleimages/barcode.png"
testoutput = "sampleimages/9d4l.jpg"

def setup_context():
  img = Image(testimage)

def destroy_context():
  img = ""

@with_setup(setup_context, destroy_context)
def test_loadsave():
  img = Image(testimage)
  img.save(testoutput)
  if (os.path.isfile(testoutput)):
    os.remove(testoutput)
    return 1
  else:
    return 0

def test_bitmap():
  img = Image(testimage)
  bmp = img.getBitmap();
  if bmp.width > 0:
    return 1
  else:
    return 0

def test_matrix():
  img = Image(testimage)
  m = img.getMatrix()
  if (m.rows == img.getBitmap().width):
    return 1
  return 0

def test_scale():
  img = Image(testimage)
  thumb = img.scale(30,30)
  thumb.save(testoutput)

def test_copy():
  img = Image(testimage2)
  copy = img.copy()

  if (img[1,1] != copy[1,1] or img.size() != copy.size()):
    return 0
  return 1

def test_getitem():
  img = Image(testimage)
  colors = img[1,1]
  if (colors[0] == 255 and colors[1] == 255 and colors[2] == 255):
    return 1
  else:
    return 0

def test_getslice():
  img = Image(testimage)
  section = img[1:10,1:10]
  section.save(testoutput)
  return 1

def test_setitem():
  img = Image(testimage)
  img[1,1] = (0, 0, 0)
  newimg = Image(img.getBitmap())
  colors = newimg[1,1]
  if (colors[0] == 0 and colors[1] == 0 and colors[2] == 0):
    return 1
  else:
    return 0

def test_setslice():
  img = Image(testimage)
  img[1:10,1:10] = (0,0,0) #make a black box
  newimg = Image(img.getBitmap())
  section = newimg[1:10,1:10]
  for i in range(5):
    colors = section[i,0]
    if (colors[0] != 0 or colors[1] != 0 or colors[2] != 0):
      return 0
  return 1

def test_findCorners():
  img = Image(testimage2)
  corners = img.findCorners(25)
  if (len(corners) == 0):
    return 0
  corners.draw()
  img.save(testoutput)

def test_meancolor():
  img = Image(testimage2)
  roi = img[1:50,1:50]

  r, g, b = roi.meanColor()

  if (r >= 0 and r <= 255 and g >= 0 and g <= 255 and b >= 0 and b <= 255):
    return 1

def test_smooth():
  img = Image(testimage2)
  img.smooth()
  img.smooth('bilateral', (3,3), 4, 1)
  img.smooth('blur', (3, 3))
  img.smooth('median', (3, 3))
  img.smooth('gaussian', (5,5), 0)

def test_invert():
  img = Image(testimage2)
  clr = img[1,1]
  img.invert()

  if (clr[0] == 255 - img[1,1][0]):
    return 1
  return 0

def test_size():
  img = Image(testimage2)
  (width, height) = img.size()
  if type(width) == "int" and type(height) == "int" and width > 0 and height > 0:
    return 1
  else:
    return 0

def test_drawing():
  img = Image(testimageclr)
  img.drawCircle((5, 5), 3)
  img.drawLine((5, 5), (5, 8))

def test_channels():
  img = Image(testimageclr)
  (r, g, b) = img.channels(True)
  (red, green, blue) = img.channels()

def test_histogram():
  img = Image(testimage2)
  h = img.histogram(25)

  for i in h:
    if type(i) != "int":
      return 0

  return 1

def test_lines():
  img = Image(testimage2)
  lines = img.findLines()

  lines.draw()
  img.save(testoutput)

def test_feature_measures():
  img = Image(testimage2)

  fs = FeatureSet()
  fs.append(Corner(img, 5, 5))
  fs.append(Line(img, ((2, 2), (3,3))))

  if BLOBS_ENABLED:
    fs.append(img.findBlobs()[0])

  if ZXING_ENABLED:
    fake_barcode = Barcode(img, zxing.BarCode("""
file:default.png (format: FAKE_DATA, type: TEXT):
Raw result:
foo-bar|the bar of foo
Parsed result:
foo-bar
the bar of foo
Also, there were 4 result points:
  Point 0: (24.0,18.0)
  Point 1: (21.0,196.0)
  Point 2: (201.0,198.0)
  Point 3: (205.23952,21.0)
"""))
    fs.append(fake_barcode)

  for f in fs:
    a = f.area()
    l = f.length()
    c = f.meanColor()
    d = f.colorDistance()
    th = f.angle()
    pts = f.coordinates()
    dist = f.distanceFrom() #distance from center of image

  fs1 = fs.sortDistance()
  fs2 = fs.sortAngle()
  fs3 = fs.sortLength()
  fs4 = fs.sortColorDistance()
  fs5 = fs.sortArea()

def test_blobs():
  if not BLOBS_ENABLED:
    return None
  img = Image(testbarcode)
  blobs = img.findBlobs()

  blobs[0].draw((0, 255, 0))
  img.save(testoutput)

  return 1

def test_barcode():
  if not ZXING_ENABLED:
    return None

  nocode = Image(testimage).findBarcode()
  if nocode: #we should find no barcode in our test image
    return 0
  code = Image(testbarcode).findBarcode()

  if code.points:
    return 1

def test_x():
  return 0
  tmpX = Image(testimage).findLines().x()
  if type(tmpX) == int:
    return 0
  else:
    return 0

<commit_msg>add pass/fail to tests.  That's pretty useful<commit_after>#!/usr/bin/python

import os, sys
from SimpleCV import *
from nose.tools import with_setup

testimage = "sampleimages/9dots4lines.png"
testimage2 = "sampleimages/aerospace.jpg"
testimageclr = "sampleimages/statue_liberty.jpg"
testbarcode = "sampleimages/barcode.png"
testoutput = "sampleimages/9d4l.jpg"

def setup_context():
  img = Image(testimage)

def destroy_context():
  img = ""

@with_setup(setup_context, destroy_context)
def test_loadsave():
  img = Image(testimage)
  img.save(testoutput)
  if (os.path.isfile(testoutput)):
    os.remove(testoutput)
    pass
  else:
    assert False

def test_bitmap():
  img = Image(testimage)
  bmp = img.getBitmap();
  if bmp.width > 0:
    pass
  else:
    assert False

def test_matrix():
  img = Image(testimage)
  m = img.getMatrix()
  if (m.rows == img.getBitmap().width):
    pass
  assert False

def test_scale():
  img = Image(testimage)
  thumb = img.scale(30,30)
  thumb.save(testoutput)

def test_copy():
  img = Image(testimage2)
  copy = img.copy()

  if (img[1,1] != copy[1,1] or img.size() != copy.size()):
    assert False
  pass

def test_getitem():
  img = Image(testimage)
  colors = img[1,1]
  if (colors[0] == 255 and colors[1] == 255 and colors[2] == 255):
    pass
  else:
    assert False

def test_getslice():
  img = Image(testimage)
  section = img[1:10,1:10]
  section.save(testoutput)
  pass

def test_setitem():
  img = Image(testimage)
  img[1,1] = (0, 0, 0)
  newimg = Image(img.getBitmap())
  colors = newimg[1,1]
  if (colors[0] == 0 and colors[1] == 0 and colors[2] == 0):
    pass
  else:
    assert False

def test_setslice():
  img = Image(testimage)
  img[1:10,1:10] = (0,0,0) #make a black box
  newimg = Image(img.getBitmap())
  section = newimg[1:10,1:10]
  for i in range(5):
    colors = section[i,0]
    if (colors[0] != 0 or colors[1] != 0 or colors[2] != 0):
      assert False
  pass

def test_findCorners():
  img = Image(testimage2)
  corners = img.findCorners(25)
  if (len(corners) == 0):
    assert False
  corners.draw()
  img.save(testoutput)

def test_meancolor():
  img = Image(testimage2)
  roi = img[1:50,1:50]

  r, g, b = roi.meanColor()

  if (r >= 0 and r <= 255 and g >= 0 and g <= 255 and b >= 0 and b <= 255):
    pass

def test_smooth():
  img = Image(testimage2)
  img.smooth()
  img.smooth('bilateral', (3,3), 4, 1)
  img.smooth('blur', (3, 3))
  img.smooth('median', (3, 3))
  img.smooth('gaussian', (5,5), 0)

def test_invert():
  img = Image(testimage2)
  clr = img[1,1]
  img.invert()

  if (clr[0] == 255 - img[1,1][0]):
    pass
  assert False

def test_size():
  img = Image(testimage2)
  (width, height) = img.size()
  if type(width) == "int" and type(height) == "int" and width > 0 and height > 0:
    pass
  else:
    assert False

def test_drawing():
  img = Image(testimageclr)
  img.drawCircle((5, 5), 3)
  img.drawLine((5, 5), (5, 8))

def test_channels():
  img = Image(testimageclr)
  (r, g, b) = img.channels(True)
  (red, green, blue) = img.channels()

def test_histogram():
  img = Image(testimage2)
  h = img.histogram(25)

  for i in h:
    if type(i) != "int":
      assert False

  pass

def test_lines():
  img = Image(testimage2)
  lines = img.findLines()

  lines.draw()
  img.save(testoutput)

def test_feature_measures():
  img = Image(testimage2)

  fs = FeatureSet()
  fs.append(Corner(img, 5, 5))
  fs.append(Line(img, ((2, 2), (3,3))))

  if BLOBS_ENABLED:
    fs.append(img.findBlobs()[0])

  if ZXING_ENABLED:
    fake_barcode = Barcode(img, zxing.BarCode("""
file:default.png (format: FAKE_DATA, type: TEXT):
Raw result:
foo-bar|the bar of foo
Parsed result:
foo-bar
the bar of foo
Also, there were 4 result points:
  Point 0: (24.0,18.0)
  Point 1: (21.0,196.0)
  Point 2: (201.0,198.0)
  Point 3: (205.23952,21.0)
"""))
    fs.append(fake_barcode)

  for f in fs:
    a = f.area()
    l = f.length()
    c = f.meanColor()
    d = f.colorDistance()
    th = f.angle()
    pts = f.coordinates()
    dist = f.distanceFrom() #distance from center of image

  fs1 = fs.sortDistance()
  fs2 = fs.sortAngle()
  fs3 = fs.sortLength()
  fs4 = fs.sortColorDistance()
  fs5 = fs.sortArea()

def test_blobs():
  if not BLOBS_ENABLED:
    return None
  img = Image(testbarcode)
  blobs = img.findBlobs()

  blobs[0].draw((0, 255, 0))
  img.save(testoutput)

  pass

def test_barcode():
  if not ZXING_ENABLED:
    return None

  nocode = Image(testimage).findBarcode()
  if nocode: #we should find no barcode in our test image
    assert False
  code = Image(testbarcode).findBarcode()

  if code.points:
    pass

def test_x():
  assert False
  tmpX = Image(testimage).findLines().x()
  if type(tmpX) == int:
    assert False
  else:
    assert False

<|endoftext|>


<commit_before>from main import t, SessionNotFound, Session, root_logger
from nose.tools import raises
import unittest
import logging
from random import randint

root_logger.setLevel(logging.INFO)

def bootstrap():
    if t.has_clients():
        TEST_SESSION_PREFIX = 'tmxwrp_'

        # find current sessions prefixed with tmxwrp
        previous_sessions = [s.session_name for s in t.list_sessions()
                             if s.session_name.startswith(TEST_SESSION_PREFIX)]

        other_sessions = [s.session_name for s in t.list_sessions()
                          if not s.session_name.startswith(
                              TEST_SESSION_PREFIX
                          )]

        if not other_sessions:
            # create a test session so client won't close when other windows
            # cleaned up
            Session.new_session(session_name='test_' + str(randint(0, 1337)))
            Session.attached_pane().send_keys('created by tmuxwrapper tests.'
                                              ' you may delete this.',
                                              enter=False)
        else:
            t.switch_client(other_sessions[0])

        for session in previous_sessions:
            t.kill_session(previous_sessions)

        TEST_SESSION_NAME = TEST_SESSION_PREFIX + str(randint(0, 1337))

        session = Session.new_session(
            session_name=TEST_SESSION_NAME,
            kill_session=True
        )

        t.switch_client(TEST_SESSION_NAME)

        return (TEST_SESSION_NAME, session)

class TmuxTest(unittest.TestCase):
    '''
        self.session
            Session object
        self.TEST_SESSION_NAME
            string. name of the test case session.
    '''

    @classmethod
    def setUpClass(cls):
        try:
            # atm bootstrap() retyrns name of session and the session object
            cls.TEST_SESSION_NAME, cls.session = bootstrap()
        except:
            cls.fail()
        return

class TestSessions(TmuxTest):
    def tearDown(self):
        pass

    def test_has_session(self):
        assert t.has_session(self.TEST_SESSION_NAME) is True
        assert t.has_session('asdf2314324321') is False

    def test_3_switch_client_returns_session(self):
        '''
        switch_client should return reference to Session object
        '''
        pass

class WindowCreation(TmuxTest):

    def test_sync_windows(self):
        self.session.attached_window().select_layout('even-horizontal')
        self.session.attached_window().split_window()
        self.session.attached_window().split_window('-h')

        self.session.select_window(1)

        self.session.attached_window().select_pane(1)
        self.session.attached_pane().send_keys('cd /srv/www/flaskr')
        self.session.attached_window().select_pane(0)
        self.session.attached_pane().send_keys('source .env/bin/activate')
        self.session.new_window('second')
        self.assertEqual(2, len(self.session._windows))
        self.session.new_window('testing 3')
        self.assertEqual(3, len(self.session._windows))
        self.session.select_window(1)
        self.session.kill_window(target_window='3')
        self.assertEqual(2, len(self.session._windows))
        #tmux('display-panes')

class WindowSelect(TmuxTest):
    def test_select_window(self):
        self.session.new_window('testing 3')
        self.session.select_window(2)
        self.assertEqual(2, int(self.session.attached_window()._TMUX['window_index']))

if __name__ == '__main__':

    if t.has_clients():
        unittest.main()
    else:
        print('must have a tmux client running')
<commit_msg>test docs<commit_after>"""
    tmuxwrapper.tests
    ~~~~~~~~~~~~~~~~~

    :copyright: Copyright 2013 Tony Narlock <tony@git-pull.com>.
    :license: BSD, see LICENSE for details

    this can be ran like::

        nosetests tests.py

    or::

        python tests.py

    also, if you have ``node`` and ``npm`` you may (sudo)::

        ``npm install -g nodemon``
        ``nodemon --watch tests.py --watch main.py --exec "nosetests" tests.py

    or::

        ``nodemon --watch tests.py --watch main.py --exec "python" tests.py

    These tests require an active tmux client open while it runs. It is best to
    have a second terminal with tmux running alongside the terminal running the
    tests.
"""

from main import t, SessionNotFound, Session, root_logger
from nose.tools import raises
import unittest
import logging
from random import randint

# set logging to INFO level
root_logger.setLevel(logging.INFO)

def bootstrap():
    '''
        Returns a tuple of the session_name (generated) and a :class:`Session`

        Checks to verify if the user has a tmux client open.

        It will clean up and delete other sessions starting with the
        TEST_SESSION_PREFIX ``tmxwrap``.

        Since tmux closes when all sessions are deleted, the bootstrap will see
        if there is no other client open aside from a tmuxwrp_ prefixed session
        a dumby session will be made to prevent tmux from closing.

    '''
    if t.has_clients():
        TEST_SESSION_PREFIX = 'tmxwrp_'

        # find current sessions prefixed with tmxwrp
        previous_sessions = [s.session_name for s in t.list_sessions()
                             if s.session_name.startswith(TEST_SESSION_PREFIX)]

        other_sessions = [s.session_name for s in t.list_sessions()
                          if not s.session_name.startswith(
                              TEST_SESSION_PREFIX
                          )]

        if not other_sessions:
            # create a test session so client won't close when other windows
            # cleaned up
            Session.new_session(session_name='test_' + str(randint(0, 1337)))
            Session.attached_pane().send_keys('created by tmuxwrapper tests.'
                                              ' you may delete this.',
                                              enter=False)
        else:
            t.switch_client(other_sessions[0])

        for session in previous_sessions:
            t.kill_session(previous_sessions)

        TEST_SESSION_NAME = TEST_SESSION_PREFIX + str(randint(0, 1337))

        session = Session.new_session(
            session_name=TEST_SESSION_NAME,
            kill_session=True
        )

        t.switch_client(TEST_SESSION_NAME)

        return (TEST_SESSION_NAME, session)

class TmuxTest(unittest.TestCase):
    '''
        self.session
            Session object
        self.TEST_SESSION_NAME
            string. name of the test case session.
    '''

    @classmethod
    def setUpClass(cls):
        try:
            # bootstrap() retyrns a tuple  of session and the session object
            cls.TEST_SESSION_NAME, cls.session = bootstrap()
        except:
            cls.fail()
        return

class TestSessions(TmuxTest):
    def tearDown(self):
        pass

    def test_has_session(self):
        assert t.has_session(self.TEST_SESSION_NAME) is True
        assert t.has_session('asdf2314324321') is False

    def test_3_switch_client_returns_session(self):
        '''
        switch_client should return reference to Session object
        '''
        pass

class WindowCreation(TmuxTest):

    def test_sync_windows(self):
        self.session.attached_window().select_layout('even-horizontal')
        self.session.attached_window().split_window()
        self.session.attached_window().split_window('-h')

        self.session.select_window(1)

        self.session.attached_window().select_pane(1)
        self.session.attached_pane().send_keys('cd /srv/www/flaskr')
        self.session.attached_window().select_pane(0)
        self.session.attached_pane().send_keys('source .env/bin/activate')
        self.session.new_window('second')
        self.assertEqual(2, len(self.session._windows))
        self.session.new_window('testing 3')
        self.assertEqual(3, len(self.session._windows))
        self.session.select_window(1)
        self.session.kill_window(target_window='3')
        self.assertEqual(2, len(self.session._windows))
        #tmux('display-panes')

class WindowSelect(TmuxTest):
    def test_select_window(self):
        self.session.new_window('testing 3')
        self.session.select_window(2)
        self.assertEqual(2, int(self.session.attached_window()._TMUX['window_index']))

if __name__ == '__main__':

    if t.has_clients():
        unittest.main()
    else:
        print('must have a tmux client running')
<|endoftext|>


<commit_before>import os
import app
import unittest
import tempfile

class AppTestCase(unittest.TestCase):

    #setup
    def setUp(self):
        self.app = app.app.test_client()

    def testPOSTandDBUpdate(self):
        rv = self.app.post('/tx', data=dict(owner="Testivus",model="Skynet"),follow_redirects=True)
        unittest.TestCase.assertEqual(self,str(rv),'<Response streamed [200 OK]>','POST Failed')

        rv = self.app.get('/api/return/person/Testivus')
        unittest.TestCase.assertIn(self,'Testivus',rv.get_data(as_text=True))

        rv = self.app.get('/api/return/asset/Skynet')
        unittest.TestCase.assertIn(self,'Skynet',rv.get_data(as_text=True))

    def testGET(self):
        rv = self.app.get('/api/return/person/Testivus')
        unittest.TestCase.assertEqual(self,rv.status_code,200)

        rv = self.app.get('/api/return/asset/Skynet')
        unittest.TestCase.assertEqual(self,rv.status_code,200)

#test runner
suite = unittest.TestLoader().loadTestsFromTestCase(AppTestCase)
unittest.TextTestRunner(verbosity=2).run(suite)
<commit_msg>cleaned up<commit_after>import os
import app
import unittest
import tempfile

class AppTestCase(unittest.TestCase):

    #setup
    def setUp(self):
        self.app = app.app.test_client()

    def testPOSTandDBUpdate(self):
        rv = self.app.post('/tx', data=dict(owner="Testivus",model="Skynet"),follow_redirects=True)
        unittest.TestCase.assertEqual(self,rv.status_code,200)

        rv = self.app.get('/api/return/person/Testivus')
        unittest.TestCase.assertIn(self,'Testivus',rv.get_data(as_text=True))

        rv = self.app.get('/api/return/asset/Skynet')
        unittest.TestCase.assertIn(self,'Skynet',rv.get_data(as_text=True))

    def testGET(self):
        rv = self.app.get('/api/return/person/Testivus')
        unittest.TestCase.assertEqual(self,rv.status_code,200)

        rv = self.app.get('/api/return/asset/Skynet')
        unittest.TestCase.assertEqual(self,rv.status_code,200)

#test runner
suite = unittest.TestLoader().loadTestsFromTestCase(AppTestCase)
unittest.TextTestRunner(verbosity=2).run(suite)
<|endoftext|>


<commit_before>from twisted.trial import unittest
from twisted.internet import task
from nanobot import UrlCache

class CacheTests(unittest.TestCase):
    def setUp(self):
        self.clock = task.Clock()
        self.cache = UrlCache(reactor=self.clock, expiration=60)
        self.cache.enable()

    def tearDown(self):
        self.cache.disable()

    def testGetNotExpired(self):
        self.cache.update("foo", "bar")
        self.assertEquals(self.cache.fetch("foo"),
                          "bar", "Expected cache to have 'foo' for 'bar'")

    def testGetExpired(self):
        self.cache.update("foo", "bar")
        self.assertEquals(self.cache.fetch("foo"),
                          "bar", "Expected cache to have 'foo' for 'bar'")
        self.clock.advance(60)
        value = self.cache.fetch("foo")
        self.assertIs(value, None,
                      "Cache had '%s' for entry 'foo'" % value)
<commit_msg>Add some failing tests as skeleton for privmsg-handling tests<commit_after>from twisted.trial import unittest
from twisted.internet import task
import nanobot

class CacheTests(unittest.TestCase):
    def setUp(self):
        self.clock = task.Clock()
        self.cache = nanobot.UrlCache(reactor=self.clock, expiration=60)
        self.cache.enable()

    def tearDown(self):
        self.cache.disable()

    def testGetNotExpired(self):
        self.cache.update("foo", "bar")
        self.assertEquals(self.cache.fetch("foo"),
                          "bar", "Expected cache to have 'foo' for 'bar'")

    def testGetExpired(self):
        self.cache.update("foo", "bar")
        self.assertEquals(self.cache.fetch("foo"),
                          "bar", "Expected cache to have 'foo' for 'bar'")
        self.clock.advance(60)
        value = self.cache.fetch("foo")
        self.assertIs(value, None,
                      "Cache had '%s' for entry 'foo'" % value)

class TestNanoBotProtocol(unittest.TestCase):
    def testNoUrl(self):
        self.fail("not implemented")

    def testHttpUrl(self):
        self.fail("not implemented")

    def testHttpsUrl(self):
        self.fail("not implemented")

    def testMultipleUrls(self):
        self.fail("not implemented")
<|endoftext|>


<commit_before>import socket
import subprocess
import time
from contextlib import closing
from datetime import datetime, timedelta
from typing import Any, Callable

import pytest

from greenstalk import Client
from greenstalk.client import DEFAULT_PRIORITY, DEFAULT_TTR
from greenstalk.exceptions import (
    BuriedError, DeadlineSoonError, JobTooBigError, NotFoundError,
    NotIgnoredError, TimedOutError, UnknownResponseError
)

TEST_PORT = 4444

def with_subprocess(*cli: Any) -> Callable:
    def configuration(**kwargs: Any) -> Callable:
        def decorator(test: Callable) -> Callable:
            def wrapper() -> None:
                cmdline = list(cli)
                try:
                    response = kwargs.pop('response')
                except KeyError:
                    pass
                else:
                    cmdline.append(response)
                process = subprocess.Popen(cmdline)
                time.sleep(0.1)
                try:
                    with closing(Client(port=TEST_PORT, **kwargs)) as c:
                        test(c)
                finally:
                    process.terminate()
                    process.wait()
            return wrapper
        return decorator
    return configuration

with_beanstalkd = with_subprocess('beanstalkd', '-l', '127.0.0.1', '-p', str(TEST_PORT))
with_fake = with_subprocess('scripts/fake-response', str(TEST_PORT))

@with_beanstalkd()
def test_basic_usage(c: Client) -> None:
    c.use('emails')
    put_jid = c.put('测试@example.com')
    c.watch('emails')
    c.ignore('default')
    reserve_jid, body = c.reserve()
    assert put_jid == reserve_jid
    assert body == '测试@example.com'
    c.delete(reserve_jid)

@with_beanstalkd()
def test_put_priority(c: Client) -> None:
    c.put('2', priority=2)
    c.put('1', priority=1)
    _, body = c.reserve()
    assert body == '1'
    _, body = c.reserve()
    assert body == '2'

@with_beanstalkd()
def test_delays(c: Client) -> None:
    c.put('delayed', delay=timedelta(seconds=1))
    before = datetime.now()
    jid, body = c.reserve()
    assert body == 'delayed'
    assert datetime.now() - before >= timedelta(seconds=1)
    c.release(jid, delay=timedelta(seconds=2))
    with pytest.raises(TimedOutError):
        c.reserve(timeout=timedelta(seconds=1))
    jid, _ = c.reserve(timeout=timedelta(seconds=1))
    c.bury(jid)
    with pytest.raises(TimedOutError):
        c.reserve(timeout=timedelta(seconds=0))

@with_beanstalkd()
def test_ttr(c: Client) -> None:
    c.put('two second ttr', ttr=timedelta(seconds=2))
    before = datetime.now()
    jid, _ = c.reserve()
    with pytest.raises(DeadlineSoonError):
        c.reserve()
    c.touch(jid)
    with pytest.raises(DeadlineSoonError):
        c.reserve()
    c.release(jid)
    delta = datetime.now() - before
    assert delta >= timedelta(seconds=1, milliseconds=950)
    assert delta <= timedelta(seconds=2, milliseconds=50)

@with_beanstalkd()
def test_reserve_raises_on_timeout(c: Client) -> None:
    before = datetime.now()
    with pytest.raises(TimedOutError):
        c.reserve(timeout=timedelta(seconds=1))
    delta = datetime.now() - before
    assert delta >= timedelta(seconds=1)
    assert delta <= timedelta(seconds=1, milliseconds=50)

@with_beanstalkd(use='hosts', watch='hosts')
def test_initialize_with_tubes(c: Client) -> None:
    c.put('www.example.com')
    jid, body = c.reserve()
    assert body == 'www.example.com'
    c.delete(jid)
    c.use('default')
    c.put('')
    with pytest.raises(TimedOutError):
        c.reserve(timeout=timedelta())

@with_beanstalkd(watch=['static', 'dynamic'])
def test_initialize_watch_multiple(c: Client) -> None:
    c.use('static')
    c.put(b'haskell')
    c.put(b'rust')
    c.use('dynamic')
    c.put(b'python')
    jid, body = c.reserve(timeout=timedelta())
    assert body == 'haskell'
    jid, body = c.reserve(timeout=timedelta())
    assert body == 'rust'
    jid, body = c.reserve(timeout=timedelta())
    assert body == 'python'

@with_beanstalkd(encoding=None)
def test_binary_jobs(c: Client) -> None:
    with open('python-logo.png', 'rb') as f:
        image = f.read()
    c.put(image)
    jid, body = c.reserve()
    assert body == image

@with_beanstalkd()
def test_peek(c: Client) -> None:
    put_jid = c.put('job')
    peek_jid, body = c.peek(put_jid)
    assert put_jid == peek_jid
    assert body == 'job'

@with_beanstalkd()
def test_peek_not_found(c: Client) -> None:
    with pytest.raises(NotFoundError):
        c.peek(111)

@with_beanstalkd()
def test_peek_ready(c: Client) -> None:
    put_jid = c.put('ready')
    peek_jid, body = c.peek_ready()
    assert put_jid == peek_jid
    assert body == 'ready'

@with_beanstalkd()
def test_peek_ready_not_found(c: Client) -> None:
    c.put('delayed', delay=timedelta(seconds=10))
    with pytest.raises(NotFoundError):
        c.peek_ready()

@with_beanstalkd()
def test_peek_delayed(c: Client) -> None:
    put_jid = c.put('delayed', delay=timedelta(seconds=10))
    peek_jid, body = c.peek_delayed()
    assert put_jid == peek_jid
    assert body == 'delayed'

@with_beanstalkd()
def test_peek_delayed_not_found(c: Client) -> None:
    with pytest.raises(NotFoundError):
        c.peek_delayed()

@with_beanstalkd()
def test_peek_buried(c: Client) -> None:
    put_jid = c.put('buried')
    jid, _ = c.reserve()
    c.bury(jid)
    peek_jid, body = c.peek_buried()
    assert put_jid == peek_jid
    assert body == 'buried'

@with_beanstalkd()
def test_peek_buried_not_found(c: Client) -> None:
    c.put('a ready job')
    with pytest.raises(NotFoundError):
        c.peek_buried()

@with_beanstalkd()
def test_kick(c: Client) -> None:
    c.put('a delayed job', delay=timedelta(hours=1))
    c.put('another delayed job', delay=timedelta(hours=1))
    c.put('a ready job')
    jid, _ = c.reserve()
    c.bury(jid)
    assert c.kick(10) == 1
    assert c.kick(10) == 2

@with_beanstalkd()
def test_kick_job(c: Client) -> None:
    jid = c.put('a delayed job', delay=timedelta(hours=1))
    c.kick_job(jid)
    c.reserve(timeout=timedelta())

@with_beanstalkd()
def test_stats_job(c: Client) -> None:
    jid = c.put('job')
    assert c.stats_job(jid) == {
        'id': 1,
        'tube': 'default',
        'state': 'ready',
        'pri': DEFAULT_PRIORITY,
        'age': 0,
        'delay': 0,
        'ttr': DEFAULT_TTR.total_seconds(),
        'time-left': 0,
        'file': 0,
        'reserves': 0,
        'timeouts': 0,
        'releases': 0,
        'buries': 0,
        'kicks': 0,
    }

@with_beanstalkd(use='foo')
def test_stats_tube(c: Client) -> None:
    assert c.stats_tube('default') == {
        'name': 'default',
        'current-jobs-urgent': 0,
        'current-jobs-ready': 0,
        'current-jobs-reserved': 0,
        'current-jobs-delayed': 0,
        'current-jobs-buried': 0,
        'total-jobs': 0,
        'current-using': 0,
        'current-watching': 1,
        'current-waiting': 0,
        'cmd-delete': 0,
        'cmd-pause-tube': 0,
        'pause': 0,
        'pause-time-left': 0,
    }

@with_beanstalkd()
def test_stats(c: Client) -> None:
    s = c.stats()
    assert s['current-jobs-urgent'] == 0
    assert s['current-jobs-ready'] == 0
    assert s['current-jobs-reserved'] == 0
    assert s['current-jobs-delayed'] == 0
    assert s['current-jobs-buried'] == 0
    assert s['cmd-put'] == 0
    assert s['cmd-peek'] == 0
    assert s['cmd-peek-ready'] == 0
    assert s['cmd-peek-delayed'] == 0
    assert s['cmd-peek-buried'] == 0
    assert s['cmd-reserve'] == 0
    assert s['cmd-reserve-with-timeout'] == 0
    assert s['cmd-delete'] == 0
    assert s['cmd-release'] == 0
    assert s['cmd-use'] == 0
    assert s['cmd-watch'] == 0
    assert s['cmd-ignore'] == 0
    assert s['cmd-bury'] == 0
    assert s['cmd-kick'] == 0
    assert s['cmd-touch'] == 0
    assert s['cmd-stats'] == 1
    assert s['cmd-stats-job'] == 0
    assert s['cmd-stats-tube'] == 0
    assert s['cmd-list-tubes'] == 0
    assert s['cmd-list-tube-used'] == 0
    assert s['cmd-list-tubes-watched'] == 0
    assert s['cmd-pause-tube'] == 0
    assert s['job-timeouts'] == 0
    assert s['total-jobs'] == 0
    assert 'max-job-size' in s
    assert s['current-tubes'] == 1
    assert s['current-connections'] == 1
    assert s['current-producers'] == 0
    assert s['current-workers'] == 0
    assert s['current-waiting'] == 0
    assert s['total-connections'] == 1
    assert 'pid' in s
    assert 'version' in s
    assert 'rusage-utime' in s
    assert 'rusage-stime' in s
    assert s['uptime'] == 0
    assert s['binlog-oldest-index'] == 0
    assert s['binlog-current-index'] == 0
    assert s['binlog-records-migrated'] == 0
    assert s['binlog-records-written'] == 0
    assert 'binlog-max-size' in s
    assert 'id' in s
    assert s['hostname'] == socket.getfqdn()

@with_beanstalkd(use='default')
def test_max_job_size(c: Client) -> None:
    with pytest.raises(JobTooBigError):
        c.put(bytes(2**16))

@with_beanstalkd()
def test_job_not_found(c: Client) -> None:
    with pytest.raises(NotFoundError):
        c.delete(87)

@with_beanstalkd()
def test_not_ignored(c: Client) -> None:
    with pytest.raises(NotIgnoredError):
        c.ignore('default')

@with_beanstalkd(encoding=None)
def test_str_body_no_encoding(c: Client) -> None:
    with pytest.raises(TypeError):
        c.put('a str job')

@with_fake(response='BURIED 10\r\n')
def test_put_buried_error(c: Client) -> None:
    with pytest.raises(BuriedError) as e:
        c.put('hello')
    assert e.value.jid == 10

@with_fake(response='BURIED\r\n')
def test_release_buried_error(c: Client) -> None:
    with pytest.raises(BuriedError) as e:
        c.release(1)
    assert e.value.jid is None

@with_fake(response='FOO 1 2 3\r\n')
def test_unknown_response_error(c: Client) -> None:
    with pytest.raises(UnknownResponseError) as e:
        c.reserve()
    assert e.value.status == b'FOO'
    assert e.value.values == [b'1', b'2', b'3']

@with_fake(response='RESERVED 1 4\r\nABC\r\n')
def test_eof_error(c: Client) -> None:
    with pytest.raises(ConnectionError) as e:
        c.reserve()
    assert e.value.args[0] == "Unexpected EOF reading chunk"

@with_fake(response='USING a')
def test_response_missing_crlf(c: Client) -> None:
    with pytest.raises(AssertionError):
        c.use('a')

@with_fake(response='')
def test_unexpected_eof(c: Client) -> None:
    with pytest.raises(ConnectionError) as e:
        c.reserve()
    assert e.value.args[0] == "Unexpected EOF"
<commit_msg>Fix Travis build<commit_after>import subprocess
import time
from contextlib import closing
from datetime import datetime, timedelta
from typing import Any, Callable

import pytest

from greenstalk import Client
from greenstalk.client import DEFAULT_PRIORITY, DEFAULT_TTR
from greenstalk.exceptions import (
    BuriedError, DeadlineSoonError, JobTooBigError, NotFoundError,
    NotIgnoredError, TimedOutError, UnknownResponseError
)

TEST_PORT = 4444

def with_subprocess(*cli: Any) -> Callable:
    def configuration(**kwargs: Any) -> Callable:
        def decorator(test: Callable) -> Callable:
            def wrapper() -> None:
                cmdline = list(cli)
                try:
                    response = kwargs.pop('response')
                except KeyError:
                    pass
                else:
                    cmdline.append(response)
                process = subprocess.Popen(cmdline)
                time.sleep(0.1)
                try:
                    with closing(Client(port=TEST_PORT, **kwargs)) as c:
                        test(c)
                finally:
                    process.terminate()
                    process.wait()
            return wrapper
        return decorator
    return configuration

with_beanstalkd = with_subprocess('beanstalkd', '-l', '127.0.0.1', '-p', str(TEST_PORT))
with_fake = with_subprocess('scripts/fake-response', str(TEST_PORT))

@with_beanstalkd()
def test_basic_usage(c: Client) -> None:
    c.use('emails')
    put_jid = c.put('测试@example.com')
    c.watch('emails')
    c.ignore('default')
    reserve_jid, body = c.reserve()
    assert put_jid == reserve_jid
    assert body == '测试@example.com'
    c.delete(reserve_jid)

@with_beanstalkd()
def test_put_priority(c: Client) -> None:
    c.put('2', priority=2)
    c.put('1', priority=1)
    _, body = c.reserve()
    assert body == '1'
    _, body = c.reserve()
    assert body == '2'

@with_beanstalkd()
def test_delays(c: Client) -> None:
    c.put('delayed', delay=timedelta(seconds=1))
    before = datetime.now()
    jid, body = c.reserve()
    assert body == 'delayed'
    assert datetime.now() - before >= timedelta(seconds=1)
    c.release(jid, delay=timedelta(seconds=2))
    with pytest.raises(TimedOutError):
        c.reserve(timeout=timedelta(seconds=1))
    jid, _ = c.reserve(timeout=timedelta(seconds=1))
    c.bury(jid)
    with pytest.raises(TimedOutError):
        c.reserve(timeout=timedelta(seconds=0))

@with_beanstalkd()
def test_ttr(c: Client) -> None:
    c.put('two second ttr', ttr=timedelta(seconds=2))
    before = datetime.now()
    jid, _ = c.reserve()
    with pytest.raises(DeadlineSoonError):
        c.reserve()
    c.touch(jid)
    with pytest.raises(DeadlineSoonError):
        c.reserve()
    c.release(jid)
    delta = datetime.now() - before
    assert delta >= timedelta(seconds=1, milliseconds=950)
    assert delta <= timedelta(seconds=2, milliseconds=50)

@with_beanstalkd()
def test_reserve_raises_on_timeout(c: Client) -> None:
    before = datetime.now()
    with pytest.raises(TimedOutError):
        c.reserve(timeout=timedelta(seconds=1))
    delta = datetime.now() - before
    assert delta >= timedelta(seconds=1)
    assert delta <= timedelta(seconds=1, milliseconds=50)

@with_beanstalkd(use='hosts', watch='hosts')
def test_initialize_with_tubes(c: Client) -> None:
    c.put('www.example.com')
    jid, body = c.reserve()
    assert body == 'www.example.com'
    c.delete(jid)
    c.use('default')
    c.put('')
    with pytest.raises(TimedOutError):
        c.reserve(timeout=timedelta())

@with_beanstalkd(watch=['static', 'dynamic'])
def test_initialize_watch_multiple(c: Client) -> None:
    c.use('static')
    c.put(b'haskell')
    c.put(b'rust')
    c.use('dynamic')
    c.put(b'python')
    jid, body = c.reserve(timeout=timedelta())
    assert body == 'haskell'
    jid, body = c.reserve(timeout=timedelta())
    assert body == 'rust'
    jid, body = c.reserve(timeout=timedelta())
    assert body == 'python'

@with_beanstalkd(encoding=None)
def test_binary_jobs(c: Client) -> None:
    with open('python-logo.png', 'rb') as f:
        image = f.read()
    c.put(image)
    jid, body = c.reserve()
    assert body == image

@with_beanstalkd()
def test_peek(c: Client) -> None:
    put_jid = c.put('job')
    peek_jid, body = c.peek(put_jid)
    assert put_jid == peek_jid
    assert body == 'job'

@with_beanstalkd()
def test_peek_not_found(c: Client) -> None:
    with pytest.raises(NotFoundError):
        c.peek(111)

@with_beanstalkd()
def test_peek_ready(c: Client) -> None:
    put_jid = c.put('ready')
    peek_jid, body = c.peek_ready()
    assert put_jid == peek_jid
    assert body == 'ready'

@with_beanstalkd()
def test_peek_ready_not_found(c: Client) -> None:
    c.put('delayed', delay=timedelta(seconds=10))
    with pytest.raises(NotFoundError):
        c.peek_ready()

@with_beanstalkd()
def test_peek_delayed(c: Client) -> None:
    put_jid = c.put('delayed', delay=timedelta(seconds=10))
    peek_jid, body = c.peek_delayed()
    assert put_jid == peek_jid
    assert body == 'delayed'

@with_beanstalkd()
def test_peek_delayed_not_found(c: Client) -> None:
    with pytest.raises(NotFoundError):
        c.peek_delayed()

@with_beanstalkd()
def test_peek_buried(c: Client) -> None:
    put_jid = c.put('buried')
    jid, _ = c.reserve()
    c.bury(jid)
    peek_jid, body = c.peek_buried()
    assert put_jid == peek_jid
    assert body == 'buried'

@with_beanstalkd()
def test_peek_buried_not_found(c: Client) -> None:
    c.put('a ready job')
    with pytest.raises(NotFoundError):
        c.peek_buried()

@with_beanstalkd()
def test_kick(c: Client) -> None:
    c.put('a delayed job', delay=timedelta(hours=1))
    c.put('another delayed job', delay=timedelta(hours=1))
    c.put('a ready job')
    jid, _ = c.reserve()
    c.bury(jid)
    assert c.kick(10) == 1
    assert c.kick(10) == 2

@with_beanstalkd()
def test_kick_job(c: Client) -> None:
    jid = c.put('a delayed job', delay=timedelta(hours=1))
    c.kick_job(jid)
    c.reserve(timeout=timedelta())

@with_beanstalkd()
def test_stats_job(c: Client) -> None:
    jid = c.put('job')
    assert c.stats_job(jid) == {
        'id': 1,
        'tube': 'default',
        'state': 'ready',
        'pri': DEFAULT_PRIORITY,
        'age': 0,
        'delay': 0,
        'ttr': DEFAULT_TTR.total_seconds(),
        'time-left': 0,
        'file': 0,
        'reserves': 0,
        'timeouts': 0,
        'releases': 0,
        'buries': 0,
        'kicks': 0,
    }

@with_beanstalkd(use='foo')
def test_stats_tube(c: Client) -> None:
    assert c.stats_tube('default') == {
        'name': 'default',
        'current-jobs-urgent': 0,
        'current-jobs-ready': 0,
        'current-jobs-reserved': 0,
        'current-jobs-delayed': 0,
        'current-jobs-buried': 0,
        'total-jobs': 0,
        'current-using': 0,
        'current-watching': 1,
        'current-waiting': 0,
        'cmd-delete': 0,
        'cmd-pause-tube': 0,
        'pause': 0,
        'pause-time-left': 0,
    }

@with_beanstalkd()
def test_stats(c: Client) -> None:
    s = c.stats()
    assert s['current-jobs-urgent'] == 0
    assert s['current-jobs-ready'] == 0
    assert s['current-jobs-reserved'] == 0
    assert s['current-jobs-delayed'] == 0
    assert s['current-jobs-buried'] == 0
    assert s['cmd-put'] == 0
    assert s['cmd-peek'] == 0
    assert s['cmd-peek-ready'] == 0
    assert s['cmd-peek-delayed'] == 0
    assert s['cmd-peek-buried'] == 0
    assert s['cmd-reserve'] == 0
    assert s['cmd-reserve-with-timeout'] == 0
    assert s['cmd-delete'] == 0
    assert s['cmd-release'] == 0
    assert s['cmd-use'] == 0
    assert s['cmd-watch'] == 0
    assert s['cmd-ignore'] == 0
    assert s['cmd-bury'] == 0
    assert s['cmd-kick'] == 0
    assert s['cmd-touch'] == 0
    assert s['cmd-stats'] == 1
    assert s['cmd-stats-job'] == 0
    assert s['cmd-stats-tube'] == 0
    assert s['cmd-list-tubes'] == 0
    assert s['cmd-list-tube-used'] == 0
    assert s['cmd-list-tubes-watched'] == 0
    assert s['cmd-pause-tube'] == 0
    assert s['job-timeouts'] == 0
    assert s['total-jobs'] == 0
    assert 'max-job-size' in s
    assert s['current-tubes'] == 1
    assert s['current-connections'] == 1
    assert s['current-producers'] == 0
    assert s['current-workers'] == 0
    assert s['current-waiting'] == 0
    assert s['total-connections'] == 1
    assert 'pid' in s
    assert 'version' in s
    assert 'rusage-utime' in s
    assert 'rusage-stime' in s
    assert s['uptime'] == 0
    assert s['binlog-oldest-index'] == 0
    assert s['binlog-current-index'] == 0
    assert s['binlog-records-migrated'] == 0
    assert s['binlog-records-written'] == 0
    assert 'binlog-max-size' in s
    assert 'id' in s
    assert 'hostname' in s

@with_beanstalkd(use='default')
def test_max_job_size(c: Client) -> None:
    with pytest.raises(JobTooBigError):
        c.put(bytes(2**16))

@with_beanstalkd()
def test_job_not_found(c: Client) -> None:
    with pytest.raises(NotFoundError):
        c.delete(87)

@with_beanstalkd()
def test_not_ignored(c: Client) -> None:
    with pytest.raises(NotIgnoredError):
        c.ignore('default')

@with_beanstalkd(encoding=None)
def test_str_body_no_encoding(c: Client) -> None:
    with pytest.raises(TypeError):
        c.put('a str job')

@with_fake(response='BURIED 10\r\n')
def test_put_buried_error(c: Client) -> None:
    with pytest.raises(BuriedError) as e:
        c.put('hello')
    assert e.value.jid == 10

@with_fake(response='BURIED\r\n')
def test_release_buried_error(c: Client) -> None:
    with pytest.raises(BuriedError) as e:
        c.release(1)
    assert e.value.jid is None

@with_fake(response='FOO 1 2 3\r\n')
def test_unknown_response_error(c: Client) -> None:
    with pytest.raises(UnknownResponseError) as e:
        c.reserve()
    assert e.value.status == b'FOO'
    assert e.value.values == [b'1', b'2', b'3']

@with_fake(response='RESERVED 1 4\r\nABC\r\n')
def test_eof_error(c: Client) -> None:
    with pytest.raises(ConnectionError) as e:
        c.reserve()
    assert e.value.args[0] == "Unexpected EOF reading chunk"

@with_fake(response='USING a')
def test_response_missing_crlf(c: Client) -> None:
    with pytest.raises(AssertionError):
        c.use('a')

@with_fake(response='')
def test_unexpected_eof(c: Client) -> None:
    with pytest.raises(ConnectionError) as e:
        c.reserve()
    assert e.value.args[0] == "Unexpected EOF"
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from __future__ import print_function

import unittest
import time
import os
import csv

from globalvalues import RPI
if RPI:
    import RPi.GPIO as GPIO

import sensor
import sender
import auxiliaries
import manager
import cust_crypt

from auxiliaries import get_data
from manager import Manager

from globalvalues import POWER_LED_PIN, NETWORK_LED_PIN, COUNTS_LED_PIN
from globalvalues import DEFAULT_CONFIG, DEFAULT_PUBLICKEY
from globalvalues import ANSI_RESET, ANSI_GR, ANSI_RED
from globalvalues import DEFAULT_DATALOG, DEFAULT_TEST_DATALOG

if RPI:
    test_config_path = DEFAULT_CONFIG
    test_publickey_path = DEFAULT_PUBLICKEY
    configs_present = True
else:
    # obviously, for security, the config and public key should NOT be
    #   included in the (public) repo!
    # these paths are for Brian's LBL desktop, but you could put them
    #   here for other machines too.
    test_config_path = './testconfig/test1.csv'
    test_publickey_path = './testconfig/id_rsa_lbl.pub'
    if (os.path.exists(test_config_path) and
            os.path.exists(test_publickey_path)):
        configs_present = True
    else:
        configs_present = False

TEST_LOGFILE = 'test.log'

class TestVerbosity(unittest.TestCase):

    class Verbosity1(object):
        def __init__(self, vlevel=1):
            auxiliaries.set_verbosity(self, verbosity=vlevel)

    def setUp(self):
        self.verbose_obj = TestVerbosity.Verbosity1(vlevel=1)
        print('Testing set_verbosity()')

    def test_verbosity(self):
        print('Two words of {}green text{} should appear here: '.format(
            ANSI_GR, ANSI_RESET))
        self.verbose_obj.vprint(0, '{}one{}'.format(ANSI_GR, ANSI_RESET))
        self.verbose_obj.vprint(1, '{}two{}'.format(ANSI_GR, ANSI_RESET))
        self.verbose_obj.vprint(2, '{}three{}'.format(ANSI_RED, ANSI_RESET))
        self.verbose_obj.vprint(3, '{}four{}'.format(ANSI_RED, ANSI_RESET))
        print()
        self.assertTrue(True)

    def tearDown(self):
        del(self.verbose_obj)
        print()

class TestLogging(unittest.TestCase):

    class Verbosity2(object):
        def __init__(self, vlevel=1, logfile=TEST_LOGFILE):
            try:
                os.remove(logfile)
            except OSError:
                pass
            auxiliaries.set_verbosity(self, verbosity=vlevel, logfile=logfile)

    def setUp(self):
        self.verbose_obj = TestLogging.Verbosity2(vlevel=1)
        print('Testing logging')

    def test_logging(self):
        print('Two words of {}green text{} should appear here: '.format(
            ANSI_GR, ANSI_RESET))
        textlines = [
            '{}one{}'.format(ANSI_GR, ANSI_RESET),
            '{}two{}'.format(ANSI_GR, ANSI_RESET),
            '{}three{}'.format(ANSI_RED, ANSI_RESET),
            '{}four{}'.format(ANSI_RED, ANSI_RESET)
        ]
        [self.verbose_obj.vprint(i, textlines[i]) for i in range(4)]
        print()
        with open(TEST_LOGFILE, 'r') as f:
            fline = f.readline()
            self.assertTrue(fline.endswith(textlines[0] + '\n'))
            fline = f.readline()
            self.assertTrue(fline.endswith(textlines[1] + '\n'))
            fline = f.readline()
            self.assertFalse(fline)

    def tearDown(self):
        del(self.verbose_obj)
        try:
            os.remove(TEST_LOGFILE)
        except OSError:
            pass
        print()

@unittest.skipUnless(RPI, "LED test only runs on a Raspberry Pi")
class TestLEDs(unittest.TestCase):

    def setUp(self):
        pins = (POWER_LED_PIN, NETWORK_LED_PIN, COUNTS_LED_PIN)
        self.LEDs = [auxiliaries.LED(pin=p) for p in pins]
        print('Testing LEDs',)

    def test_LED(self):
        print('on')
        [LED.on() for LED in self.LEDs]
        time.sleep(1)

        print('off')
        [LED.off() for LED in self.LEDs]
        time.sleep(1)

        print('flash')
        [LED.flash() for LED in self.LEDs]
        time.sleep(1)

        print('start blink')
        [LED.start_blink(interval=0.5) for LED in self.LEDs]
        time.sleep(3)

        print('stop blink')
        [LED.stop_blink() for LED in self.LEDs]
        time.sleep(1)

    def tearDown(self):
        GPIO.cleanup()
        print()

class TestNetworkStatus(unittest.TestCase):
    """
    Doesn't use the auto pinging subprocess - just manually run methods
    """

    good_hostname = 'www.google.com'
    bad_hostname = 'asnbdfmnasdbf.dosenet.dhcp.lbl.gov'

    def setUp(self):
        if RPI:
            self.LED = auxiliaries.LED(pin=NETWORK_LED_PIN)
        else:
            self.LED = None
        print('Testing NetworkStatus')

        self.net = auxiliaries.NetworkStatus(
            hostname=self.good_hostname,
            network_led=self.LED,
            pinging=False,
            verbosity=2)

    def test_is_up(self):
        self.net.update()
        self.assertTrue(self.net)

    def test_is_down(self):
        # give an invalid hostname
        self.net.hostname = self.bad_hostname
        self.net.update()

        self.assertFalse(self.net)

        self.net.hostname = self.good_hostname
        self.net.update()

    def tearDown(self):
        if RPI:
            GPIO.cleanup()
        del(self.net)
        print()

@unittest.skipUnless(
    RPI, "NetworkStatus live test only operates on a Raspberry Pi")
class TestNetworkStatusLive(TestNetworkStatus):
    """
    check the subprocess that pings at intervals
    also check LED behavior
    """

    # inherit good_hostname, bad_hostname
    # overwrite setUp(), tearDown(), test_is_up(), test_is_down()

    def setUp(self):
        self.LED = auxiliaries.LED(pin=NETWORK_LED_PIN)
        print('Testing NetworkStatus (live)')

        self.net = auxiliaries.NetworkStatus(
            hostname=self.good_hostname,
            up_interval_s=3,
            down_interval_s=1,
            network_led=self.LED,
            pinging=True,
            verbosity=2)

    def test_is_up(self):
        print('test_is_up (live)...')
        time.sleep(2)
        self.assertTrue(self.net)
        time.sleep(6)
        self.assertTrue(self.net)

    @unittest.skip(
        ("test_is_down (live) doesn't work until I can " +
         "hack the system network settings..."))
    def test_is_down(self):
        print('test_is_down (live)...')
        # give an invalid hostname
        self.net.hostname = self.bad_hostname

        time.sleep(3)
        self.assertFalse(self.net)
        time.sleep(3)

        # restore connection
        self.net.hostname = self.good_hostname

        time.sleep(1)
        self.assertTrue(self.net)
        time.sleep(3)
        self.assertTrue(self.net)

    def tearDown(self):
        self.net.stop_pinging()
        GPIO.cleanup()

@unittest.skipUnless(configs_present, "Config test requires config files")
class TestConfig(unittest.TestCase):

    def test(self):
        config = auxiliaries.Config(test_config_path, verbosity=2)
        self.assertIsNotNone(config.ID)
        self.assertIsNotNone(config.hash)
        self.assertIsNotNone(config.lat)
        self.assertIsNotNone(config.long)

@unittest.skipUnless(configs_present, "PublicKey test requires config files")
class TestPublicKey(unittest.TestCase):

    def setUp(self):
        self.publickey = auxiliaries.PublicKey(
            test_publickey_path, verbosity=2)
        self.assertIsInstance(
            self.publickey.encrypter, cust_crypt.PublicDEncrypt)

    def test_encrypt(self):
        test_packet = 'This is a string with which we are testing encryption'
        encrypted_packet = self.publickey.encrypter.encrypt_message(
            test_packet)[0]
        self.assertIsInstance(encrypted_packet, str)

class TestSensor(unittest.TestCase):

    def setUp(self):
        # fake sensor - only simulating counts
        self.sensor = sensor.Sensor(max_accumulation_time_s=2, use_gpio=False)

    def tearDown(self):
        self.sensor.cleanup()
        self.sensor = None

    def test_basic_counts(self):
        self.assertEqual(len(self.sensor.get_all_counts()), 0)
        n = 3
        [self.sensor.count() for _ in xrange(n)]
        self.assertEqual(len(self.sensor.get_all_counts()), n)

    def test_max_accum(self):
        self.assertEqual(len(self.sensor.get_all_counts()), 0)

        n1 = 3
        [self.sensor.count() for _ in xrange(n1)]
        self.assertEqual(len(self.sensor.get_all_counts()), n1)

        time.sleep(1)
        n2 = 4
        [self.sensor.count() for _ in xrange(n2)]
        self.assertEqual(len(self.sensor.get_all_counts()), n1 + n2)

        time.sleep(1.5)
        self.assertEqual(len(self.sensor.get_all_counts()), n2)

        time.sleep(1)
        self.assertEqual(len(self.sensor.get_all_counts()), 0)

class TestSender(unittest.TestCase):

    def test_missing_config(self):
        ss = sender.ServerSender(
            manager=None,
            network_status=None,
            config=None,
            publickey=None,
            verbosity=4)
        with self.assertRaises(sender.MissingFile):
            ss.send_cpm(0, 0)

    @unittest.skipUnless(configs_present, "Sender tests require config files")
    def test_missing_publickey(self):
        ss = sender.ServerSender(
            manager=None,
            network_status=None,
            config=auxiliaries.Config(test_config_path),
            publickey=None,
            verbosity=4)
        with self.assertRaises(sender.MissingFile):
            ss.send_cpm(0, 0)

class TestDataLog(unittest.TestCase):

    def setUp(self):
        print('Checking local data')

    def test_get_data(self):
        """
        Checks the data log functionality.

        Creates a test data log, simulates 2 counts,
        checks that the test data log was created,
        checks that there are 2 counts, and then deletes the test datalog.
        """
        mgr = Manager(test=True, datalog=DEFAULT_TEST_DATALOG)

        now = time.time()
        mgr.handle_cpm(now - 10, now)
        [mgr.sensor.count() for _ in xrange(2)]
        mgr.handle_cpm(now, now + 10)
        output = get_data(DEFAULT_TEST_DATALOG)
        print(output)

        self.assertIsNotNone(output)
        self.assertEqual(len(output), 2)

        os.remove(DEFAULT_TEST_DATALOG)
        mgr.takedown()

    def tearDown(self):
        print()

    # ...

if __name__ == '__main__':
    unittest.main()
<commit_msg>bug fixing<commit_after># -*- coding: utf-8 -*-

from __future__ import print_function

import unittest
import time
import os
import csv

from globalvalues import RPI
if RPI:
    import RPi.GPIO as GPIO

import sensor
import sender
import auxiliaries
import manager
import cust_crypt

from auxiliaries import get_data
from manager import Manager

from globalvalues import POWER_LED_PIN, NETWORK_LED_PIN, COUNTS_LED_PIN
from globalvalues import DEFAULT_CONFIG, DEFAULT_PUBLICKEY
from globalvalues import ANSI_RESET, ANSI_GR, ANSI_RED
from globalvalues import DEFAULT_DATALOG, DEFAULT_TEST_DATALOG

if RPI:
    test_config_path = DEFAULT_CONFIG
    test_publickey_path = DEFAULT_PUBLICKEY
    configs_present = True
else:
    # obviously, for security, the config and public key should NOT be
    #   included in the (public) repo!
    # these paths are for Brian's LBL desktop, but you could put them
    #   here for other machines too.
    test_config_path = './testconfig/test1.csv'
    test_publickey_path = './testconfig/id_rsa_lbl.pub'
    if (os.path.exists(test_config_path) and
            os.path.exists(test_publickey_path)):
        configs_present = True
    else:
        configs_present = False

TEST_LOGFILE = 'test.log'

class TestVerbosity(unittest.TestCase):

    class Verbosity1(object):
        def __init__(self, vlevel=1):
            auxiliaries.set_verbosity(self, verbosity=vlevel)

    def setUp(self):
        self.verbose_obj = TestVerbosity.Verbosity1(vlevel=1)
        print('Testing set_verbosity()')

    def test_verbosity(self):
        print('Two words of {}green text{} should appear here: '.format(
            ANSI_GR, ANSI_RESET))
        self.verbose_obj.vprint(0, '{}one{}'.format(ANSI_GR, ANSI_RESET))
        self.verbose_obj.vprint(1, '{}two{}'.format(ANSI_GR, ANSI_RESET))
        self.verbose_obj.vprint(2, '{}three{}'.format(ANSI_RED, ANSI_RESET))
        self.verbose_obj.vprint(3, '{}four{}'.format(ANSI_RED, ANSI_RESET))
        print()
        self.assertTrue(True)

    def tearDown(self):
        del(self.verbose_obj)
        print()

class TestLogging(unittest.TestCase):

    class Verbosity2(object):
        def __init__(self, vlevel=1, logfile=TEST_LOGFILE):
            try:
                os.remove(logfile)
            except OSError:
                pass
            auxiliaries.set_verbosity(self, verbosity=vlevel, logfile=logfile)

    def setUp(self):
        self.verbose_obj = TestLogging.Verbosity2(vlevel=1)
        print('Testing logging')

    def test_logging(self):
        print('Two words of {}green text{} should appear here: '.format(
            ANSI_GR, ANSI_RESET))
        textlines = [
            '{}one{}'.format(ANSI_GR, ANSI_RESET),
            '{}two{}'.format(ANSI_GR, ANSI_RESET),
            '{}three{}'.format(ANSI_RED, ANSI_RESET),
            '{}four{}'.format(ANSI_RED, ANSI_RESET)
        ]
        [self.verbose_obj.vprint(i, textlines[i]) for i in range(4)]
        print()
        with open(TEST_LOGFILE, 'r') as f:
            fline = f.readline()
            self.assertTrue(fline.endswith(textlines[0] + '\n'))
            fline = f.readline()
            self.assertTrue(fline.endswith(textlines[1] + '\n'))
            fline = f.readline()
            self.assertFalse(fline)

    def tearDown(self):
        del(self.verbose_obj)
        try:
            os.remove(TEST_LOGFILE)
        except OSError:
            pass
        print()

@unittest.skipUnless(RPI, "LED test only runs on a Raspberry Pi")
class TestLEDs(unittest.TestCase):

    def setUp(self):
        pins = (POWER_LED_PIN, NETWORK_LED_PIN, COUNTS_LED_PIN)
        self.LEDs = [auxiliaries.LED(pin=p) for p in pins]
        print('Testing LEDs',)

    def test_LED(self):
        print('on')
        [LED.on() for LED in self.LEDs]
        time.sleep(1)

        print('off')
        [LED.off() for LED in self.LEDs]
        time.sleep(1)

        print('flash')
        [LED.flash() for LED in self.LEDs]
        time.sleep(1)

        print('start blink')
        [LED.start_blink(interval=0.5) for LED in self.LEDs]
        time.sleep(3)

        print('stop blink')
        [LED.stop_blink() for LED in self.LEDs]
        time.sleep(1)

    def tearDown(self):
        GPIO.cleanup()
        print()

class TestNetworkStatus(unittest.TestCase):
    """
    Doesn't use the auto pinging subprocess - just manually run methods
    """

    good_hostname = 'www.google.com'
    bad_hostname = 'asnbdfmnasdbf.dosenet.dhcp.lbl.gov'

    def setUp(self):
        if RPI:
            self.LED = auxiliaries.LED(pin=NETWORK_LED_PIN)
        else:
            self.LED = None
        print('Testing NetworkStatus')

        self.net = auxiliaries.NetworkStatus(
            hostname=self.good_hostname,
            network_led=self.LED,
            pinging=False,
            verbosity=2)

    def test_is_up(self):
        self.net.update()
        self.assertTrue(self.net)

    def test_is_down(self):
        # give an invalid hostname
        self.net.hostname = self.bad_hostname
        self.net.update()

        self.assertFalse(self.net)

        self.net.hostname = self.good_hostname
        self.net.update()

    def tearDown(self):
        if RPI:
            GPIO.cleanup()
        del(self.net)
        print()

@unittest.skipUnless(
    RPI, "NetworkStatus live test only operates on a Raspberry Pi")
class TestNetworkStatusLive(TestNetworkStatus):
    """
    check the subprocess that pings at intervals
    also check LED behavior
    """

    # inherit good_hostname, bad_hostname
    # overwrite setUp(), tearDown(), test_is_up(), test_is_down()

    def setUp(self):
        self.LED = auxiliaries.LED(pin=NETWORK_LED_PIN)
        print('Testing NetworkStatus (live)')

        self.net = auxiliaries.NetworkStatus(
            hostname=self.good_hostname,
            up_interval_s=3,
            down_interval_s=1,
            network_led=self.LED,
            pinging=True,
            verbosity=2)

    def test_is_up(self):
        print('test_is_up (live)...')
        time.sleep(2)
        self.assertTrue(self.net)
        time.sleep(6)
        self.assertTrue(self.net)

    @unittest.skip(
        ("test_is_down (live) doesn't work until I can " +
         "hack the system network settings..."))
    def test_is_down(self):
        print('test_is_down (live)...')
        # give an invalid hostname
        self.net.hostname = self.bad_hostname

        time.sleep(3)
        self.assertFalse(self.net)
        time.sleep(3)

        # restore connection
        self.net.hostname = self.good_hostname

        time.sleep(1)
        self.assertTrue(self.net)
        time.sleep(3)
        self.assertTrue(self.net)

    def tearDown(self):
        self.net.stop_pinging()
        GPIO.cleanup()

@unittest.skipUnless(configs_present, "Config test requires config files")
class TestConfig(unittest.TestCase):

    def test(self):
        config = auxiliaries.Config(test_config_path, verbosity=2)
        self.assertIsNotNone(config.ID)
        self.assertIsNotNone(config.hash)
        self.assertIsNotNone(config.lat)
        self.assertIsNotNone(config.long)

@unittest.skipUnless(configs_present, "PublicKey test requires config files")
class TestPublicKey(unittest.TestCase):

    def setUp(self):
        self.publickey = auxiliaries.PublicKey(
            test_publickey_path, verbosity=2)
        self.assertIsInstance(
            self.publickey.encrypter, cust_crypt.PublicDEncrypt)

    def test_encrypt(self):
        test_packet = 'This is a string with which we are testing encryption'
        encrypted_packet = self.publickey.encrypter.encrypt_message(
            test_packet)[0]
        self.assertIsInstance(encrypted_packet, str)

class TestSensor(unittest.TestCase):

    def setUp(self):
        # fake sensor - only simulating counts
        self.sensor = sensor.Sensor(max_accumulation_time_s=2, use_gpio=False)

    def tearDown(self):
        self.sensor.cleanup()
        self.sensor = None

    def test_basic_counts(self):
        self.assertEqual(len(self.sensor.get_all_counts()), 0)
        n = 3
        [self.sensor.count() for _ in xrange(n)]
        self.assertEqual(len(self.sensor.get_all_counts()), n)

    def test_max_accum(self):
        self.assertEqual(len(self.sensor.get_all_counts()), 0)

        n1 = 3
        [self.sensor.count() for _ in xrange(n1)]
        self.assertEqual(len(self.sensor.get_all_counts()), n1)

        time.sleep(1)
        n2 = 4
        [self.sensor.count() for _ in xrange(n2)]
        self.assertEqual(len(self.sensor.get_all_counts()), n1 + n2)

        time.sleep(1.5)
        self.assertEqual(len(self.sensor.get_all_counts()), n2)

        time.sleep(1)
        self.assertEqual(len(self.sensor.get_all_counts()), 0)

class TestSender(unittest.TestCase):

    def test_missing_config(self):
        ss = sender.ServerSender(
            manager=None,
            network_status=None,
            config=None,
            publickey=None,
            verbosity=4)
        with self.assertRaises(sender.MissingFile):
            ss.send_cpm(0, 0)

    @unittest.skipUnless(configs_present, "Sender tests require config files")
    def test_missing_publickey(self):
        ss = sender.ServerSender(
            manager=None,
            network_status=None,
            config=auxiliaries.Config(test_config_path),
            publickey=None,
            verbosity=4)
        with self.assertRaises(sender.MissingFile):
            ss.send_cpm(0, 0)

class TestDataLog(unittest.TestCase):

    def setUp(self):
        print('Checking local data')

    def test_get_data(self):
        """
        Checks the data log functionality.

        Creates a test data log, simulates 2 counts,
        checks that the test data log was created,
        checks that there are 2 counts, and then deletes the test datalog.
        """
        mgr = Manager(test=True, datalog=DEFAULT_TEST_DATALOG)

        now = time.time()
        mgr.handle_cpm(now - 10, now)
        [mgr.sensor.count() for _ in xrange(2)]
        mgr.handle_cpm(now, now + 10)
        output = get_data(DEFAULT_TEST_DATALOG)
        print(output)

        self.assertIsNotNone(output)
        self.assertEqual(len(output), 3)

        #os.remove(DEFAULT_TEST_DATALOG)
        #mgr.takedown()

    def tearDown(self):
        os.remove(DEFAULT_TEST_DATALOG)
        mgr.takedown()
        print()

    # ...

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>import sublime, sublime_plugin
import os, zipfile

class Themr():
	def load_themes(self):
		themes = [['Theme: Default', 'Default.sublime-theme']]

		for root, dirs, files in os.walk(sublime.packages_path()):
			for filename in (filename for filename in files if filename.endswith('.sublime-theme')):
				name = filename.replace('.sublime-theme', '')
				themes.append(['Theme: ' + name, filename])

		for root, dirs, files in os.walk(sublime.installed_packages_path()):
			for package in (package for package in files if package.endswith('.sublime-package')):
				zf = zipfile.ZipFile(os.path.join(sublime.installed_packages_path(), package))
				for filename in (filename for filename in zf.namelist() if filename.endswith('.sublime-theme')):
					name = os.path.basename(filename).replace('.sublime-theme', '')
					themes.append(['Theme: ' + name, filename])

		themes.sort()
		return themes

	def set_theme(self, s):
		self.settings().set('theme', s)
		sublime.save_settings('Preferences.sublime-settings')

	def get_theme(self):
		return self.settings().get('theme')

	def cycle_theme(self, d):
		themes = self.load_themes()
		the_theme = self.get_theme()
		the_index = [theme[1] for theme in themes].index(the_theme)
		num_of_themes = len(themes)

		if d == 1:
			index = the_index + 1 if the_index < num_of_themes - 1 else 0

		if d == -1:
			index = the_index - 1 if the_index > 0 else num_of_themes - 1

		self.set_theme(themes[index][1])
		sublime.status_message(themes[index][0])

	def settings(self):
		return sublime.load_settings('Preferences.sublime-settings')

Themr = Themr()

class ThemrListThemesCommand(sublime_plugin.WindowCommand):
	def run(self):
		themes = Themr.load_themes()

		def on_done(index):
			if index != -1:
				Themr.set_theme(themes[index][1])
				sublime.status_message(themes[index][0])

		self.window.show_quick_panel(themes, on_done)

class ThemrNextThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		Themr.cycle_theme(1)

class ThemrPrevThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		Themr.cycle_theme(-1)
<commit_msg>Added support for random command<commit_after>import sublime, sublime_plugin
import os, zipfile
from random import random

class Themr():
	def load_themes(self):
		themes = [["Theme: Default", "Default.sublime-theme"]]

		for root, dirs, files in os.walk(sublime.packages_path()):
			for filename in (filename for filename in files if filename.endswith('.sublime-theme')):
				name = filename.replace('.sublime-theme', '')
				themes.append(['Theme: ' + name, filename])

		for root, dirs, files in os.walk(sublime.installed_packages_path()):
			for package in (package for package in files if package.endswith('.sublime-package')):
				zf = zipfile.ZipFile(os.path.join(sublime.installed_packages_path(), package))
				for filename in (filename for filename in zf.namelist() if filename.endswith('.sublime-theme')):
					name = os.path.basename(filename).replace('.sublime-theme', '')
					themes.append(['Theme: ' + name, filename])

		themes.sort()
		return themes

	def set_theme(self, s):
		self.settings().set('theme', s)
		sublime.save_settings('Preferences.sublime-settings')

	def get_theme(self):
		return self.settings().get('theme')

	def cycle_theme(self, d):
		themes = self.load_themes()
		the_theme = self.get_theme()
		index = 0
		the_index = [theme[1] for theme in themes].index(the_theme)
		num_of_themes = len(themes)

		if d == "next":
			index = the_index + 1 if the_index < num_of_themes - 1 else 0

		if d == "prev":
			index = the_index - 1 if the_index > 0 else num_of_themes - 1

		if d == "rand":
			index = int(random() * len(themes))

		self.set_theme(themes[index][1])
		sublime.status_message(themes[index][0])

	def settings(self):
		return sublime.load_settings('Preferences.sublime-settings')

Themr = Themr()

class ThemrListThemesCommand(sublime_plugin.WindowCommand):
	def run(self):
		themes = Themr.load_themes()
		the_theme = Themr.get_theme()
		the_index = [theme[1] for theme in themes].index(the_theme)

		def on_done(index):
			if index != -1:
				Themr.set_theme(themes[index][1])
				sublime.status_message(themes[index][0])

			if index == -1:
				Themr.set_theme(themes[the_index][1])

		def on_select(index):
			Themr.set_theme(themes[index][1])

		self.window.show_quick_panel(themes, on_done)

class ThemrNextThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		Themr.cycle_theme("next")

class ThemrPreviousThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		Themr.cycle_theme("prev")

class ThemrRandomThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		Themr.cycle_theme("rand")
<|endoftext|>


<commit_before>import sublime, sublime_plugin
import os, zipfile, re
from random import random

PREFERENCES = 'Preferences.sublime-settings'
FAVORITES = 'ThemrFavorites.sublime-settings'
DEFAULT_THEME = 'Default.sublime-theme'

is_ST2 = int(sublime.version()) < 3000

class Themr(object):
	_instance = None

	@classmethod
	def instance(cls):
		if not cls._instance:
			cls._instance = cls()
		return cls._instance

	def __init__(self):
		self.preferences = sublime.load_settings(PREFERENCES)
		self.favorites = sublime.load_settings(FAVORITES)
		self.theme = self.preferences.get('theme', DEFAULT_THEME)

		def check_theme():
			""" Check the theme can be set and revert to the previous or default theme if invalid """

			the_theme = self.get_theme()
			themes = self.find_themes()

			if the_theme in themes:
				self.theme = the_theme
			else:
				if self.theme in themes:
					self.set_theme(self.theme)
					sublime.status_message('Theme not found. Reverting to ' + self.theme)
				else:
					self.set_theme(DEFAULT_THEME)
					sublime.status_message('Theme not found. Reverting to ' + DEFAULT_THEME)

		if self.preferences.get('themr_watch_settings', False):
			self.preferences.add_on_change('themr', check_theme)
			check_theme() # run once at startup to validate theme setting

	def find_themes(self):
		""" Return a set of all .sublime-theme files in the Sublime Text package folders """

		themes = set()

		try: # use find_resources() first for ST3
			for theme_resource in sublime.find_resources('*.sublime-theme'):
				filename = os.path.basename(theme_resource)
				themes.add(filename)

		except: # fallback to walk() for ST2
			for root, dirs, files in os.walk(sublime.packages_path()):
				for filename in (filename for filename in files if filename.endswith('.sublime-theme')):
					themes.add(filename)

			for root, dirs, files in os.walk(sublime.installed_packages_path()):
				for package in (package for package in files if package.endswith('.sublime-package')):
					zf = zipfile.ZipFile(os.path.join(sublime.installed_packages_path(), package))
					for filename in (filename for filename in zf.namelist() if filename.endswith('.sublime-theme')):
						themes.add(filename)

		return themes

	def load_themes(self):
		""" Return a list of all .sublime-theme files with favorites flagged """

		all_themes = self.find_themes()
		favorite_themes = self.get_favorites()
		themes = []

		for theme in all_themes:
			favorited = theme in favorite_themes
			pretty_name = theme.replace('.sublime-theme', '')
			if favorited: pretty_name += u'   \u2605' # Put a pretty star icon next to favorited themes. :)
			themes.append([pretty_name, theme, favorited])

		themes.sort()
		return themes

	def list_themes(self, window, theme_list):
		""" Display a quick panel with the contents of the theme_list """

		themes = [[theme[0], theme[1]] for theme in theme_list]
		the_theme = self.get_theme()
		try:
			the_index = [theme[1] for theme in themes].index(the_theme)
		except (ValueError):
			the_index = 0

		def on_done(index):
			""" Set the selected theme """

			if index != -1:
				self.set_theme(themes[index][1])
				sublime.status_message(themes[index][0])

		try:
			window.show_quick_panel(themes, on_done, 0, the_index)
		except:
			window.show_quick_panel(themes, on_done)

	def cycle_themes(self, themes, direction):
		""" Adjust the selected theme in the given direction """

		the_theme = Themr.instance().get_theme()
		index = 0
		num_of_themes = len(themes)
		try:
			the_index = [theme[1] for theme in themes].index(the_theme)
		except (ValueError):
			the_index = 0

		if direction == 'next':
			index = the_index + 1 if the_index < num_of_themes - 1 else 0

		if direction == 'prev':
			index = the_index - 1 if the_index > 0 else num_of_themes - 1

		if direction == 'rand':
			index = int(random() * len(themes))

		Themr.instance().set_theme(themes[index][1])
		sublime.status_message(themes[index][0])

	def set_theme(self, theme):
		""" Save the theme value """

		self.preferences.set('theme', theme)
		sublime.save_settings(PREFERENCES)

	def get_theme(self):
		""" Return the current theme value """

		return self.preferences.get('theme', DEFAULT_THEME)

	def set_favorites(self, themes):
		""" Save the favorites theme list """

		self.favorites.set('themr_favorites', themes)
		sublime.save_settings(FAVORITES)

	def get_favorites(self):
		""" Return the current favorites list """

		return self.favorites.get('themr_favorites')

	# Look for "settings" keys within the theme file
	def load_theme_settings(self):
		""" Parse the .sublime-theme file for any settings keys """

		the_theme = Themr.instance().get_theme()
		pattern = re.compile(r'"settings":\s*\[(?:[, ]*"!?(\w+)")*\]')
		theme_settings = set()

		# Load the actual theme resource files
		resources = [sublime.load_resource(theme) for theme in sublime.find_resources(the_theme)]
		for resource in resources:
			for key in re.findall(pattern, resource):
				theme_settings.add(key)

		# Return a list of tuples with setting key and values
		return [(key, self.preferences.get(key, False)) for key in theme_settings]

	# Called when Sublime API is ready [ST3]
def plugin_loaded():
	Themr.instance()

def plugin_unloaded():
	Themr.instance().preferences.clear_on_change('themr')

class ThemrListThemesCommand(sublime_plugin.WindowCommand):
	def run(self):
		Themr.instance().list_themes(self.window, Themr.instance().load_themes())

class ThemrListFavoriteThemesCommand(sublime_plugin.WindowCommand):
	def run(self):
		Themr.instance().list_themes(self.window, [theme for theme in Themr.instance().load_themes() if theme[2]])

	def is_enabled(self):
		return len(Themr.instance().get_favorites()) > 0

class ThemrCycleThemesCommand(sublime_plugin.WindowCommand):
	def run(self, direction):
		Themr.instance().cycle_themes(Themr.instance().load_themes(), direction)

class ThemrCycleFavoriteThemesCommand(sublime_plugin.WindowCommand):
	def run(self, direction):
		Themr.instance().cycle_themes([theme for theme in Themr.instance().load_themes() if theme[2]], direction)

	def is_enabled(self):
		return len(Themr.instance().get_favorites()) > 1

class ThemrFavoriteCurrentThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		the_theme = Themr.instance().get_theme()
		favorites = Themr.instance().get_favorites()
		favorites.append(the_theme)
		Themr.instance().set_favorites(favorites)
		sublime.status_message(the_theme + ' added to favorites')

	def is_enabled(self):
		return Themr.instance().get_theme() not in Themr.instance().get_favorites()

class ThemrUnfavoriteCurrentThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		the_theme = Themr.instance().get_theme()
		favorites = Themr.instance().get_favorites()
		favorites.remove(the_theme)
		Themr.instance().set_favorites(favorites)
		sublime.status_message(the_theme + ' removed from favorites')

	def is_enabled(self):
		return Themr.instance().get_theme() in Themr.instance().get_favorites()

# Toggle one of the boolean settings used to customize current theme
class ThemrToggleSettingsCommand(sublime_plugin.WindowCommand):
	def run(self):
		the_theme_settings = Themr.instance().load_theme_settings()
		the_theme_settings.sort()
		theme_setting_list = []

		for setting in the_theme_settings:
			if setting[1]:
				theme_setting_list.append('Disable ' + setting[0] + u'   [\u2713]')
			else:
				theme_setting_list.append('Enable ' + setting[0] + u'   [\u2717]')

		# Toggles the setting key/val at the index specified
		def on_done(index):
			if index != -1:
				Themr.instance().preferences.set(the_theme_settings[index][0], not the_theme_settings[index][1])
				sublime.save_settings(PREFERENCES)

				if the_theme_settings[index][1]:
					sublime.status_message('Themr: Disabled ' + the_theme_settings[index][0])
				else:
					sublime.status_message('Themr: Enabled ' + the_theme_settings[index][0])

		self.window.show_quick_panel(theme_setting_list, on_done)

	def is_enabled(self):
		return int(sublime.version()) >= 3000

class ThemrNextThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		self.window.run_command('themr_cycle_themes', {'direction': 'next'})
class ThemrPreviousThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		self.window.run_command('themr_cycle_themes', {'direction': 'prev'})
class ThemrRandomThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		self.window.run_command('themr_cycle_themes', {'direction': 'rand'})

if is_ST2: plugin_loaded()

unload_handler = plugin_unloaded if is_ST2 else lambda: None
<commit_msg>Update status message text when selecting a theme<commit_after>import sublime, sublime_plugin
import os, zipfile, re
from random import random

PREFERENCES = 'Preferences.sublime-settings'
FAVORITES = 'ThemrFavorites.sublime-settings'
DEFAULT_THEME = 'Default.sublime-theme'

is_ST2 = int(sublime.version()) < 3000

class Themr(object):
	_instance = None

	@classmethod
	def instance(cls):
		if not cls._instance:
			cls._instance = cls()
		return cls._instance

	def __init__(self):
		self.preferences = sublime.load_settings(PREFERENCES)
		self.favorites = sublime.load_settings(FAVORITES)
		self.theme = self.preferences.get('theme', DEFAULT_THEME)

		def check_theme():
			""" Check the theme can be set and revert to the previous or default theme if invalid """

			the_theme = self.get_theme()
			themes = self.find_themes()

			if the_theme in themes:
				self.theme = the_theme
			else:
				if self.theme in themes:
					self.set_theme(self.theme)
					sublime.status_message('Theme not found. Reverting to ' + self.theme)
				else:
					self.set_theme(DEFAULT_THEME)
					sublime.status_message('Theme not found. Reverting to ' + DEFAULT_THEME)

		if self.preferences.get('themr_watch_settings', False):
			self.preferences.add_on_change('themr', check_theme)
			check_theme() # run once at startup to validate theme setting

	def find_themes(self):
		""" Return a set of all .sublime-theme files in the Sublime Text package folders """

		themes = set()

		try: # use find_resources() first for ST3
			for theme_resource in sublime.find_resources('*.sublime-theme'):
				filename = os.path.basename(theme_resource)
				themes.add(filename)

		except: # fallback to walk() for ST2
			for root, dirs, files in os.walk(sublime.packages_path()):
				for filename in (filename for filename in files if filename.endswith('.sublime-theme')):
					themes.add(filename)

			for root, dirs, files in os.walk(sublime.installed_packages_path()):
				for package in (package for package in files if package.endswith('.sublime-package')):
					zf = zipfile.ZipFile(os.path.join(sublime.installed_packages_path(), package))
					for filename in (filename for filename in zf.namelist() if filename.endswith('.sublime-theme')):
						themes.add(filename)

		return themes

	def load_themes(self):
		""" Return a list of all .sublime-theme files with favorites flagged """

		all_themes = self.find_themes()
		favorite_themes = self.get_favorites()
		themes = []

		for theme in all_themes:
			favorited = theme in favorite_themes
			pretty_name = theme.replace('.sublime-theme', '')
			if favorited: pretty_name += u'   \u2605' # Put a pretty star icon next to favorited themes. :)
			themes.append([pretty_name, theme, favorited])

		themes.sort()
		return themes

	def list_themes(self, window, theme_list):
		""" Display a quick panel with the contents of the theme_list """

		themes = [[theme[0], theme[1]] for theme in theme_list]
		the_theme = self.get_theme()
		try:
			the_index = [theme[1] for theme in themes].index(the_theme)
		except (ValueError):
			the_index = 0

		def on_done(index):
			""" Set the selected theme """

			if index != -1:
				self.set_theme(themes[index][1])
				sublime.status_message('Theme: ' + themes[index][1].replace('.sublime-theme', ''))

		try:
			window.show_quick_panel(themes, on_done, 0, the_index)
		except:
			window.show_quick_panel(themes, on_done)

	def cycle_themes(self, themes, direction):
		""" Adjust the selected theme in the given direction """

		the_theme = Themr.instance().get_theme()
		index = 0
		num_of_themes = len(themes)
		try:
			the_index = [theme[1] for theme in themes].index(the_theme)
		except (ValueError):
			the_index = 0

		if direction == 'next':
			index = the_index + 1 if the_index < num_of_themes - 1 else 0

		if direction == 'prev':
			index = the_index - 1 if the_index > 0 else num_of_themes - 1

		if direction == 'rand':
			index = int(random() * len(themes))

		Themr.instance().set_theme(themes[index][1])
		sublime.status_message(themes[index][0])

	def set_theme(self, theme):
		""" Save the theme value """

		self.preferences.set('theme', theme)
		sublime.save_settings(PREFERENCES)

	def get_theme(self):
		""" Return the current theme value """

		return self.preferences.get('theme', DEFAULT_THEME)

	def set_favorites(self, themes):
		""" Save the favorites theme list """

		self.favorites.set('themr_favorites', themes)
		sublime.save_settings(FAVORITES)

	def get_favorites(self):
		""" Return the current favorites list """

		return self.favorites.get('themr_favorites')

	# Look for "settings" keys within the theme file
	def load_theme_settings(self):
		""" Parse the .sublime-theme file for any settings keys """

		the_theme = Themr.instance().get_theme()
		pattern = re.compile(r'"settings":\s*\[(?:[, ]*"!?(\w+)")*\]')
		theme_settings = set()

		# Load the actual theme resource files
		resources = [sublime.load_resource(theme) for theme in sublime.find_resources(the_theme)]
		for resource in resources:
			for key in re.findall(pattern, resource):
				theme_settings.add(key)

		# Return a list of tuples with setting key and values
		return [(key, self.preferences.get(key, False)) for key in theme_settings]

	# Called when Sublime API is ready [ST3]
def plugin_loaded():
	Themr.instance()

def plugin_unloaded():
	Themr.instance().preferences.clear_on_change('themr')

class ThemrListThemesCommand(sublime_plugin.WindowCommand):
	def run(self):
		Themr.instance().list_themes(self.window, Themr.instance().load_themes())

class ThemrListFavoriteThemesCommand(sublime_plugin.WindowCommand):
	def run(self):
		Themr.instance().list_themes(self.window, [theme for theme in Themr.instance().load_themes() if theme[2]])

	def is_enabled(self):
		return len(Themr.instance().get_favorites()) > 0

class ThemrCycleThemesCommand(sublime_plugin.WindowCommand):
	def run(self, direction):
		Themr.instance().cycle_themes(Themr.instance().load_themes(), direction)

class ThemrCycleFavoriteThemesCommand(sublime_plugin.WindowCommand):
	def run(self, direction):
		Themr.instance().cycle_themes([theme for theme in Themr.instance().load_themes() if theme[2]], direction)

	def is_enabled(self):
		return len(Themr.instance().get_favorites()) > 1

class ThemrFavoriteCurrentThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		the_theme = Themr.instance().get_theme()
		favorites = Themr.instance().get_favorites()
		favorites.append(the_theme)
		Themr.instance().set_favorites(favorites)
		sublime.status_message(the_theme + ' added to favorites')

	def is_enabled(self):
		return Themr.instance().get_theme() not in Themr.instance().get_favorites()

class ThemrUnfavoriteCurrentThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		the_theme = Themr.instance().get_theme()
		favorites = Themr.instance().get_favorites()
		favorites.remove(the_theme)
		Themr.instance().set_favorites(favorites)
		sublime.status_message(the_theme + ' removed from favorites')

	def is_enabled(self):
		return Themr.instance().get_theme() in Themr.instance().get_favorites()

# Toggle one of the boolean settings used to customize current theme
class ThemrToggleSettingsCommand(sublime_plugin.WindowCommand):
	def run(self):
		the_theme_settings = Themr.instance().load_theme_settings()
		the_theme_settings.sort()
		theme_setting_list = []

		for setting in the_theme_settings:
			if setting[1]:
				theme_setting_list.append('Disable ' + setting[0] + u'   [\u2713]')
			else:
				theme_setting_list.append('Enable ' + setting[0] + u'   [\u2717]')

		# Toggles the setting key/val at the index specified
		def on_done(index):
			if index != -1:
				Themr.instance().preferences.set(the_theme_settings[index][0], not the_theme_settings[index][1])
				sublime.save_settings(PREFERENCES)

				if the_theme_settings[index][1]:
					sublime.status_message('Themr: Disabled ' + the_theme_settings[index][0])
				else:
					sublime.status_message('Themr: Enabled ' + the_theme_settings[index][0])

		self.window.show_quick_panel(theme_setting_list, on_done)

	def is_enabled(self):
		return int(sublime.version()) >= 3000

class ThemrNextThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		self.window.run_command('themr_cycle_themes', {'direction': 'next'})
class ThemrPreviousThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		self.window.run_command('themr_cycle_themes', {'direction': 'prev'})
class ThemrRandomThemeCommand(sublime_plugin.WindowCommand):
	def run(self):
		self.window.run_command('themr_cycle_themes', {'direction': 'rand'})

if is_ST2: plugin_loaded()

unload_handler = plugin_unloaded if is_ST2 else lambda: None
<|endoftext|>


<commit_before># coding: utf-8
from datetime import datetime, timedelta
import tweepy
import re
import sys
import logging.config
import logging
from lib.db_cancel import todayinfo
import lib.jholiday
from lib.tweeter import tweet, get_api

logging.config.fileConfig('./log/log.conf')
log = logging.getLogger('getlog')

def del_yesterday_info():
    # 昨日の日付を取得
    d = datetime.now() + timedelta(days=-1)
    yesterday = "%s/%s/%s" % (d.year, d.month, d.day)

    api = get_api()

    # アカウント情報及びTLの取得
    myinfo = api.me()
    try:
        tweets = tweepy.Cursor(api.user_timeline, id=myinfo.id).items(100)
    except Exception as e:
        log.exception(e)

    # 昨日の定期ツイートを削除
    for t in tweets:
        r = re.compile(yesterday)
        sentence = t.text.encode('utf-8')
        s = re.match(r, sentence)
        if s is None:
            pass
        else:
            try:
                api.destroy_status(t.id)
            except Exception as e:
                log.exception(e)

def get_today_info():
    # 今日の日付を取得
    d = datetime.now()
    # 祝日を取得
    holiday = lib.jholiday.holiday_name(date=datetime.date(d))
    date = u"%s/%s/%s" % (d.year, d.month, d.day)

    # 取得した日付を元にDBから情報を取得
    today = todayinfo(date)
    if holiday is None:
        # Tweet
        if len(today) is 0:
            tweet(u"%s 本日休講はありません" % (date))
        else:
            today = map(decode_utf8, today)
            s = u", ".join(today)
            t = u"%s 本日の休講\n%s" % (date, s)
            if len(t) < 135:
                tweet(t)
            else:
                a = u""
                i = 0
                while len(a) < 120:
                    a = a + u"%s, " % (today[i])
                    i += 1
                i -= 1
                all = [today[o:o + i] for o in range(0, len(today), i)]
                head = u"本日の休講"
                for one in all:
                    s = u", ".join(one)
                    tweet(u"%s %s\n%s" % (date, head, s))
                    head = u"続き"
    else:
        t = u'本日は%sです．課題やレポートは終わりましたか？意義のある祝日をお過ごしください．' % (
            holiday)
        tweet(t)

def decode_utf8(txt):
    return txt.decode('utf-8')

if __name__ == "__main__":
    del_yesterday_info()
    get_today_info()
<commit_msg>祝日のとき日付もツイートするように修正<commit_after># coding: utf-8
from datetime import datetime, timedelta
import tweepy
import re
import sys
import logging.config
import logging
from lib.db_cancel import todayinfo
import lib.jholiday
from lib.tweeter import tweet, get_api

logging.config.fileConfig('./log/log.conf')
log = logging.getLogger('getlog')

def del_yesterday_info():
    # 昨日の日付を取得
    d = datetime.now() + timedelta(days=-1)
    yesterday = "%s/%s/%s" % (d.year, d.month, d.day)

    api = get_api()

    # アカウント情報及びTLの取得
    myinfo = api.me()
    try:
        tweets = tweepy.Cursor(api.user_timeline, id=myinfo.id).items(100)
    except Exception as e:
        log.exception(e)

    # 昨日の定期ツイートを削除
    for t in tweets:
        r = re.compile(yesterday)
        sentence = t.text.encode('utf-8')
        s = re.match(r, sentence)
        if s is None:
            pass
        else:
            try:
                api.destroy_status(t.id)
            except Exception as e:
                log.exception(e)

def get_today_info():
    # 今日の日付を取得
    d = datetime.now()
    # 祝日を取得
    holiday = lib.jholiday.holiday_name(date=datetime.date(d))
    date = u"%s/%s/%s" % (d.year, d.month, d.day)

    # 取得した日付を元にDBから情報を取得
    today = todayinfo(date)
    if holiday is None:
        # Tweet
        if len(today) is 0:
            tweet(u"%s 本日休講はありません" % (date))
        else:
            today = map(decode_utf8, today)
            s = u", ".join(today)
            t = u"%s 本日の休講\n%s" % (date, s)
            if len(t) < 135:
                tweet(t)
            else:
                a = u""
                i = 0
                while len(a) < 120:
                    a = a + u"%s, " % (today[i])
                    i += 1
                i -= 1
                all = [today[o:o + i] for o in range(0, len(today), i)]
                head = u"本日の休講"
                for one in all:
                    s = u", ".join(one)
                    tweet(u"%s %s\n%s" % (date, head, s))
                    head = u"続き"
    else:
        t = u'%s 本日は%sです．課題やレポートは終わりましたか？意義のある祝日をお過ごしください．' % (
            date, holiday)
        tweet(t)

def decode_utf8(txt):
    return txt.decode('utf-8')

if __name__ == "__main__":
    del_yesterday_info()
    get_today_info()
<|endoftext|>


<commit_before># linedt.py

# Imports
import matplotlib.pyplot as plt
import numpy as np

from scipy.linalg import norm

# Plotter
class Plotter(object):
    def __init__(self, delta=0.0):
        self._delta = delta

        i = np.finfo(np.float64)
        self._xmin = i.max
        self._xmax = i.min
        self._ymin = i.max
        self._ymax = i.min

    def __call__(self, ax, P, *args, **kwargs):
        P = np.atleast_2d(P)
        x, y = np.transpose(P)
        ax.plot(x, y, *args, **kwargs)

        self._xmin = min(self._xmin, np.amin(x))
        self._xmax = max(self._xmax, np.amax(x))
        self._ymin = min(self._ymin, np.amin(y))
        self._ymax = max(self._ymax, np.amax(y))

    def _lim(self, min_, max_):
        d = self._delta * (max_ - min_)
        return (min_ - d, max_ + d)

    @property
    def xlim(self):
        return self._lim(self._xmin, self._xmax)

    @property
    def ylim(self):
        return self._lim(self._ymin, self._ymax)

# LineSegment
class LineSegment(object):
    def __init__(self, m, x0, l = 1.0):
        norm_m = norm(m)
        self._m = m / norm_m
        self._x0 = x0
        self._l = l * norm_m
        self._n = np.r_[-self._m[1], self._m[0]]

    def __call__(self, t):
        t = np.atleast_1d(t)
        return self._m * self._l * t[:, np.newaxis] + self._x0

    # closest_preimage
    def closest_preimage(self, Q):
        Q = np.atleast_2d(Q)
        u = np.atleast_1d(np.dot(Q - self._x0, self._m) / self._l)
        u[u < 0.0] = 0.0
        u[u > 1.0] = 1.0
        return u

    # dt
    def dt(self, integral_domain, outside_left=None):
        # create `X` as scanning `integral_domain` along rows, from
        # "top" (max y) to "bottom" (min y)
        slice_ = tuple(slice(None, d) for d in integral_domain[::-1])
        G = map(np.ravel, np.mgrid[slice_])
        X = np.transpose(G)
        X = np.fliplr(X)
        X[:,1] *= -1
        X[:,1] += integral_domain[1]

        u = self.closest_preimage(X)
        Y = self(u)
        r = X - Y
        d = np.sqrt(np.sum(r**2, axis=1))

        if outside_left is not None:
            s = (np.dot(r, self._n) > 0).astype(np.float64)
            s *= 2.0
            s -= 1.0
            if not outside_left:
                s *= -1.0
            d *= s

        return d.reshape(integral_domain[::-1])

# main_test_LineSegment
def main_test_LineSegment():
    x0 = np.r_[0.0, 0.0]
    m = np.r_[2.0, 1.0]
    m /= norm(m)
    l = 4.0
    line = LineSegment(m, x0, l)

    Q = np.array([[2.0, 2.0],
                  [4.0, 3.0]], dtype=np.float64)
    u = line.closest_preimage(Q)

    f, ax = plt.subplots()
    ax.set_aspect('equal')
    plot = Plotter(delta=0.05)

    t = np.linspace(0.0, 1.0, 20, endpoint=True)
    plot(ax, line(t), 'ro-')

    for i, ui in enumerate(u):
        plot(ax, np.r_['0,2', Q[i], line(ui)], 'bo-')

    ax.set_xlim(plot.xlim)
    ax.set_ylim(plot.ylim)

    plt.show()

# main_test_linedt
def main_test_linedt():
    x0 = np.r_[25.0, 25.0]
    m = np.r_[2.0, 1.0]
    m *= (10.0 / norm(m))
    line = LineSegment(m, x0)

    D = line.dt((50, 100), outside_left=True)
    f, ax = plt.subplots()
    ax.imshow(D)
    plt.show()

if __name__ == '__main__':
    # main_test_LineSegment()
    main_test_linedt()

<commit_msg>Add `points` property to `LineSegment` in linedt.py<commit_after># linedt.py

# Imports
import matplotlib.pyplot as plt
import numpy as np

from scipy.linalg import norm

# Plotter
class Plotter(object):
    def __init__(self, delta=0.0):
        self._delta = delta

        i = np.finfo(np.float64)
        self._xmin = i.max
        self._xmax = i.min
        self._ymin = i.max
        self._ymax = i.min

    def __call__(self, ax, P, *args, **kwargs):
        P = np.atleast_2d(P)
        x, y = np.transpose(P)
        ax.plot(x, y, *args, **kwargs)

        self._xmin = min(self._xmin, np.amin(x))
        self._xmax = max(self._xmax, np.amax(x))
        self._ymin = min(self._ymin, np.amin(y))
        self._ymax = max(self._ymax, np.amax(y))

    def _lim(self, min_, max_):
        d = self._delta * (max_ - min_)
        return (min_ - d, max_ + d)

    @property
    def xlim(self):
        return self._lim(self._xmin, self._xmax)

    @property
    def ylim(self):
        return self._lim(self._ymin, self._ymax)

# LineSegment
class LineSegment(object):
    def __init__(self, m, x0, l = 1.0):
        norm_m = norm(m)
        self._m = m / norm_m
        self._x0 = x0
        self._l = l * norm_m
        self._n = np.r_[-self._m[1], self._m[0]]
        self._x1 = self._x0 + self._l * self._m
        self._points = np.r_['0,2', self._x0, self._x1]

    @property
    def points(self):
        return self._points

    def __call__(self, t):
        t = np.atleast_1d(t)
        return self._m * self._l * t[:, np.newaxis] + self._x0

    # closest_preimage
    def closest_preimage(self, Q):
        Q = np.atleast_2d(Q)
        u = np.atleast_1d(np.dot(Q - self._x0, self._m) / self._l)
        u[u < 0.0] = 0.0
        u[u > 1.0] = 1.0
        return u

    # dt
    def dt(self, integral_domain, outside_left=None):
        # create `X` as scanning `integral_domain` along rows, from
        # "top" (max y) to "bottom" (min y)
        slice_ = tuple(slice(None, d) for d in integral_domain[::-1])
        G = map(np.ravel, np.mgrid[slice_])
        X = np.transpose(G)
        X = np.fliplr(X)
        X[:,1] *= -1
        X[:,1] += integral_domain[1]

        u = self.closest_preimage(X)
        Y = self(u)
        r = X - Y
        d = np.sqrt(np.sum(r**2, axis=1))

        if outside_left is not None:
            s = (np.dot(r, self._n) > 0).astype(np.float64)
            s *= 2.0
            s -= 1.0
            if not outside_left:
                s *= -1.0
            d *= s

        return d.reshape(integral_domain[::-1])

# main_test_LineSegment
def main_test_LineSegment():
    x0 = np.r_[0.0, 0.0]
    m = np.r_[2.0, 1.0]
    m /= norm(m)
    l = 4.0
    line = LineSegment(m, x0, l)

    Q = np.array([[2.0, 2.0],
                  [4.0, 3.0]], dtype=np.float64)
    u = line.closest_preimage(Q)

    f, ax = plt.subplots()
    ax.set_aspect('equal')
    plot = Plotter(delta=0.05)

    t = np.linspace(0.0, 1.0, 20, endpoint=True)
    plot(ax, line(t), 'ro-')

    for i, ui in enumerate(u):
        plot(ax, np.r_['0,2', Q[i], line(ui)], 'bo-')

    ax.set_xlim(plot.xlim)
    ax.set_ylim(plot.ylim)

    plt.show()

# main_test_linedt
def main_test_linedt():
    x0 = np.r_[25.0, 25.0]
    m = np.r_[2.0, 1.0]
    m *= (10.0 / norm(m))
    line = LineSegment(m, x0)

    D = line.dt((50, 100), outside_left=True)
    f, ax = plt.subplots()
    ax.imshow(D)
    plt.show()

if __name__ == '__main__':
    # main_test_LineSegment()
    main_test_linedt()

<|endoftext|>


<commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#

"""This module exports the JadeLint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class JadeLint(NodeLinter):

    """Provides an interface to jade-lint."""

    npm_name = 'jade-lint'
    syntax = 'jade'
    cmd = 'jade-lint @ *'
    executable = None
    version_args = '--version'
    version_re = r'(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.0.0'
    regex = r''
    multiline = False
    # line_col_base = (1, 1)
    tempfile_suffix = 'jade'
    error_stream = util.STREAM_BOTH
    # selectors = {}
    # word_re = None
    # defaults = {}
    # inline_settings = None
    # inline_overrides = None
    # comment_re = None
    config_file = ('--config', '.jade-lintrc', '-')

<commit_msg>> Remove double blank line<commit_after>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#

"""This module exports the JadeLint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class JadeLint(NodeLinter):

    """Provides an interface to jade-lint."""

    npm_name = 'jade-lint'
    syntax = 'jade'
    cmd = 'jade-lint @ *'
    executable = None
    version_args = '--version'
    version_re = r'(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 1.0.0'
    regex = r''
    multiline = False
    # line_col_base = (1, 1)
    tempfile_suffix = 'jade'
    error_stream = util.STREAM_BOTH
    # selectors = {}
    # word_re = None
    # defaults = {}
    # inline_settings = None
    # inline_overrides = None
    # comment_re = None
    config_file = ('--config', '.jade-lintrc', '-')
<|endoftext|>