<commit_before>#! /usr/local/python

# Fix Python source files to use the new class definition syntax,
# i.e.,
#	class C(base, base, ...): ...
# instead of
#	class C() = base(), base(), ...: ...
#
# Command line arguments are files or directories to be processed.
# Directories are searched recursively for files whose name looks
# like a python module.
# Symbolic links are always ignored (except as explicit directory
# arguments).  Of course, the original file is kept as a back-up
# (with a "~" attached to its name).
#
# Undoubtedly you can do this using find and sed, but this is
# a nice example of Python code that recurses down a directory tree
# and uses regular expressions.  Also note several subtleties like
# preserving the file's mode and avoiding to even write a temp file
# when no changes are needed for a file.
#
# Changes made are reported to stdout in a diff-like format.

import sys
import regexp
import posix
import path
import string
from stat import *

err = sys.stderr.write
dbg = err
rep = sys.stdout.write

def main():
	bad = 0
	if not sys.argv[1:]: # No arguments
		err('usage: classfix file-or-directory ...\n')
		sys.exit(2)
	for arg in sys.argv[1:]:
		if path.isdir(arg):
			if recursedown(arg): bad = 1
		elif path.islink(arg):
			err(arg + ': will not process symbolic links\n')
			bad = 1
		else:
			if fix(arg): bad = 1
	sys.exit(bad)

ispython = regexp.compile('^[a-zA-Z0-9_]+\.py$').match # This is a method!

def recursedown(dirname):
	dbg('recursedown(' + `dirname` + ')\n')
	bad = 0
	try:
		names = posix.listdir(dirname)
	except posix.error, msg:
		err(dirname + ': cannot list directory: ' + `msg` + '\n')
		return 1
	for name in names:
		if name in ('.', '..'): continue
		fullname = path.join(dirname, name)
		if path.islink(fullname): pass
		elif path.isdir(fullname):
			if recursedown(fullname): bad = 1
		elif ispython(name):
			if fix(fullname): bad = 1
	return bad

# This expression doesn't catch *all* class definition headers,
# but it's darn pretty close.
classexpr = '^([ \t]*class +[a-zA-Z0-9_]+) *\( *\) *((=.*)?):'
findclass = regexp.compile(classexpr).match # This is a method!

baseexpr = '^ *(.*) *\( *\) *$'
findbase = regexp.compile(baseexpr).match # This is a method, too!

def fix(filename):
##	dbg('fix(' + `filename` + ')\n')
	try:
		f = open(filename, 'r')
	except IOError, msg:
		err(filename + ': cannot open: ' + `msg` + '\n')
		return 1
	head, tail = path.split(filename)
	tempname = path.join(head, '@' + tail)
	tf = None
	# If we find a match, we rewind the file and start over but
	# now copy everything to a temp file.
	while 1:
		line = f.readline()
		if not line: break
		res = findclass(line)
		if not res:
			if tf: tf.write(line)
			continue
		if not tf:
			try:
				tf = open(tempname, 'w')
			except IOError, msg:
				f.close()
				err(tempname+': cannot create: '+`msg`+'\n')
				return 1
			rep(filename + ':\n')
			# Rewind the input file and start all over:
			f.seek(0)
			continue
		a0, b0 = res[0] # Whole match (up to ':')
		a1, b1 = res[1] # First subexpression (up to classname)
		a2, b2 = res[2] # Second subexpression (=.*)
		head = line[:b1]
		tail = line[b0:] # Unmatched rest of line
		if a2 = b2: # No base classes -- easy case
			newline = head + ':' + tail
		else:
			# Get rid of leading '='
			basepart = line[a2+1:b2]
			# Extract list of base expressions
			bases = string.splitfields(basepart, ',')
			# Strip trailing '()' from each base expression
			for i in range(len(bases)):
				res = findbase(bases[i])
				if res:
					(x0, y0), (x1, y1) = res
					bases[i] = bases[i][x1:y1]
			# Join the bases back again and build the new line
			basepart = string.joinfields(bases, ', ')
			newline = head + '(' + basepart + '):' + tail
		rep('< ' + line)
		rep('> ' + newline)
		tf.write(newline)
	f.close()
	if not tf: return 0 # No changes

	# Finishing touch -- move files

	# First copy the file's mode to the temp file
	try:
		statbuf = posix.stat(filename)
		posix.chmod(tempname, statbuf[ST_MODE] & 0x7777)
	except posix.error, msg:
		err(tempname + ': warning: chmod failed (' + `msg` + ')\n')
	# Then make a backup of the original file as filename~
	try:
		posix.rename(filename, filename + '~')
	except posix.error, msg:
		err(filename + ': warning: backup failed (' + `msg` + ')\n')
	# Now move the temp file to the original file
	try:
		posix.rename(tempname, filename)
	except posix.error, msg:
		err(filename + ': rename failed (' + `msg` + ')\n')
		return 1
	# Return succes
	return 0

main()
<commit_msg>Fix bogus mode mask.<commit_after>#! /usr/local/python

# Fix Python source files to use the new class definition syntax,
# i.e.,
#	class C(base, base, ...): ...
# instead of
#	class C() = base(), base(), ...: ...
#
# Command line arguments are files or directories to be processed.
# Directories are searched recursively for files whose name looks
# like a python module.
# Symbolic links are always ignored (except as explicit directory
# arguments).  Of course, the original file is kept as a back-up
# (with a "~" attached to its name).
#
# Undoubtedly you can do this using find and sed, but this is
# a nice example of Python code that recurses down a directory tree
# and uses regular expressions.  Also note several subtleties like
# preserving the file's mode and avoiding to even write a temp file
# when no changes are needed for a file.
#
# Changes made are reported to stdout in a diff-like format.

import sys
import regexp
import posix
import path
import string
from stat import *

err = sys.stderr.write
dbg = err
rep = sys.stdout.write

def main():
	bad = 0
	if not sys.argv[1:]: # No arguments
		err('usage: classfix file-or-directory ...\n')
		sys.exit(2)
	for arg in sys.argv[1:]:
		if path.isdir(arg):
			if recursedown(arg): bad = 1
		elif path.islink(arg):
			err(arg + ': will not process symbolic links\n')
			bad = 1
		else:
			if fix(arg): bad = 1
	sys.exit(bad)

ispython = regexp.compile('^[a-zA-Z0-9_]+\.py$').match # This is a method!

def recursedown(dirname):
	dbg('recursedown(' + `dirname` + ')\n')
	bad = 0
	try:
		names = posix.listdir(dirname)
	except posix.error, msg:
		err(dirname + ': cannot list directory: ' + `msg` + '\n')
		return 1
	for name in names:
		if name in ('.', '..'): continue
		fullname = path.join(dirname, name)
		if path.islink(fullname): pass
		elif path.isdir(fullname):
			if recursedown(fullname): bad = 1
		elif ispython(name):
			if fix(fullname): bad = 1
	return bad

# This expression doesn't catch *all* class definition headers,
# but it's darn pretty close.
classexpr = '^([ \t]*class +[a-zA-Z0-9_]+) *\( *\) *((=.*)?):'
findclass = regexp.compile(classexpr).match # This is a method!

baseexpr = '^ *(.*) *\( *\) *$'
findbase = regexp.compile(baseexpr).match # This is a method, too!

def fix(filename):
##	dbg('fix(' + `filename` + ')\n')
	try:
		f = open(filename, 'r')
	except IOError, msg:
		err(filename + ': cannot open: ' + `msg` + '\n')
		return 1
	head, tail = path.split(filename)
	tempname = path.join(head, '@' + tail)
	tf = None
	# If we find a match, we rewind the file and start over but
	# now copy everything to a temp file.
	while 1:
		line = f.readline()
		if not line: break
		res = findclass(line)
		if not res:
			if tf: tf.write(line)
			continue
		if not tf:
			try:
				tf = open(tempname, 'w')
			except IOError, msg:
				f.close()
				err(tempname+': cannot create: '+`msg`+'\n')
				return 1
			rep(filename + ':\n')
			# Rewind the input file and start all over:
			f.seek(0)
			continue
		a0, b0 = res[0] # Whole match (up to ':')
		a1, b1 = res[1] # First subexpression (up to classname)
		a2, b2 = res[2] # Second subexpression (=.*)
		head = line[:b1]
		tail = line[b0:] # Unmatched rest of line
		if a2 = b2: # No base classes -- easy case
			newline = head + ':' + tail
		else:
			# Get rid of leading '='
			basepart = line[a2+1:b2]
			# Extract list of base expressions
			bases = string.splitfields(basepart, ',')
			# Strip trailing '()' from each base expression
			for i in range(len(bases)):
				res = findbase(bases[i])
				if res:
					(x0, y0), (x1, y1) = res
					bases[i] = bases[i][x1:y1]
			# Join the bases back again and build the new line
			basepart = string.joinfields(bases, ', ')
			newline = head + '(' + basepart + '):' + tail
		rep('< ' + line)
		rep('> ' + newline)
		tf.write(newline)
	f.close()
	if not tf: return 0 # No changes

	# Finishing touch -- move files

	# First copy the file's mode to the temp file
	try:
		statbuf = posix.stat(filename)
		posix.chmod(tempname, statbuf[ST_MODE] & 07777)
	except posix.error, msg:
		err(tempname + ': warning: chmod failed (' + `msg` + ')\n')
	# Then make a backup of the original file as filename~
	try:
		posix.rename(filename, filename + '~')
	except posix.error, msg:
		err(filename + ': warning: backup failed (' + `msg` + ')\n')
	# Now move the temp file to the original file
	try:
		posix.rename(tempname, filename)
	except posix.error, msg:
		err(filename + ': rename failed (' + `msg` + ')\n')
		return 1
	# Return succes
	return 0

main()
<|endoftext|>


<commit_before>from SimpleCV.base import *

_jpegstreamers = {}
class JpegStreamHandler(SimpleHTTPRequestHandler):
  """
  The JpegStreamHandler handles requests to the threaded HTTP server.
  Once initialized, any request to this port will receive a multipart/replace
  jpeg.
  """

  def do_GET(self):
    global _jpegstreamers

    if (self.path == "/" or not self.path):

      self.send_response(200)
      self.send_header('Content-type','text/html')
      self.end_headers()
      self.wfile.write("""
<html>
<head>
<style type=text/css>
  body { background-image: url(/stream); background-repeat:no-repeat; background-position:center top; background-attachment:fixed; background-size: 100% , auto; }
</style>
</head>
<body>

</body>
</html>
      """)
      return

    elif (self.path == "/stream"):
      self.send_response(200)
      self.send_header("Connection", "close")
      self.send_header("Max-Age", "0")
      self.send_header("Expires", "0")
      self.send_header("Cache-Control", "no-cache, private")
      self.send_header("Pragma", "no-cache")
      self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=--BOUNDARYSTRING")
      self.end_headers()
      (host, port) = self.server.socket.getsockname()[:2]

      count = 0
      timeout = 0.75
      lasttimeserved = 0
      while (1):
        if (_jpegstreamers[port].refreshtime > lasttimeserved or time.time() - timeout > lasttimeserved):
          try:
            self.wfile.write("--BOUNDARYSTRING\r\n")
            self.send_header("Content-type","image/jpeg")
            self.send_header("Content-Length", str(len(_jpegstreamers[port].jpgdata.getvalue())))
            self.end_headers()
            self.wfile.write(_jpegstreamers[port].jpgdata.getvalue() + "\r\n")
            lasttimeserved = time.time()
          except socket.error, e:
            return
          except IOError, e:
            return
          count = count + 1

        time.sleep(_jpegstreamers[port].sleeptime)

class JpegTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
  allow_reuse_address = True

#factory class for jpegtcpservers
class JpegStreamer():
  """
  The JpegStreamer class allows the user to stream a jpeg encoded file
  to a HTTP port.  Any updates to the jpg file will automatically be pushed
  to the browser via multipart/replace content type.

  To initialize:
  js = JpegStreamer()

  to update:
  img.save(js)

  to open a browser and display:
  import webbrowser
  webbrowser.open(js.url)

  Note 3 optional parameters on the constructor:
  - port (default 8080) which sets the TCP port you need to connect to
  - sleep time (default 0.1) how often to update.  Above 1 second seems to cause dropped connections in Google chrome

  Once initialized, the buffer and sleeptime can be modified and will function properly -- port will not.
  """
  server = ""
  host = ""
  port = ""
  sleeptime = ""
  framebuffer = ""
  counter = 0
  refreshtime = 0

  def __init__(self, hostandport = 8080, st=0.1 ):
    global _jpegstreamers
    if (type(hostandport) == int):
      self.port = hostandport
      self.host = "localhost"
    elif (type(hostandport) == str and re.search(":", hostandport)):
      (self.host, self.port) = hostandport.split(":")
      self.port = int(self.port)
    elif (type(hostandport) == tuple):
      (self.host, self.port) = hostandport

    self.sleeptime = st
    self.server = JpegTCPServer((self.host, self.port), JpegStreamHandler)
    self.server_thread = threading.Thread(target = self.server.serve_forever)
    _jpegstreamers[self.port] = self
    self.server_thread.daemon = True
    self.server_thread.start()
    self.framebuffer = self #self referential, ugh.  but gives some bkcompat

  def url(self):
    """
  Returns the JpegStreams Webbrowser-appropriate URL, if not provided in the constructor, it defaults to "http://localhost:8080"
    """
    return "http://" + self.host + ":" + str(self.port) + "/"

  def streamUrl(self):
    """
  Returns the URL of the MJPEG stream. If host and port are not set in the constructor, defaults to "http://localhost:8080/stream/"
    """
    return self.url() + "stream/"

class VideoStream():
  """
The VideoStream lets you save video files in a number of different formats.

You can initialize it by specifying the file you want to output::

    vs = VideoStream("hello.mpg")

You can also specify a framerate, and if you want to "fill" in missed frames.
So if you want to record a realtime video you may want to do this::

    vs = VideoStream("myvideo.mpg", 25, True) #note these are default values

Where if you want to do a stop-motion animation, you would want to turn fill off::

    vs_animation = VideoStream("cartoon.mpg", 15, False)

If you select a fill, the VideoStream will do its best to stay close to "real time" by duplicating frames or dropping frames when the clock doesn't sync up
with the file writes.

You can save a frame to the video by using the Image.save() function, or by using the writeFrame function::

    my_camera.getImage().save(vs)
    vs.writeFrame(my_camera.getImage())

  """

  fps = 25
  filename = ""
  writer = ""
  fourcc = ""
  framefill = True
  videotime = 0.0
  starttime = 0.0
  framecount = 0

  def __init__(self, filename, fps = 25, framefill = True):
    (revextension, revname) = str(reverse(filename)).split(".")
    extension = str(reverse(revextension))
    self.filename = filename
    self.fps = fps
    self.framefill = framefill
    if extension == "mpg":
      self.fourcc = cv.CV_FOURCC('P', 'I', 'M', '1')
    else:
      warning.warn(extension + " is not supported for video writing on this platform, sorry");
      return False

  def initializeWriter(self, size):
    self.writer = cv.CreateVideoWriter(self.filename, self.fourcc, self.fps, size, 1)
    self.videotime = 0.0
    self.starttime = time.time()

  def writeFrame(self, img):
    if not self.writer:
      self.initializeWriter(img.size())
      self.lastframe = img

    frametime = 1.0 / float(self.fps)
    targettime = self.starttime + self.frametime * self.framecount
    realtime = time.time()
    if self.framefill:
      #see if we need to do anything to adjust to real time
      if (targettime > realtime + frametime):
        #if we're more than one frame ahead
        self.lastframe = img
        #save the lastframe, but don't write to videoout
        return
      if (targettime < realtime - frametime):
        #we're at least one frame behind
        framesbehind = int((realtime - targettime) * self.fps)
        #figure out how many frames behind we are

        lastframes = framesbehind / 2
        for i in range(0..lastframes):
          self.framecount += 1
          cv.WriteFrame(writer, self.lastframe.getBitmap())

        theseframes = framesbehind - lastframes
        for i in range(0..theseframes)
          self.framecount += 1
          cv.WriteFrame(writer, img.getBitmap())
        #split missing frames evenly between the prior and current frame
    else:
      cv.WriteFrame(writer, img.getBitmap())
      self.framecount += 1

    self.lastframe = img
<commit_msg>videostream, um, works but doesn't write anything.  Might be my opencv<commit_after>from SimpleCV.base import *

_jpegstreamers = {}
class JpegStreamHandler(SimpleHTTPRequestHandler):
  """
  The JpegStreamHandler handles requests to the threaded HTTP server.
  Once initialized, any request to this port will receive a multipart/replace
  jpeg.
  """

  def do_GET(self):
    global _jpegstreamers

    if (self.path == "/" or not self.path):

      self.send_response(200)
      self.send_header('Content-type','text/html')
      self.end_headers()
      self.wfile.write("""
<html>
<head>
<style type=text/css>
  body { background-image: url(/stream); background-repeat:no-repeat; background-position:center top; background-attachment:fixed; background-size: 100% , auto; }
</style>
</head>
<body>

</body>
</html>
      """)
      return

    elif (self.path == "/stream"):
      self.send_response(200)
      self.send_header("Connection", "close")
      self.send_header("Max-Age", "0")
      self.send_header("Expires", "0")
      self.send_header("Cache-Control", "no-cache, private")
      self.send_header("Pragma", "no-cache")
      self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=--BOUNDARYSTRING")
      self.end_headers()
      (host, port) = self.server.socket.getsockname()[:2]

      count = 0
      timeout = 0.75
      lasttimeserved = 0
      while (1):
        if (_jpegstreamers[port].refreshtime > lasttimeserved or time.time() - timeout > lasttimeserved):
          try:
            self.wfile.write("--BOUNDARYSTRING\r\n")
            self.send_header("Content-type","image/jpeg")
            self.send_header("Content-Length", str(len(_jpegstreamers[port].jpgdata.getvalue())))
            self.end_headers()
            self.wfile.write(_jpegstreamers[port].jpgdata.getvalue() + "\r\n")
            lasttimeserved = time.time()
          except socket.error, e:
            return
          except IOError, e:
            return
          count = count + 1

        time.sleep(_jpegstreamers[port].sleeptime)

class JpegTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
  allow_reuse_address = True

#factory class for jpegtcpservers
class JpegStreamer():
  """
  The JpegStreamer class allows the user to stream a jpeg encoded file
  to a HTTP port.  Any updates to the jpg file will automatically be pushed
  to the browser via multipart/replace content type.

  To initialize:
  js = JpegStreamer()

  to update:
  img.save(js)

  to open a browser and display:
  import webbrowser
  webbrowser.open(js.url)

  Note 3 optional parameters on the constructor:
  - port (default 8080) which sets the TCP port you need to connect to
  - sleep time (default 0.1) how often to update.  Above 1 second seems to cause dropped connections in Google chrome

  Once initialized, the buffer and sleeptime can be modified and will function properly -- port will not.
  """
  server = ""
  host = ""
  port = ""
  sleeptime = ""
  framebuffer = ""
  counter = 0
  refreshtime = 0

  def __init__(self, hostandport = 8080, st=0.1 ):
    global _jpegstreamers
    if (type(hostandport) == int):
      self.port = hostandport
      self.host = "localhost"
    elif (type(hostandport) == str and re.search(":", hostandport)):
      (self.host, self.port) = hostandport.split(":")
      self.port = int(self.port)
    elif (type(hostandport) == tuple):
      (self.host, self.port) = hostandport

    self.sleeptime = st
    self.server = JpegTCPServer((self.host, self.port), JpegStreamHandler)
    self.server_thread = threading.Thread(target = self.server.serve_forever)
    _jpegstreamers[self.port] = self
    self.server_thread.daemon = True
    self.server_thread.start()
    self.framebuffer = self #self referential, ugh.  but gives some bkcompat

  def url(self):
    """
  Returns the JpegStreams Webbrowser-appropriate URL, if not provided in the constructor, it defaults to "http://localhost:8080"
    """
    return "http://" + self.host + ":" + str(self.port) + "/"

  def streamUrl(self):
    """
  Returns the URL of the MJPEG stream. If host and port are not set in the constructor, defaults to "http://localhost:8080/stream/"
    """
    return self.url() + "stream/"

class VideoStream():
  """
The VideoStream lets you save video files in a number of different formats.

You can initialize it by specifying the file you want to output::

    vs = VideoStream("hello.mpg")

You can also specify a framerate, and if you want to "fill" in missed frames.
So if you want to record a realtime video you may want to do this::

    vs = VideoStream("myvideo.mpg", 25, True) #note these are default values

Where if you want to do a stop-motion animation, you would want to turn fill off::

    vs_animation = VideoStream("cartoon.mpg", 15, False)

If you select a fill, the VideoStream will do its best to stay close to "real time" by duplicating frames or dropping frames when the clock doesn't sync up
with the file writes.

You can save a frame to the video by using the Image.save() function, or by using the writeFrame function::

    my_camera.getImage().save(vs)
    vs.writeFrame(my_camera.getImage())

  """

  fps = 25
  filename = ""
  writer = ""
  fourcc = ""
  framefill = True
  videotime = 0.0
  starttime = 0.0
  framecount = 0

  def __init__(self, filename, fps = 25, framefill = True):
    (revextension, revname) = filename[::-1].split(".")
    extension = revextension[::-1]
    self.filename = filename
    self.fps = fps
    self.framefill = framefill
    if extension == "mpg":
      self.fourcc = cv.CV_FOURCC('M', 'J', 'P', 'G')
    else:
      warning.warn(extension + " is not supported for video writing on this platform, sorry");
      return False

  def initializeWriter(self, size):
    self.writer = cv.CreateVideoWriter(self.filename, self.fourcc, self.fps, size, True)
    self.videotime = 0.0
    self.starttime = time.time()

  def writeFrame(self, img):
    if not self.writer:
      self.initializeWriter(img.size())
      self.lastframe = img

    frametime = 1.0 / float(self.fps)
    targettime = self.starttime + frametime * self.framecount
    realtime = time.time()
    if self.framefill:
      #see if we need to do anything to adjust to real time
      if (targettime > realtime + frametime):
        #if we're more than one frame ahead
        #save the lastframe, but don't write to videoout
        self.lastframe = img
        return

      elif (targettime < realtime - frametime):
        #we're at least one frame behind
        framesbehind = int((realtime - targettime) * self.fps) + 1
        #figure out how many frames behind we are

        lastframes = framesbehind / 2
        for i in range(0, lastframes):
          self.framecount += 1
          cv.WriteFrame(self.writer, self.lastframe.getBitmap())

        theseframes = framesbehind - lastframes
        for i in range(0, theseframes):
          self.framecount += 1
          cv.WriteFrame(self.writer, img.getBitmap())
        #split missing frames evenly between the prior and current frame
      else: #we are on track
        self.framecount += 1
        cv.WriteFrame(self.writer, img.getBitmap())
    else:
      cv.WriteFrame(self.writer, img.getBitmap())
      self.framecount += 1

    self.lastframe = img
<|endoftext|>


<commit_before>import re
import csv
from .xlrd import xlrd_dict_reader
from .csv import csv_dict_reader
from ..models import (SpreadsheetUpload, SpreadsheetPerson,
                      SpreadsheetUploadSource, SpreadsheetPersonSource,
                      SpreadsheetLink, SpreadsheetContactDetail)

from collections import defaultdict
from contextlib import contextmanager
from pupa.scrape.helpers import Legislator, Person
from pupa.scrape.popolo import Organization

def people_to_pupa(stream, transaction):
    org = Organization(
        name=transaction.jurisdiction.name,
        classification='legislature',
    )

    for source in list(transaction.sources.all()):
        org.add_source(url=source.url, note=source.note)

    parties = defaultdict(list)

    for person in stream:
        name = person.name
        position = person.position
        district = person.district
        image = person.image

        if not name:
            raise ValueError("A name is required for each entry.")

        if position is None:
            position = "member"

        if not district:
            obj = Person(name=name)
            # OK. Let's manually create the relation without the district.
            # (If they don't have a district, it's assumed they're a member
            #  of the org, but not a "legislator". Something like Mayor, where
            #  they hold membership, but not a district).
            obj.add_membership(
                organization=org,
                label=person.position,
                role=person.position,
            )
            org.add_post(label=position, role=position)
        else:
            obj = Legislator(name=name, district=district)
            org.add_post(label=district, role=position)
            if person.party:
                obj._party = person.party
                parties[person.party].append(person.sources.all())

        if image:
            obj.image = image

        for detail in person.contacts.all():
            obj.add_contact_detail(
                type=detail.type,
                value=detail.value,
                # label=detail.label,  # Unexpected argument. Add?
                note=detail.note,
            )

        for link in person.links.all():
            obj.add_link(
                url=link.url,
                note=link.note,
            )

        for source in (list(person.sources.all())
                       + list(transaction.sources.all())):
            obj.add_source(
                url=source.url,
                note=source.note,
            )

        obj.validate()
        obj.pre_save(transaction.jurisdiction.id)
        yield obj
        for related in obj._related:
            yield related

    for party in dict(parties):
        party = Organization(classification='party', name=party)
        sources = list(parties[party]) + list(transaction.sources.all())

        for source in sources:
            party.add_source(url=source.url, note=source.note)

        party.validate()
        party.pre_save(transaction.jurisdiction.id)
        for related in party._related:
            yield related
        yield party

    org.validate()
    org.pre_save(transaction.jurisdiction.id)
    for related in org._related:
        yield related
    yield org

def import_parsed_stream(stream, user, jurisdiction, sources):
    upload = SpreadsheetUpload(user=user, jurisdiction=jurisdiction)
    upload.save()

    for source in sources:
        a = SpreadsheetUploadSource(
            upload=upload,
            url=source,
            note="Default Spreadsheet Source"
        )
        a.save()

    for person in stream:
        if not person['Name']:
            raise ValueError("Bad district or name")

        position = person.pop("Position")
        district = person.pop("District")

        if not position:
            position = "member"

        who = SpreadsheetPerson(
            name=person.pop('Name'),
            spreadsheet=upload,
            position=position,
            district=district,
        )

        if 'Photo' in person:
            who.image = person.pop("Photo")

        if 'Image' in person:
            who.image = person.pop("Image")

        if 'Party' in person:
            who.party = person.pop("Party")

        who.save()

        contact_details = {
            "Address": "address",
            "Phone": "voice",
            "Email": "email",
            "Fax": "fax",
            "Cell": "voice",
        }
        links = ["Website", "Homepage",
                 "Twitter", "Facebook",
                 "Blog", "Webform"]
        sources = ["Source"]

        for key, value in person.items():
            if not value:
                # 'errything is optional.
                continue

            root = key
            label = None

            if "(" in key:
                root, label = key.rsplit("(", 1)
                root = root.strip()
                label = label.rstrip(")").strip()

            if root in sources:
                a = SpreadsheetPersonSource(
                    person=who,
                    url=value,
                    note=key
                )
                a.save()
                continue

            # If we've got a link.
            if root in links:
                a = SpreadsheetLink(
                    person=who,
                    url=value,
                    note=key,
                )
                a.save()
                continue

            # If we've got a contact detail.
            if root in contact_details:
                type_ = contact_details[root]
                a = SpreadsheetContactDetail(
                    person=who,
                    type=type_,
                    value=value,
                    label=label or "",
                    note=key,
                )
                a.save()
                continue

            raise ValueError("Unknown spreadhseet key: %s" % (key))

    return upload

def import_stream(stream, extension, user, jurisdiction, sources):
    reader = {"csv": csv_dict_reader,
              "xlsx": xlrd_dict_reader,
              "xls": xlrd_dict_reader}[extension]

    return import_parsed_stream(reader(stream), user, jurisdiction, sources)

@contextmanager
def import_file_stream(fpath, user, jurisdiction, sources):
    _, xtn = fpath.rsplit(".", 1)

    with open(fpath, 'br') as fd:
        yield import_stream(fd, xtn, user, jurisdiction, sources)
<commit_msg>short-circut if name is vacant.<commit_after>import re
import csv
from .xlrd import xlrd_dict_reader
from .csv import csv_dict_reader
from ..models import (SpreadsheetUpload, SpreadsheetPerson,
                      SpreadsheetUploadSource, SpreadsheetPersonSource,
                      SpreadsheetLink, SpreadsheetContactDetail)

from collections import defaultdict
from contextlib import contextmanager
from pupa.scrape.helpers import Legislator, Person
from pupa.scrape.popolo import Organization

def people_to_pupa(stream, transaction):
    org = Organization(
        name=transaction.jurisdiction.name,
        classification='legislature',
    )

    for source in list(transaction.sources.all()):
        org.add_source(url=source.url, note=source.note)

    parties = defaultdict(list)

    for person in stream:
        name = person.name
        position = person.position
        district = person.district
        image = person.image

        if not name:
            raise ValueError("A name is required for each entry.")

        if name.lower() == "vacant":
            # The following is so that we can create a post without a person
            # attached to it, for vacant seats. Since all that we do
            # below is create the Person, we can get away with just creating
            # the post, without actually filling out the person.
            org.add_post(label=position, role=position)
            continue

        if position is None:
            position = "member"

        if not district:
            obj = Person(name=name)
            # OK. Let's manually create the relation without the district.
            # (If they don't have a district, it's assumed they're a member
            #  of the org, but not a "legislator". Something like Mayor, where
            #  they hold membership, but not a district).
            obj.add_membership(
                organization=org,
                label=person.position,
                role=person.position,
            )
            org.add_post(label=position, role=position)
        else:
            obj = Legislator(name=name, district=district)
            org.add_post(label=district, role=position)
            if person.party:
                obj._party = person.party
                parties[person.party].append(person.sources.all())

        if image:
            obj.image = image

        for detail in person.contacts.all():
            obj.add_contact_detail(
                type=detail.type,
                value=detail.value,
                # label=detail.label,  # Unexpected argument. Add?
                note=detail.note,
            )

        for link in person.links.all():
            obj.add_link(
                url=link.url,
                note=link.note,
            )

        for source in (list(person.sources.all())
                       + list(transaction.sources.all())):
            obj.add_source(
                url=source.url,
                note=source.note,
            )

        obj.validate()
        obj.pre_save(transaction.jurisdiction.id)
        yield obj
        for related in obj._related:
            yield related

    for party in dict(parties):
        party = Organization(classification='party', name=party)
        sources = list(parties[party]) + list(transaction.sources.all())

        for source in sources:
            party.add_source(url=source.url, note=source.note)

        party.validate()
        party.pre_save(transaction.jurisdiction.id)
        for related in party._related:
            yield related
        yield party

    org.validate()
    org.pre_save(transaction.jurisdiction.id)
    for related in org._related:
        yield related
    yield org

def import_parsed_stream(stream, user, jurisdiction, sources):
    upload = SpreadsheetUpload(user=user, jurisdiction=jurisdiction)
    upload.save()

    for source in sources:
        a = SpreadsheetUploadSource(
            upload=upload,
            url=source,
            note="Default Spreadsheet Source"
        )
        a.save()

    for person in stream:
        if not person['Name']:
            raise ValueError("Bad district or name")

        position = person.pop("Position")
        district = person.pop("District")

        if not position:
            position = "member"

        who = SpreadsheetPerson(
            name=person.pop('Name'),
            spreadsheet=upload,
            position=position,
            district=district,
        )

        if 'Photo' in person:
            who.image = person.pop("Photo")

        if 'Image' in person:
            who.image = person.pop("Image")

        if 'Party' in person:
            who.party = person.pop("Party")

        who.save()

        contact_details = {
            "Address": "address",
            "Phone": "voice",
            "Email": "email",
            "Fax": "fax",
            "Cell": "voice",
        }
        links = ["Website", "Homepage",
                 "Twitter", "Facebook",
                 "Blog", "Webform"]
        sources = ["Source"]

        for key, value in person.items():
            if not value:
                # 'errything is optional.
                continue

            root = key
            label = None

            if "(" in key:
                root, label = key.rsplit("(", 1)
                root = root.strip()
                label = label.rstrip(")").strip()

            if root in sources:
                a = SpreadsheetPersonSource(
                    person=who,
                    url=value,
                    note=key
                )
                a.save()
                continue

            # If we've got a link.
            if root in links:
                a = SpreadsheetLink(
                    person=who,
                    url=value,
                    note=key,
                )
                a.save()
                continue

            # If we've got a contact detail.
            if root in contact_details:
                type_ = contact_details[root]
                a = SpreadsheetContactDetail(
                    person=who,
                    type=type_,
                    value=value,
                    label=label or "",
                    note=key,
                )
                a.save()
                continue

            raise ValueError("Unknown spreadhseet key: %s" % (key))

    return upload

def import_stream(stream, extension, user, jurisdiction, sources):
    reader = {"csv": csv_dict_reader,
              "xlsx": xlrd_dict_reader,
              "xls": xlrd_dict_reader}[extension]

    return import_parsed_stream(reader(stream), user, jurisdiction, sources)

@contextmanager
def import_file_stream(fpath, user, jurisdiction, sources):
    _, xtn = fpath.rsplit(".", 1)

    with open(fpath, 'br') as fd:
        yield import_stream(fd, xtn, user, jurisdiction, sources)
<|endoftext|>


<commit_before>
'''
MAP Client Plugin Step
'''
import json

from mapclient.mountpoints.workflowstep import WorkflowStepMountPoint
from mapclientplugins.transformpointcloudstep.configuredialog import ConfigureDialog

class TransformPointCloudStep(WorkflowStepMountPoint):
    '''
    Skeleton step which is intended to be a helpful starting point
    for new steps.
    '''

    def __init__(self, location):
        super(TransformPointCloudStep, self).__init__('Transform Point Cloud', location)
        self._configured = False # A step cannot be executed until it has been configured.
        self._category = 'Transform'
        # Add any other initialisation code here:
        # Ports:
        self.addPort(('http://physiomeproject.org/workflow/1.0/rdf-schema#port',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#uses',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud'))
        self.addPort(('http://physiomeproject.org/workflow/1.0/rdf-schema#port',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#uses',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#affinetransform'))
        self.addPort(('http://physiomeproject.org/workflow/1.0/rdf-schema#port',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#provides',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud'))
        # Port data:
        self._portData0 = None # http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud
        self._portData1 = None # http://physiomeproject.org/workflow/1.0/rdf-schema#affinetransform
        self._portData2 = None # http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud
        # Config:
        self._config = {}
        self._config['identifier'] = ''

    def execute(self):
        '''
        Add your code here that will kick off the execution of the step.
        Make sure you call the _doneExecution() method when finished.  This method
        may be connected up to a button in a widget for example.
        '''
        # Put your execute step code here before calling the '_doneExecution' method.
        self._portData2 = self._portData0
        self._doneExecution()

    def setPortData(self, index, dataIn):
        '''
        Add your code here that will set the appropriate objects for this step.
        The index is the index of the port in the port list.  If there is only one
        uses port for this step then the index can be ignored.
        '''
        if index == 0:
            self._portData0 = dataIn # http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud
        elif index == 1:
            self._portData1 = dataIn # http://physiomeproject.org/workflow/1.0/rdf-schema#affinetransform

    def getPortData(self, index):
        '''
        Add your code here that will return the appropriate objects for this step.
        The index is the index of the port in the port list.  If there is only one
        provides port for this step then the index can be ignored.
        '''
        return self._portData2 # http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud

    def configure(self):
        '''
        This function will be called when the configure icon on the step is
        clicked.  It is appropriate to display a configuration dialog at this
        time.  If the conditions for the configuration of this step are complete
        then set:
            self._configured = True
        '''
        dlg = ConfigureDialog()
        dlg.identifierOccursCount = self._identifierOccursCount
        dlg.setConfig(self._config)
        dlg.validate()
        dlg.setModal(True)

        if dlg.exec_():
            self._config = dlg.getConfig()

        self._configured = dlg.validate()
        self._configuredObserver()

    def getIdentifier(self):
        '''
        The identifier is a string that must be unique within a workflow.
        '''
        return self._config['identifier']

    def setIdentifier(self, identifier):
        '''
        The framework will set the identifier for this step when it is loaded.
        '''
        self._config['identifier'] = identifier

    def serialize(self):
        '''
        Add code to serialize this step to string.  This method should
        implement the opposite of 'deserialize'.
        '''
        return json.dumps(self._config, default=lambda o: o.__dict__, sort_keys=True, indent=4)

    def deserialize(self, string):
        '''
        Add code to deserialize this step from string.  This method should
        implement the opposite of 'serialize'.
        '''
        self._config.update(json.loads(string))

        d = ConfigureDialog()
        d.identifierOccursCount = self._identifierOccursCount
        d.setConfig(self._config)
        self._configured = d.validate()

<commit_msg>Updated ConfigureDialog() arguments.<commit_after>
'''
MAP Client Plugin Step
'''
import json

from mapclient.mountpoints.workflowstep import WorkflowStepMountPoint
from mapclientplugins.transformpointcloudstep.configuredialog import ConfigureDialog

class TransformPointCloudStep(WorkflowStepMountPoint):
    '''
    Skeleton step which is intended to be a helpful starting point
    for new steps.
    '''

    def __init__(self, location):
        super(TransformPointCloudStep, self).__init__('Transform Point Cloud', location)
        self._configured = False # A step cannot be executed until it has been configured.
        self._category = 'Transform'
        # Add any other initialisation code here:
        # Ports:
        self.addPort(('http://physiomeproject.org/workflow/1.0/rdf-schema#port',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#uses',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud'))
        self.addPort(('http://physiomeproject.org/workflow/1.0/rdf-schema#port',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#uses',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#affinetransform'))
        self.addPort(('http://physiomeproject.org/workflow/1.0/rdf-schema#port',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#provides',
                      'http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud'))
        # Port data:
        self._portData0 = None # http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud
        self._portData1 = None # http://physiomeproject.org/workflow/1.0/rdf-schema#affinetransform
        self._portData2 = None # http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud
        # Config:
        self._config = {}
        self._config['identifier'] = ''

    def execute(self):
        '''
        Add your code here that will kick off the execution of the step.
        Make sure you call the _doneExecution() method when finished.  This method
        may be connected up to a button in a widget for example.
        '''
        # Put your execute step code here before calling the '_doneExecution' method.
        self._portData2 = self._portData0
        self._doneExecution()

    def setPortData(self, index, dataIn):
        '''
        Add your code here that will set the appropriate objects for this step.
        The index is the index of the port in the port list.  If there is only one
        uses port for this step then the index can be ignored.
        '''
        if index == 0:
            self._portData0 = dataIn # http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud
        elif index == 1:
            self._portData1 = dataIn # http://physiomeproject.org/workflow/1.0/rdf-schema#affinetransform

    def getPortData(self, index):
        '''
        Add your code here that will return the appropriate objects for this step.
        The index is the index of the port in the port list.  If there is only one
        provides port for this step then the index can be ignored.
        '''
        return self._portData2 # http://physiomeproject.org/workflow/1.0/rdf-schema#pointcloud

    def configure(self):
        '''
        This function will be called when the configure icon on the step is
        clicked.  It is appropriate to display a configuration dialog at this
        time.  If the conditions for the configuration of this step are complete
        then set:
            self._configured = True
        '''
        dlg = ConfigureDialog(self._main_window)
        dlg.identifierOccursCount = self._identifierOccursCount
        dlg.setConfig(self._config)
        dlg.validate()
        dlg.setModal(True)

        if dlg.exec_():
            self._config = dlg.getConfig()

        self._configured = dlg.validate()
        self._configuredObserver()

    def getIdentifier(self):
        '''
        The identifier is a string that must be unique within a workflow.
        '''
        return self._config['identifier']

    def setIdentifier(self, identifier):
        '''
        The framework will set the identifier for this step when it is loaded.
        '''
        self._config['identifier'] = identifier

    def serialize(self):
        '''
        Add code to serialize this step to string.  This method should
        implement the opposite of 'deserialize'.
        '''
        return json.dumps(self._config, default=lambda o: o.__dict__, sort_keys=True, indent=4)

    def deserialize(self, string):
        '''
        Add code to deserialize this step from string.  This method should
        implement the opposite of 'serialize'.
        '''
        self._config.update(json.loads(string))

        d = ConfigureDialog()
        d.identifierOccursCount = self._identifierOccursCount
        d.setConfig(self._config)
        self._configured = d.validate()

<|endoftext|>


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

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QUrl

from MainWindow_raspi import Ui_MainWindow
from PyQt5.QtGui import QDesktopServices
import sys
import datetime
import os as os
import logging
import time

import soco

class QPlainTextEditLogger(logging.Handler):
    """create a logger class that emits to the TE_Debug field in Gui

    :param ui:              instance to the ui forma
    :type ui:               class 'MainForm.Ui_MainWindow'
    """
    __criticalHtml = ""
    __errorHtml = ""
    __warningHtml = ""
    __infoHtml = ""
    __dbgHtml = ""
    __endHtml = "
"
    __htmlMsg = ""

    def __init__(self, ui):
        super().__init__()
        self.ui = ui

    def emit(self, record):
        msg = self.format(record)
        print(msg)
        if ": CRITICAL" in msg:
            self.__htmlMsg = self.__criticalHtml + msg
        elif ": ERROR" in msg:
            self.__htmlMsg = self.__errorHtml + msg
        elif ": WARNING" in msg:
            self.__htmlMsg = self.__warningHtml + msg
        elif ": INFO" in msg:
            self.__htmlMsg = self.__infoHtml + msg
        elif ": DEBUG" in msg:
            self.__htmlMsg = self.__dbgHtml + msg
        self.__htmlMsg = self.__htmlMsg + self.__endHtml
        print(self.__htmlMsg)
        self.ui.TE_Debug.insertHtml(self.__htmlMsg)
        self.ui.TE_Debug.ensureCursorVisible()

def createLogger(logFile):
    """ create a logger facility that logs to a file and to the stdout
    :param logFile:         File name of the log
    :type logFile:          class 'str'

    :rtype:                 class 'logging.Logger'
    """
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s - %(funcName)s - %(levelname)s - %(lineno)d - %(message)s',
                        datefmt='%m-%d %H:%M',
                        filename=logFile,
                        filemode='w')
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    # set a format which is simpler for console use
    formatter = logging.Formatter('%(funcName)-12s: %(levelname)-8s %(message)s')
    # tell the handler to use this format
    console.setFormatter(formatter)
    # add the handler to the root logger
    logging.getLogger('').addHandler(console)

    logger = logging.getLogger(__name__)
    logger.info('---end of logger create function---')
    return logger

class SonosInterface():
  myZone=0
  activeSpeaker=0
  def __init__(self, ui):
    SonosInterface.myZone = list(soco.discover())
    SonosInterface.activeSpeaker = 0
  def displayMyZone(self):
    print(self.myZone[self.activeSpeaker])
  def selectLineIn(self):
    self.myZone[self.activeSpeaker].switchto_line_in()
  def selectTv(self):
    self.myZone[self.activeSpeaker].switch_to_tv()
  def playMusic(self):
    self.myZone[self.activeSpeaker].play()
  def stopMusic(self):
    self.myZone[self.activeSpeaker].stop()
  def muteMusic(self):
    self.myZone[self.activeSpeaker].mute(True)
  def pauseMusic(self):
    self.myZone[self.activeSpeaker].pause()
  def skipMusic(self):
    self.myZone[self.activeSpeaker].next()
  def previousMusic(self):
    self.myZone[self.activeSpeaker].previous()
  def setVolume(self, vol):
    self.myZone[self.activeSpeaker].volume=vol
  def getVolume(self):
    return self.myZone[self.activeSpeaker].volume
  def volumeUp(self):
    vol=self.myZone[self.activeSpeaker].volume
    self.myZone[self.activeSpeaker].volume=vol+5
  def volumeDown(self):
    vol=self.myZone[self.activeSpeaker].volume
    vol=min(vol, 0)
    self.myZone[self.activeSpeaker].volume=vol-5
  def get_current_track_info(self):
    info=self.myZone[self.activeSpeaker].get_current_track_info()
    ui.LB_currentlyPlaying.setText(str(info))
  def printMyZone(self):
    for speaker in speakers:
      print(speaker.player_name, speaker.ip_address)
  def selectWohnzimmer(self):
    for speaker in speakers:
      if speaker.player_name=="Wohnzimmer":
        self.activeSpeaker = 0

class openBrowserWidget():
    def __init__(self, ui):
        Ui=ui
    def openHb(self):
        ui.ST_workerStack.setCurrentIndex(6)
        timeDate=self.getTimeDate()
        myUrl=QUrl("https://www.sbb.ch/de/kaufen/pages/fahrplan/fahrplan.xhtml?von=Bern+Breitfeld&nach=Bern&datum=" + timeDate[0] + "&zeit=" + timeDate[1] + "&suche=true")
        logging.info(myUrl)
        ui.WV_sbbHb.load(myUrl)
    def openBreitsch(self):
        ui.ST_workerStack.setCurrentIndex(8)
        timeDate=self.getTimeDate()
        myUrl=QUrl("https://www.sbb.ch/de/kaufen/pages/fahrplan/fahrplan.xhtml?von=Bern+Wylerbad&nach=Bern+Breitenrainplatz&datum=" + timeDate[0] + "&zeit=" + timeDate[1] + "&suche=true")
        logging.info(myUrl)
        ui.WV_sbbBreitsch.load(myUrl)
    def openWankdorf(self):
        ui.ST_workerStack.setCurrentIndex(7)
        timeDate=self.getTimeDate()
        myUrl=QUrl("https://www.sbb.ch/de/kaufen/pages/fahrplan/fahrplan.xhtml?von=Bern+Breitfeld&nach=Bern+Wankdorf&datum=" + timeDate[0] + "&zeit=" + timeDate[1] + "&suche=true")
        logging.info(myUrl)
        ui.WV_sbbWankdorf.load(myUrl)
    def openMeteo(self):
        myUrl=QUrl("https://m.srf.ch/meteo")
        ui.WV_srfMeteo.load(myUrl)
    def getTimeDate(self):
        myTime = time.gmtime()
        myYear=myTime.tm_year
        myMonth=myTime.tm_mon
        myDay=myTime.tm_mday
        myHour=myTime.tm_hour
        myMin=myTime.tm_min
        myDate=(str(myDay)+"."+str(myMonth)+"."+str(myYear))
        myCurTime=(str(myHour)+":"+str(myMin))
        return [myDate, myCurTime]

if __name__ == '__main__':
    #logger = createLogger("myFirstTask.log")
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    myMusicPlayer=SonosInterface(ui)

    openBrowser=openBrowserWidget(ui)

    logTextBox = QPlainTextEditLogger(ui)
    logTextBox.setFormatter(logging.Formatter('%(funcName)-12s: %(levelname)-8s %(message)s'))
    logging.getLogger().addHandler(logTextBox)
    # You can control the logging level
    logging.getLogger().setLevel(logging.DEBUG)

    logging.info('Here we are')
    logging.error('Oops')

    ui.ST_workerStack.setCurrentIndex(0)
    ui.BT_openHomeScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(0))
    filepath=os.path.abspath(os.path.join(os.path.dirname(__file__), "index.html"))
    myUrl=QUrl.fromLocalFile(filepath)
    ui.BT_openHomeScreen.clicked.connect(lambda: ui.WV_clock.load(myUrl))
    ui.BT_openSonosScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(1))
    ui.BT_openWeatherScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(2))
    ui.BT_openLogScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(3))
    ui.BT_openMeteoScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(4))
    ui.BT_openMeteoScreen.clicked.connect(lambda: openBrowser.openMeteo())
    ui.BT_openSbbScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(5))

    ui.BT_hb.clicked.connect(lambda: openBrowser.openHb())
    ui.BT_breitsch.clicked.connect(lambda: openBrowser.openBreitsch())
    ui.BT_wankdorf.clicked.connect(lambda: openBrowser.openWankdorf())

    ui.BT_sonosPlay.clicked.connect(lambda: myMusicPlayer.playMusic())
    ui.BT_stop.clicked.connect(lambda: myMusicPlayer.stopMusic())
    ui.BT_pause.clicked.connect(lambda: myMusicPlayer.pauseMusic())
    ui.BT_skip.clicked.connect(lambda: myMusicPlayer.skipMusic())
    ui.BT_previous.clicked.connect(lambda: myMusicPlayer.previousMusic())
    ui.SL_volume.valueChanged.connect(lambda: myMusicPlayer.setVolume(ui.SL_volume.value()))

    file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "index.html"))

    '''the clock'''
    local_url = QUrl.fromLocalFile(file_path)
    #ui.WD_clock.load(local_url)

    myTimer =QtCore.QTimer()
    myTimer.timeout.connect(myMusicPlayer.get_current_track_info)
    myTimer.start(6000)

    volume=50
    volume = myMusicPlayer.getVolume()
    ui.SL_volume.setValue(volume)

    MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)

    MainWindow.show()
    sys.exit(app.exec_())
<commit_msg>initial screen<commit_after># -*- coding: utf-8 -*-

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QUrl

from MainWindow_raspi import Ui_MainWindow
from PyQt5.QtGui import QDesktopServices
import sys
import datetime
import os as os
import logging
import time

import soco

class QPlainTextEditLogger(logging.Handler):
    """create a logger class that emits to the TE_Debug field in Gui

    :param ui:              instance to the ui forma
    :type ui:               class 'MainForm.Ui_MainWindow'
    """
    __criticalHtml = ""
    __errorHtml = ""
    __warningHtml = ""
    __infoHtml = ""
    __dbgHtml = ""
    __endHtml = "
"
    __htmlMsg = ""

    def __init__(self, ui):
        super().__init__()
        self.ui = ui

    def emit(self, record):
        msg = self.format(record)
        print(msg)
        if ": CRITICAL" in msg:
            self.__htmlMsg = self.__criticalHtml + msg
        elif ": ERROR" in msg:
            self.__htmlMsg = self.__errorHtml + msg
        elif ": WARNING" in msg:
            self.__htmlMsg = self.__warningHtml + msg
        elif ": INFO" in msg:
            self.__htmlMsg = self.__infoHtml + msg
        elif ": DEBUG" in msg:
            self.__htmlMsg = self.__dbgHtml + msg
        self.__htmlMsg = self.__htmlMsg + self.__endHtml
        print(self.__htmlMsg)
        self.ui.TE_Debug.insertHtml(self.__htmlMsg)
        self.ui.TE_Debug.ensureCursorVisible()

def createLogger(logFile):
    """ create a logger facility that logs to a file and to the stdout
    :param logFile:         File name of the log
    :type logFile:          class 'str'

    :rtype:                 class 'logging.Logger'
    """
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s - %(funcName)s - %(levelname)s - %(lineno)d - %(message)s',
                        datefmt='%m-%d %H:%M',
                        filename=logFile,
                        filemode='w')
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    # set a format which is simpler for console use
    formatter = logging.Formatter('%(funcName)-12s: %(levelname)-8s %(message)s')
    # tell the handler to use this format
    console.setFormatter(formatter)
    # add the handler to the root logger
    logging.getLogger('').addHandler(console)

    logger = logging.getLogger(__name__)
    logger.info('---end of logger create function---')
    return logger

class SonosInterface():
  myZone=0
  activeSpeaker=0
  def __init__(self, ui):
    SonosInterface.myZone = list(soco.discover())
    SonosInterface.activeSpeaker = 0
  def displayMyZone(self):
    print(self.myZone[self.activeSpeaker])
  def selectLineIn(self):
    self.myZone[self.activeSpeaker].switchto_line_in()
  def selectTv(self):
    self.myZone[self.activeSpeaker].switch_to_tv()
  def playMusic(self):
    self.myZone[self.activeSpeaker].play()
  def stopMusic(self):
    self.myZone[self.activeSpeaker].stop()
  def muteMusic(self):
    self.myZone[self.activeSpeaker].mute(True)
  def pauseMusic(self):
    self.myZone[self.activeSpeaker].pause()
  def skipMusic(self):
    self.myZone[self.activeSpeaker].next()
  def previousMusic(self):
    self.myZone[self.activeSpeaker].previous()
  def setVolume(self, vol):
    self.myZone[self.activeSpeaker].volume=vol
  def getVolume(self):
    return self.myZone[self.activeSpeaker].volume
  def volumeUp(self):
    vol=self.myZone[self.activeSpeaker].volume
    self.myZone[self.activeSpeaker].volume=vol+5
  def volumeDown(self):
    vol=self.myZone[self.activeSpeaker].volume
    vol=min(vol, 0)
    self.myZone[self.activeSpeaker].volume=vol-5
  def get_current_track_info(self):
    info=self.myZone[self.activeSpeaker].get_current_track_info()
    ui.LB_currentlyPlaying.setText(str(info))
  def printMyZone(self):
    for speaker in speakers:
      print(speaker.player_name, speaker.ip_address)
  def selectWohnzimmer(self):
    for speaker in speakers:
      if speaker.player_name=="Wohnzimmer":
        self.activeSpeaker = 0

class openBrowserWidget():
    def __init__(self, ui):
        Ui=ui
    def openHb(self):
        ui.ST_workerStack.setCurrentIndex(6)
        timeDate=self.getTimeDate()
        myUrl=QUrl("https://www.sbb.ch/de/kaufen/pages/fahrplan/fahrplan.xhtml?von=Bern+Breitfeld&nach=Bern&datum=" + timeDate[0] + "&zeit=" + timeDate[1] + "&suche=true")
        logging.info(myUrl)
        ui.WV_sbbHb.load(myUrl)
    def openBreitsch(self):
        ui.ST_workerStack.setCurrentIndex(8)
        timeDate=self.getTimeDate()
        myUrl=QUrl("https://www.sbb.ch/de/kaufen/pages/fahrplan/fahrplan.xhtml?von=Bern+Wylerbad&nach=Bern+Breitenrainplatz&datum=" + timeDate[0] + "&zeit=" + timeDate[1] + "&suche=true")
        logging.info(myUrl)
        ui.WV_sbbBreitsch.load(myUrl)
    def openWankdorf(self):
        ui.ST_workerStack.setCurrentIndex(7)
        timeDate=self.getTimeDate()
        myUrl=QUrl("https://www.sbb.ch/de/kaufen/pages/fahrplan/fahrplan.xhtml?von=Bern+Breitfeld&nach=Bern+Wankdorf&datum=" + timeDate[0] + "&zeit=" + timeDate[1] + "&suche=true")
        logging.info(myUrl)
        ui.WV_sbbWankdorf.load(myUrl)
    def openMeteo(self):
        myUrl=QUrl("https://m.srf.ch/meteo")
        ui.WV_srfMeteo.load(myUrl)
    def getTimeDate(self):
        myTime = time.gmtime()
        myYear=myTime.tm_year
        myMonth=myTime.tm_mon
        myDay=myTime.tm_mday
        myHour=myTime.tm_hour
        myMin=myTime.tm_min
        myDate=(str(myDay)+"."+str(myMonth)+"."+str(myYear))
        myCurTime=(str(myHour)+":"+str(myMin))
        return [myDate, myCurTime]

if __name__ == '__main__':
    #logger = createLogger("myFirstTask.log")
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    filepath=os.path.abspath(os.path.join(os.path.dirname(__file__), "index.html"))
    myUrl=QUrl.fromLocalFile(filepath)
    ui.WV_clock.load(myUrl)

    myMusicPlayer=SonosInterface(ui)

    openBrowser=openBrowserWidget(ui)

    logTextBox = QPlainTextEditLogger(ui)
    logTextBox.setFormatter(logging.Formatter('%(funcName)-12s: %(levelname)-8s %(message)s'))
    logging.getLogger().addHandler(logTextBox)
    # You can control the logging level
    logging.getLogger().setLevel(logging.DEBUG)

    logging.info('Here we are')
    logging.error('Oops')

    ui.ST_workerStack.setCurrentIndex(0)
    ui.BT_openHomeScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(0))
    filepath=os.path.abspath(os.path.join(os.path.dirname(__file__), "index.html"))
    myUrl=QUrl.fromLocalFile(filepath)
    ui.BT_openHomeScreen.clicked.connect(lambda: ui.WV_clock.load(myUrl))
    ui.BT_openSonosScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(1))
    ui.BT_openWeatherScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(2))
    ui.BT_openLogScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(3))
    ui.BT_openMeteoScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(4))
    ui.BT_openMeteoScreen.clicked.connect(lambda: openBrowser.openMeteo())
    ui.BT_openSbbScreen.clicked.connect(lambda: ui.ST_workerStack.setCurrentIndex(5))

    ui.BT_hb.clicked.connect(lambda: openBrowser.openHb())
    ui.BT_breitsch.clicked.connect(lambda: openBrowser.openBreitsch())
    ui.BT_wankdorf.clicked.connect(lambda: openBrowser.openWankdorf())

    ui.BT_sonosPlay.clicked.connect(lambda: myMusicPlayer.playMusic())
    ui.BT_stop.clicked.connect(lambda: myMusicPlayer.stopMusic())
    ui.BT_pause.clicked.connect(lambda: myMusicPlayer.pauseMusic())
    ui.BT_skip.clicked.connect(lambda: myMusicPlayer.skipMusic())
    ui.BT_previous.clicked.connect(lambda: myMusicPlayer.previousMusic())
    ui.SL_volume.valueChanged.connect(lambda: myMusicPlayer.setVolume(ui.SL_volume.value()))

    file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "index.html"))

    '''the clock'''
    local_url = QUrl.fromLocalFile(file_path)
    #ui.WD_clock.load(local_url)

    myTimer =QtCore.QTimer()
    myTimer.timeout.connect(myMusicPlayer.get_current_track_info)
    myTimer.start(6000)

    volume=50
    volume = myMusicPlayer.getVolume()
    ui.SL_volume.setValue(volume)

    MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)

    MainWindow.show()
    sys.exit(app.exec_())
<|endoftext|>


<commit_before># coding: utf-8

from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

import cv2

from .config import get_config
from .imgutils import (crop, _frame_repr, pixel_bounding_box, _validate_region)
from .logging import ddebug, ImageLogger
from .types import Region

class FrameDiffer(object):
    """Interface for different algorithms for diffing frames in a sequence.

    Say you have a sequence of frames A, B, C. Typically you will compare frame
    A against B, and then frame B against C. This is a class (not a function)
    so that you can remember work you've done on frame B, so that you don't
    repeat that work when you need to compare against frame C.
    """

    def __init__(self, initial_frame, region=Region.ALL, mask=None,
                 min_size=None):
        self.prev_frame = initial_frame
        self.region = _validate_region(self.prev_frame, region)
        self.mask = mask
        self.min_size = min_size
        if (self.mask is not None and
                self.mask.shape[:2] != (self.region.height, self.region.width)):
            raise ValueError(
                "The dimensions of the mask %s don't match the %s <%ix%i>"
                % (_frame_repr(self.mask),
                   "frame" if region == Region.ALL else "region",
                   self.region.width, self.region.height))

    def diff(self, frame):
        raise NotImplementedError(
            "%s.diff is not implemented" % self.__class__.__name__)

class MotionDiff(FrameDiffer):
    """The `wait_for_motion` diffing algorithm."""

    def __init__(self, initial_frame, region=Region.ALL, mask=None,
                 min_size=None, noise_threshold=None):
        super(MotionDiff, self).__init__(initial_frame, region, mask, min_size)
        if noise_threshold is None:
            noise_threshold = get_config(
                'motion', 'noise_threshold', type_=float)
        self.noise_threshold = noise_threshold
        self.prev_frame_gray = self.gray(initial_frame)

    def gray(self, frame):
        return cv2.cvtColor(crop(frame, self.region), cv2.COLOR_BGR2GRAY)

    def diff(self, frame):
        frame_gray = self.gray(frame)

        imglog = ImageLogger("MotionDiff", region=self.region,
                             min_size=self.min_size,
                             noise_threshold=self.noise_threshold)
        imglog.imwrite("source", frame)
        imglog.imwrite("gray", frame_gray)
        imglog.imwrite("previous_frame_gray", self.prev_frame_gray)

        absdiff = cv2.absdiff(self.prev_frame_gray, frame_gray)
        imglog.imwrite("absdiff", absdiff)

        if self.mask is not None:
            absdiff = cv2.bitwise_and(absdiff, self.mask)
            imglog.imwrite("mask", self.mask)
            imglog.imwrite("absdiff_masked", absdiff)

        _, thresholded = cv2.threshold(
            absdiff, int((1 - self.noise_threshold) * 255), 255,
            cv2.THRESH_BINARY)
        eroded = cv2.erode(
            thresholded,
            cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
        imglog.imwrite("absdiff_threshold", thresholded)
        imglog.imwrite("absdiff_threshold_erode", eroded)

        out_region = pixel_bounding_box(eroded)
        if out_region:
            # Undo cv2.erode above:
            out_region = out_region.extend(x=-1, y=-1)
            # Undo crop:
            out_region = out_region.translate(self.region)

        motion = bool(out_region and (
            self.min_size is None or
            (out_region.width >= self.min_size[0] and
             out_region.height >= self.min_size[1])))

        if motion:
            # Only update the comparison frame if it's different to the previous
            # one.  This makes `detect_motion` more sensitive to slow motion
            # because the differences between frames 1 and 2 might be small and
            # the differences between frames 2 and 3 might be small but we'd see
            # the difference by looking between 1 and 3.
            self.prev_frame = frame
            self.prev_frame_gray = frame_gray

        result = MotionResult(getattr(frame, "time", None), motion,
                              out_region, frame)
        ddebug(str(result))
        imglog.html(MOTION_HTML, result=result)
        return result

class MotionResult(object):
    """The result from `detect_motion` and `wait_for_motion`.

    :ivar float time: The time at which the video-frame was captured, in
        seconds since 1970-01-01T00:00Z. This timestamp can be compared with
        system time (``time.time()``).

    :ivar bool motion: True if motion was found. This is the same as evaluating
        ``MotionResult`` as a bool. That is, ``if result:`` will behave the
        same as ``if result.motion:``.

    :ivar Region region: Bounding box where the motion was found, or ``None``
        if no motion was found.

    :ivar Frame frame: The video frame in which motion was (or wasn't) found.
    """
    _fields = ("time", "motion", "region", "frame")

    def __init__(self, time, motion, region, frame):
        self.time = time
        self.motion = motion
        self.region = region
        self.frame = frame

    def __bool__(self):
        return self.motion

    def __nonzero__(self):
        return self.__bool__()

    def __repr__(self):
        return (
            "MotionResult(time=%s, motion=%r, region=%r, frame=%s)" % (
                "None" if self.time is None else "%.3f" % self.time,
                self.motion, self.region, _frame_repr(self.frame)))

MOTION_HTML = u"""\

      detect_motion:
      {{ "Found" if result.motion else "Didn't find" }} motion

    {{ annotated_image(result) }}

Result:

{{ result | escape }}

    {% if result.region and not result.motion %}

Found motion {{ result.region | escape }} smaller than
    min_size {{ min_size | escape }}.

    {% endif %}

ROI Gray:

Previous frame ROI Gray:

Absolute difference:

    {% if "mask" in images %}

Mask:

Absolute difference – masked:

    {% endif %}

Threshold (noise_threshold={{noise_threshold}}):

Eroded:

"""
<commit_msg>MotionDiff: Use "open" instead of "erode"<commit_after># coding: utf-8

from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

import cv2

from .config import get_config
from .imgutils import (crop, _frame_repr, pixel_bounding_box, _validate_region)
from .logging import ddebug, ImageLogger
from .types import Region

class FrameDiffer(object):
    """Interface for different algorithms for diffing frames in a sequence.

    Say you have a sequence of frames A, B, C. Typically you will compare frame
    A against B, and then frame B against C. This is a class (not a function)
    so that you can remember work you've done on frame B, so that you don't
    repeat that work when you need to compare against frame C.
    """

    def __init__(self, initial_frame, region=Region.ALL, mask=None,
                 min_size=None):
        self.prev_frame = initial_frame
        self.region = _validate_region(self.prev_frame, region)
        self.mask = mask
        self.min_size = min_size
        if (self.mask is not None and
                self.mask.shape[:2] != (self.region.height, self.region.width)):
            raise ValueError(
                "The dimensions of the mask %s don't match the %s <%ix%i>"
                % (_frame_repr(self.mask),
                   "frame" if region == Region.ALL else "region",
                   self.region.width, self.region.height))

    def diff(self, frame):
        raise NotImplementedError(
            "%s.diff is not implemented" % self.__class__.__name__)

class MotionDiff(FrameDiffer):
    """The `wait_for_motion` diffing algorithm."""

    def __init__(self, initial_frame, region=Region.ALL, mask=None,
                 min_size=None, noise_threshold=None):
        super(MotionDiff, self).__init__(initial_frame, region, mask, min_size)
        if noise_threshold is None:
            noise_threshold = get_config(
                'motion', 'noise_threshold', type_=float)
        self.noise_threshold = noise_threshold
        self.prev_frame_gray = self.gray(initial_frame)

    def gray(self, frame):
        return cv2.cvtColor(crop(frame, self.region), cv2.COLOR_BGR2GRAY)

    def diff(self, frame):
        frame_gray = self.gray(frame)

        imglog = ImageLogger("MotionDiff", region=self.region,
                             min_size=self.min_size,
                             noise_threshold=self.noise_threshold)
        imglog.imwrite("source", frame)
        imglog.imwrite("gray", frame_gray)
        imglog.imwrite("previous_frame_gray", self.prev_frame_gray)

        absdiff = cv2.absdiff(self.prev_frame_gray, frame_gray)
        imglog.imwrite("absdiff", absdiff)

        if self.mask is not None:
            absdiff = cv2.bitwise_and(absdiff, self.mask)
            imglog.imwrite("mask", self.mask)
            imglog.imwrite("absdiff_masked", absdiff)

        _, thresholded = cv2.threshold(
            absdiff, int((1 - self.noise_threshold) * 255), 255,
            cv2.THRESH_BINARY)
        eroded = cv2.morphologyEx(
            thresholded, cv2.MORPH_OPEN,
            cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
        imglog.imwrite("absdiff_threshold", thresholded)
        imglog.imwrite("absdiff_threshold_erode", eroded)

        out_region = pixel_bounding_box(eroded)
        if out_region:
            # Undo crop:
            out_region = out_region.translate(self.region)

        motion = bool(out_region and (
            self.min_size is None or
            (out_region.width >= self.min_size[0] and
             out_region.height >= self.min_size[1])))

        if motion:
            # Only update the comparison frame if it's different to the previous
            # one.  This makes `detect_motion` more sensitive to slow motion
            # because the differences between frames 1 and 2 might be small and
            # the differences between frames 2 and 3 might be small but we'd see
            # the difference by looking between 1 and 3.
            self.prev_frame = frame
            self.prev_frame_gray = frame_gray

        result = MotionResult(getattr(frame, "time", None), motion,
                              out_region, frame)
        ddebug(str(result))
        imglog.html(MOTION_HTML, result=result)
        return result

class MotionResult(object):
    """The result from `detect_motion` and `wait_for_motion`.

    :ivar float time: The time at which the video-frame was captured, in
        seconds since 1970-01-01T00:00Z. This timestamp can be compared with
        system time (``time.time()``).

    :ivar bool motion: True if motion was found. This is the same as evaluating
        ``MotionResult`` as a bool. That is, ``if result:`` will behave the
        same as ``if result.motion:``.

    :ivar Region region: Bounding box where the motion was found, or ``None``
        if no motion was found.

    :ivar Frame frame: The video frame in which motion was (or wasn't) found.
    """
    _fields = ("time", "motion", "region", "frame")

    def __init__(self, time, motion, region, frame):
        self.time = time
        self.motion = motion
        self.region = region
        self.frame = frame

    def __bool__(self):
        return self.motion

    def __nonzero__(self):
        return self.__bool__()

    def __repr__(self):
        return (
            "MotionResult(time=%s, motion=%r, region=%r, frame=%s)" % (
                "None" if self.time is None else "%.3f" % self.time,
                self.motion, self.region, _frame_repr(self.frame)))

MOTION_HTML = u"""\

      detect_motion:
      {{ "Found" if result.motion else "Didn't find" }} motion

    {{ annotated_image(result) }}

Result:

{{ result | escape }}

    {% if result.region and not result.motion %}

Found motion {{ result.region | escape }} smaller than
    min_size {{ min_size | escape }}.

    {% endif %}

ROI Gray:

Previous frame ROI Gray:

Absolute difference:

    {% if "mask" in images %}

Mask:

Absolute difference – masked:

    {% endif %}

Threshold (noise_threshold={{noise_threshold}}):

Eroded:

"""
<|endoftext|>


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

from __future__ import print_function, unicode_literals

from django.http import HttpResponse
from django.test import signals, TestCase
from django.test.client import RequestFactory
from django.template.loader import render_to_string
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.core.urlresolvers import NoReverseMatch

from django_jinja.base import env, dict_from_context, Template

import datetime
import sys

class TemplateFunctionsTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def tearDown(self):
        pass

    def test_template_filters(self):
        filters_data = [
            ("{{ 'test-static.css'|static }}", {}, '/static/test-static.css'),
            ("{{ 'test-1'|reverseurl }}", {}, '/test1/'),
            ("{{ 'test-1'|reverseurl(data=2) }}", {}, '/test1/2/'),
            ("{{ num|floatformat }}", {'num': 34.23234}, '34.2'),
            ("{{ num|floatformat(3) }}", {'num': 34.23234}, '34.232'),
            ("{{ 'hola'|capfirst }}", {}, "Hola"),
            ("{{ 'hola mundo'|truncatechars(5) }}", {}, "ho..."),
            ("{{ 'hola mundo'|truncatewords(1) }}", {}, "hola ..."),
            ("{{ 'hola mundo'|truncatewords_html(1) }}", {}, "hola ..."),
            ("{{ 'hola mundo'|wordwrap(1) }}", {}, "hola\nmundo"),
            ("{{ 'hola mundo'|title }}", {}, "Hola Mundo"),
            ("{{ 'hola mundo'|slugify }}", {}, "hola-mundo"),
            ("{{ 'hello'|ljust(10) }}", {}, "hello     "),
            ("{{ 'hello'|rjust(10) }}", {}, "     hello"),
            ("{{ 'hello\nworld'|linebreaksbr }}", {}, "hello
world"),
            ("{{ '
hello
'|removetags('div') }}", {}, "hello"),
            ("{{ '
hello
'|striptags }}", {}, "hello"),
            ("{{ list|join(',') }}", {'list':['a','b']}, 'a,b'),
            ("{{ 3|add(2) }}", {}, "5"),
            ("{{ now|date('n Y') }}", {"now": datetime.datetime(2012, 12, 20)}, "12 2012"),
        ]

        print()
        for template_str, kwargs, result in filters_data:
            print("- Testing: ", template_str, "with:", kwargs)
            template = env.from_string(template_str)
            _result = template.render(kwargs)
            self.assertEqual(_result, result)

    def test_urlresolve_exceptions(self):
        template = env.from_string("{{ url('adads') }}")
        template.render({})

    def test_custom_addons_01(self):
        template = env.from_string("{{ 'Hello'|replace('H','M') }}")
        result = template.render({})

        self.assertEqual(result, "Mello")

    def test_custom_addons_02(self):
        template = env.from_string("{% if m is one %}Foo{% endif %}")
        result = template.render({'m': 1})

        self.assertEqual(result, "Foo")

    def test_custom_addons_03(self):
        template = env.from_string("{{ myecho('foo') }}")
        result = template.render({})

        self.assertEqual(result, "foo")

    def test_autoescape_01(self):
        old_autoescape_value = env.autoescape
        env.autoescape = True

        template = env.from_string("{{ foo|safe }}")
        result = template.render({'foo': '
Hellp
'})
        self.assertEqual(result, "
Hellp
")

        env.autoescape = old_autoescape_value

    def test_autoescape_02(self):
        old_autoescape_value = env.autoescape
        env.autoescape = True

        template = env.from_string("{{ foo }}")
        result = template.render({'foo': '
Hellp
'})
        self.assertEqual(result, "<h1>Hellp</h1>")

        env.autoescape = old_autoescape_value

    def test_csrf_01(self):
        template_content = "{% csrf_token %}"

        request = self.factory.get('/customer/details')
        if sys.version_info[0] < 3:
            request.META["CSRF_COOKIE"] = b'1234123123'
        else:
            request.META["CSRF_COOKIE"] = '1234123123'

        context = dict_from_context(RequestContext(request))

        template = env.from_string(template_content)
        result = template.render(context)
        self.assertEqual(result, "<input type='hidden' name='csrfmiddlewaretoken' value='1234123123' />")

    def test_cache_01(self):
        template_content = "{% cache 200 'fooo' %}foo bar{% endcache %}"

        request = self.factory.get('/customer/details')
        context = dict_from_context(RequestContext(request))

        template = env.from_string(template_content)
        result = template.render(context)

        self.assertEqual(result, "foo bar")

    def test_404_page(self):
        response = self.client.get(reverse("page-404"))
        self.assertEqual(response.status_code, 404)
        self.assertEqual(response.content, b"404")

    def test_403_page(self):
        response = self.client.get(reverse("page-403"))
        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.content, b"403")

    def test_500_page(self):
        response = self.client.get(reverse("page-500"))
        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.content, b"500")

class DjangoPipelineTestTest(TestCase):
    def test_pipeline_js_safe(self):
        template = env.from_string("{{ compressed_js('test') }}")
        result = template.render({})
        self.assertEqual(result,
            '')

    def test_pipeline_css_safe(self):
        template = env.from_string("{{ compressed_css('test') }}")
        result = template.render({})
        self.assertEqual(result,
            '<link href="/static/style.2.css" rel="stylesheet" type="text/css" />')

class TemplateDebugSignalsTest(TestCase):
    def setUp(self):
        signals.template_rendered.connect(self._listener)

    def tearDown(self):
        signals.template_rendered.disconnect(self._listener)
        signals.template_rendered.disconnect(self._fail_listener)

    def _listener(self, sender=None, template=None, **kwargs):
        self.assertTrue(isinstance(sender, Template))
        self.assertTrue(isinstance(template, Template))

    def _fail_listener(self, *args, **kwargs):
        self.fail("I shouldn't be called")

    def test_render(self):
        with self.settings(TEMPLATE_DEBUG=True):
            tmpl = Template("OK")
            tmpl.render()

    def test_render_without_template_debug_setting(self):
        signals.template_rendered.connect(self._fail_listener)

        with self.settings(TEMPLATE_DEBUG=False):
            tmpl = Template("OK")
            tmpl.render()

    def test_stream(self):
        with self.settings(TEMPLATE_DEBUG=True):
            tmpl = Template("OK")
            tmpl.stream()

    def test_stream_without_template_debug_setting(self):
        signals.template_rendered.connect(self._fail_listener)

        with self.settings(TEMPLATE_DEBUG=False):
            tmpl = Template("OK")
            tmpl.stream()

    def test_template_used(self):
        """
        Test TestCase.assertTemplateUsed with django-jinja template
        """
        template_name = 'test.jinja'

        def view(request, template_name):
            tmpl = Template("{{ test }}")
            return HttpResponse(tmpl.stream({"test": "success"}))

        with self.settings(TEMPLATE_DEBUG=True):
            request = RequestFactory().get('/')
            response = view(request, template_name=template_name)
            self.assertTemplateUsed(response, template_name)
            self.assertEqual(response.content, b"success")
<commit_msg>Add some other test.<commit_after># -*- coding: utf-8 -*-

from __future__ import print_function, unicode_literals

from django.http import HttpResponse
from django.test import signals, TestCase
from django.test.client import RequestFactory
from django.template.loader import render_to_string
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.core.urlresolvers import NoReverseMatch

from django_jinja.base import env, dict_from_context, Template

import datetime
import sys

class TemplateFunctionsTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def tearDown(self):
        pass

    def test_template_filters(self):
        filters_data = [
            ("{{ 'test-static.css'|static }}", {}, '/static/test-static.css'),
            ("{{ 'test-1'|reverseurl }}", {}, '/test1/'),
            ("{{ 'test-1'|reverseurl(data=2) }}", {}, '/test1/2/'),
            ("{{ num|floatformat }}", {'num': 34.23234}, '34.2'),
            ("{{ num|floatformat(3) }}", {'num': 34.23234}, '34.232'),
            ("{{ 'hola'|capfirst }}", {}, "Hola"),
            ("{{ 'hola mundo'|truncatechars(5) }}", {}, "ho..."),
            ("{{ 'hola mundo'|truncatewords(1) }}", {}, "hola ..."),
            ("{{ 'hola mundo'|truncatewords_html(1) }}", {}, "hola ..."),
            ("{{ 'hola mundo'|wordwrap(1) }}", {}, "hola\nmundo"),
            ("{{ 'hola mundo'|title }}", {}, "Hola Mundo"),
            ("{{ 'hola mundo'|slugify }}", {}, "hola-mundo"),
            ("{{ 'hello'|ljust(10) }}", {}, "hello     "),
            ("{{ 'hello'|rjust(10) }}", {}, "     hello"),
            ("{{ 'hello\nworld'|linebreaksbr }}", {}, "hello
world"),
            ("{{ '
hello
'|removetags('div') }}", {}, "hello"),
            ("{{ '
hello
'|striptags }}", {}, "hello"),
            ("{{ list|join(',') }}", {'list':['a','b']}, 'a,b'),
            ("{{ 3|add(2) }}", {}, "5"),
            ("{{ now|date('n Y') }}", {"now": datetime.datetime(2012, 12, 20)}, "12 2012"),
            ("{{ url('test-1') }}", {}, '/test1/'),
        ]

        print()
        for template_str, kwargs, result in filters_data:
            print("- Testing: ", template_str, "with:", kwargs)
            template = env.from_string(template_str)
            _result = template.render(kwargs)
            self.assertEqual(_result, result)

    def test_urlresolve_exceptions(self):
        template = env.from_string("{{ url('adads') }}")
        template.render({})

    def test_custom_addons_01(self):
        template = env.from_string("{{ 'Hello'|replace('H','M') }}")
        result = template.render({})

        self.assertEqual(result, "Mello")

    def test_custom_addons_02(self):
        template = env.from_string("{% if m is one %}Foo{% endif %}")
        result = template.render({'m': 1})

        self.assertEqual(result, "Foo")

    def test_custom_addons_03(self):
        template = env.from_string("{{ myecho('foo') }}")
        result = template.render({})

        self.assertEqual(result, "foo")

    def test_autoescape_01(self):
        old_autoescape_value = env.autoescape
        env.autoescape = True

        template = env.from_string("{{ foo|safe }}")
        result = template.render({'foo': '
Hellp
'})
        self.assertEqual(result, "
Hellp
")

        env.autoescape = old_autoescape_value

    def test_autoescape_02(self):
        old_autoescape_value = env.autoescape
        env.autoescape = True

        template = env.from_string("{{ foo }}")
        result = template.render({'foo': '
Hellp
'})
        self.assertEqual(result, "<h1>Hellp</h1>")

        env.autoescape = old_autoescape_value

    def test_csrf_01(self):
        template_content = "{% csrf_token %}"

        request = self.factory.get('/customer/details')
        if sys.version_info[0] < 3:
            request.META["CSRF_COOKIE"] = b'1234123123'
        else:
            request.META["CSRF_COOKIE"] = '1234123123'

        context = dict_from_context(RequestContext(request))

        template = env.from_string(template_content)
        result = template.render(context)
        self.assertEqual(result, "<input type='hidden' name='csrfmiddlewaretoken' value='1234123123' />")

    def test_cache_01(self):
        template_content = "{% cache 200 'fooo' %}foo bar{% endcache %}"

        request = self.factory.get('/customer/details')
        context = dict_from_context(RequestContext(request))

        template = env.from_string(template_content)
        result = template.render(context)

        self.assertEqual(result, "foo bar")

    def test_404_page(self):
        response = self.client.get(reverse("page-404"))
        self.assertEqual(response.status_code, 404)
        self.assertEqual(response.content, b"404")

    def test_403_page(self):
        response = self.client.get(reverse("page-403"))
        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.content, b"403")

    def test_500_page(self):
        response = self.client.get(reverse("page-500"))
        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.content, b"500")

class DjangoPipelineTestTest(TestCase):
    def test_pipeline_js_safe(self):
        template = env.from_string("{{ compressed_js('test') }}")
        result = template.render({})
        self.assertEqual(result,
            '')

    def test_pipeline_css_safe(self):
        template = env.from_string("{{ compressed_css('test') }}")
        result = template.render({})
        self.assertEqual(result,
            '<link href="/static/style.2.css" rel="stylesheet" type="text/css" />')

class TemplateDebugSignalsTest(TestCase):
    def setUp(self):
        signals.template_rendered.connect(self._listener)

    def tearDown(self):
        signals.template_rendered.disconnect(self._listener)
        signals.template_rendered.disconnect(self._fail_listener)

    def _listener(self, sender=None, template=None, **kwargs):
        self.assertTrue(isinstance(sender, Template))
        self.assertTrue(isinstance(template, Template))

    def _fail_listener(self, *args, **kwargs):
        self.fail("I shouldn't be called")

    def test_render(self):
        with self.settings(TEMPLATE_DEBUG=True):
            tmpl = Template("OK")
            tmpl.render()

    def test_render_without_template_debug_setting(self):
        signals.template_rendered.connect(self._fail_listener)

        with self.settings(TEMPLATE_DEBUG=False):
            tmpl = Template("OK")
            tmpl.render()

    def test_stream(self):
        with self.settings(TEMPLATE_DEBUG=True):
            tmpl = Template("OK")
            tmpl.stream()

    def test_stream_without_template_debug_setting(self):
        signals.template_rendered.connect(self._fail_listener)

        with self.settings(TEMPLATE_DEBUG=False):
            tmpl = Template("OK")
            tmpl.stream()

    def test_template_used(self):
        """
        Test TestCase.assertTemplateUsed with django-jinja template
        """
        template_name = 'test.jinja'

        def view(request, template_name):
            tmpl = Template("{{ test }}")
            return HttpResponse(tmpl.stream({"test": "success"}))

        with self.settings(TEMPLATE_DEBUG=True):
            request = RequestFactory().get('/')
            response = view(request, template_name=template_name)
            self.assertTemplateUsed(response, template_name)
            self.assertEqual(response.content, b"success")
<|endoftext|>


<commit_before>from pyinfra import host
from pyinfra.modules import lxd

SUDO = True

# Note: This is an example of running a command on remote
server.shell(
    {'Run lxd auto init'},
    'lxd init --auto',
)

lxd.container(
    {'Add an ubuntu container'},
    'ubuntu19',
    image='ubuntu:19.10',
)
<commit_msg>remove unused import<commit_after>from pyinfra.modules import lxd, server

SUDO = True

# Note: This is an example of running a command on remote
server.shell(
    {'Run lxd auto init'},
    'lxd init --auto',
)

lxd.container(
    {'Add an ubuntu container'},
    'ubuntu19',
    image='ubuntu:19.10',
)
<|endoftext|>


<commit_before>import config

class Full:
    def output(self, train):
        return ("{time}\t{delayed}{actual} {destination}".format(
            time=train.timetabled_departure.strftime("%H:%M"),
            delayed='!' if train.delayed else ' ',
            actual=train.actual_departure.strftime("%H:%M") if train.actual_departure else '??:??',
            destination=train.destination))

class SixteenByTwo:

    @classmethod
    def countdown(cls, train):

        minutes = train.minutes_until
        if minutes is None:
            minutes = '??'  # Expected departure unknown
        elif minutes > 99:
            minutes = '99'  # A long time until this train leaves
        return str(minutes)

    @classmethod
    def delay(cls, train):
        if train.delayed:
            if train.minutes_late:
                return '+{}'.format(train.minutes_late)  # Known delay
            else:
                return '!'                               # Unknown delay
        else:
            return ''

    def output(self, train):

        time = train.timetabled_departure.strftime("%H:%M")
        return "{time} {countdown:2} {delay:>3} {station}".format(
            time=time,
            countdown=self.__class__.countdown(train),
            delay=self.__class__.delay(train),
            station=config.STATION_CODES[train.destination])
<commit_msg>added comments<commit_after>import config

class Full:

    def output(self, train):
        """Format train information for a terminal display"""

        return ("{time}\t{delayed}{actual} {destination}".format(
            time=train.timetabled_departure.strftime("%H:%M"),
            delayed='!' if train.delayed else ' ',
            actual=train.actual_departure.strftime("%H:%M") if train.actual_departure else '??:??',
            destination=train.destination))

class SixteenByTwo:

    def countdown(self, train):
        """Indicate number of minutes until train departs
           Unknown departure time:     '??'
           More than 99 minutes away:  '99'
           Fewer than 99 minutes away: '37'
        """

        minutes = train.minutes_until
        if minutes is None:
            minutes = '??'  # Expected departure unknown
        elif minutes > 99:
            minutes = '99'  # A long time until this train leaves
        return str(minutes)

    def delay(self, train):
        """Indicate number of minutes the train is delayed
            Known delay:   '+37'
            Unknown delay: '!'
            No delay:      ''
        """

        if train.delayed:
            if train.minutes_late:
                return '+{}'.format(train.minutes_late)  # Known delay
            else:
                return '!'                               # Unknown delay
        else:
            return ''

    def output(self, train):
        """Format train information for a 16x2 character display
            Normal (no delay):  10:32 10     WAT
            Known delay:        10:47  8 +35 PMH
            Unknown delay:      11:01 ??   ! RDG
        """

        time = train.timetabled_departure.strftime("%H:%M")
        return "{time} {countdown:2} {delay:>3} {station}".format(
            time=time,
            countdown=self.countdown(train),
            delay=self.delay(train),
            station=config.STATION_CODES[train.destination])
<|endoftext|>