<commit_before>import sys

from bp.filepath import FilePath

from _opencv import ffi, lib
from opencv_cffi.imaging import Camera
from opencv_cffi.gui import Window
from opencv_cffi.object_detection import HaarClassifier

ESCAPE = ord("\x1b")

classifier = HaarClassifier.from_path(FilePath(sys.argv[1]))
camera = Camera(index=0)

def escape_is_pressed(milliseconds=20):
    return lib.cvWaitKey(milliseconds) == ESCAPE

def uglify(frame, facetangle):
    lib.cvSetImageROI(frame, facetangle.right_half._cv_rect)
    lib.cvNot(frame, frame)
    lib.cvResetImageROI(frame)

def prettify(frame, facetangle):
    facetangle.draw_onto(frame)

transform = uglify if sys.argv[2] == "uglify" else prettify

with Window(name="Example") as window:
    for frame in camera.frames():
        if escape_is_pressed():
            break

        for rectangle in classifier.detect_objects(inside=frame):
            transform(frame=frame, facetangle=rectangle)

        window.show(frame)
<commit_msg>Wait less.<commit_after>import sys

from bp.filepath import FilePath

from _opencv import ffi, lib
from opencv_cffi.imaging import Camera
from opencv_cffi.gui import Window
from opencv_cffi.object_detection import HaarClassifier

ESCAPE = ord("\x1b")

classifier = HaarClassifier.from_path(FilePath(sys.argv[1]))
camera = Camera(index=0)

def escape_is_pressed(milliseconds=1):
    return lib.cvWaitKey(milliseconds) == ESCAPE

def uglify(frame, facetangle):
    lib.cvSetImageROI(frame, facetangle.right_half._cv_rect)
    lib.cvNot(frame, frame)
    lib.cvResetImageROI(frame)

def prettify(frame, facetangle):
    facetangle.draw_onto(frame)

transform = uglify if sys.argv[2] == "uglify" else prettify

with Window(name="Example") as window:
    for frame in camera.frames():
        if escape_is_pressed():
            break

        for rectangle in classifier.detect_objects(inside=frame):
            transform(frame=frame, facetangle=rectangle)

        window.show(frame)
<|endoftext|>


<commit_before>from stat_parser.parser import Parser

if __name__ == '__main__':
    parser = Parser()
    print parser.parse("Who leads the star ship Enterprise in Star Trek ?")
<commit_msg>Parse the last question :-)<commit_after>from stat_parser.parser import Parser

if __name__ == '__main__':
    parser = Parser()

    # http://www.thrivenotes.com/the-last-question/
    print parser.parse("How can the net amount of entropy of the universe be massively decreased?")
<|endoftext|>


<commit_before># coding=utf-8

import os
import sys
import time
import termios

import contactList
import communicator
import messageClass

def main():
	endMain = False
	os.system('clear')

	print '----------- MODULO DE COMUNICACION -----------\n'
	print '\t\t1 - Enviar mensaje/archivo'
	print '\t\t2 - Enviar instancia de mensaje'
	print '\t\t3 - Leer un mensaje'
	print '\t\t4 - Llamar a un número'
	print '\t\t5 - Atender la llamada'
	print '\t\t6 - Colgar la llamada'
	print '\t\t7 - Conectar GPRS'
	print '\t\t8 - Desconectar GPRS'
	print '\t\tc - DEBUG: Cerrar Comunicador'
	print '\t\to - DEBUG: Abrir Comunicador'
	print '\t\tq - Salir\n'

	communicator.open() # Se abre el comunicador para detectar medios
	print 'El módulo de comunicación está listo para usarse!'

	while not endMain:
		try:
			termios.tcflush(sys.stdin, termios.TCIOFLUSH) # Limpiamos el stdin
			optionSelected = raw_input()
			# Opcion 1 - Enviar mensaje
			if optionSelected is '1':
				# Preguntamos si se desea ver una lista con los clientes registrados
				selectClient = askClients()
				if selectClient is None:
					print 'Abortado.'
					continue
				# Indicamos el cliente al cual se va a enviar el mensaje
				receiver = raw_input('Cliente a enviar: ')
				# Indicamos el mensaje que se desea enviar
				messageToSend = raw_input('Mensaje a enviar: ')
				# Preguntamos si hay alguna preferencia en relación a los medios de comunicación
				selectMedia = askMedia()
				if selectMedia is True:
					# El medio preferido está dado por 'media'
					media = raw_input('Medio de comunicación preferido: ')
					communicator.send(messageToSend, receiver, media) # <----- IMPORTANTE
				elif selectMedia is False:
					# El medio se elige automáticamente
					communicator.send(messageToSend, receiver) # <----- IMPORTANTE
				else:
					print 'Abortado.'
					continue
			# Opcion 2 - Enviar instancia de mensaje
			elif optionSelected is '2':
				# Establecemos el campo 'sender'
				sender = raw_input('Nombre del emisor: ')
				# Preguntamos si se desea ver una lista con los clientes registrados
				selectClient = askClients()
				if selectClient is None:
					print 'Abortado.'
					continue
				# Establecemos el campo 'receiver'
				receiver = raw_input('Cliente a enviar: ')
				# Establecemos el campo 'infoText'
				infoText = raw_input('Mensaje a enviar: ')
				# Creamos la instancia de mensaje
				infoMessage = messageClass.InfoMessage(sender, receiver, infoText)
				# Preguntamos si hay alguna preferencia en relación a los medios de comunicación
				selectMedia = askMedia()
				if selectMedia is True:
					# El medio preferido está dado por 'media'
					media = raw_input('Medio de comunicación preferido: ')
					communicator.send(infoMessage, media = media) # <----- IMPORTANTE
				elif selectMedia is False:
					# El medio se elige automáticamente
					communicator.send(infoMessage) # <----- IMPORTANTE
				else:
					print 'Abortado.'
					continue
			# Opcion 3 - Leer un mensaje
			elif optionSelected is '3':
				messageReceived = communicator.receive()
				if messageReceived is not None:
					if isinstance(messageReceived, messageClass.Message):
						print 'Instancia de mensaje recibida: ' + str(messageReceived)
						print '\tPrioridad: ' + str(messageReceived.priority)
						print '\tEmisor: ' + messageReceived.sender
						if isinstance(messageReceived, messageClass.InfoMessage):
							print '\tMensaje de texto: ' + str(messageReceived.infoText)
					else:
						print 'Mensaje recibido: %s' % messageReceived
			# Opcion 4 - Llamar a un número
			elif optionSelected is '4':
				# Indicamos el número al cual efectuar la llamada de voz
				telephoneNumber = raw_input('Número a llamar: ')
				communicator.sendVoiceCall(telephoneNumber)
			# Opcion 5 - Atender la llamada
			elif optionSelected is '5':
				communicator.answerVoiceCall()
			# Opcion 6 - Colgar la llamada
			elif optionSelected is '6':
				communicator.hangUpVoiceCall()
			# Opcion 7 - Conectar GPRS
			elif optionSelected is '7':
				communicator.connectGprs()
			# Opcion 8 - Desconectar GPRS
			elif optionSelected is '8':
				communicator.disconnectGprs()
			elif optionSelected is 'c':
				communicator.close()
			elif optionSelected is 'o':
				communicator.open()
			elif optionSelected is 'q':
				endMain = True
			# Opcion inválida
			else:
				print 'Opción inválida!'
		except KeyboardInterrupt:
			endMain = True

	print 'Cerrando la aplicación...'
	communicator.close() # Se cierran las conexiones
	print '\n---------------- UNC - Fcefyn ----------------'
	print '---------- Ingeniería en Computación ---------'

def askClients():
	showClients = raw_input('¿Desea ver los clientes registrados? [S/n] ')
	if showClients is 'S' or showClients is 's' or len(showClients) is 0:
		# Creamos una lista de claves (clientes registrados en los diccionarios)
		clientList = list() + contactList.allowedHosts.keys()
		clientList += contactList.allowedMacAddress.keys()
		clientList += contactList.allowedEmails.keys()
		clientList += contactList.allowedNumbers.keys()
		# Quitamos los clientes repetidos
		clientList = list(set(clientList))
		print clientList
		return True
	elif showClients is 'N' or showClients is 'n':
		return False
	else:
		return None

def askMedia():
	selectMedia = raw_input('¿Desea elegir un medio de comunicación preferido? [S/n] ')
	if selectMedia is 'S' or selectMedia is 's' or len(selectMedia) is 0:
		print 'Lista de medios: NETWORK, BLUETOOTH, EMAIL, SMS.'
		return True
	elif selectMedia is 'N' or selectMedia is 'n':
		return False
	else:
		return None

if __name__ == '__main__':
	main()
<commit_msg>Cambio de orden en el menú principal.<commit_after># coding=utf-8

import os
import sys
import termios

import contactList
import communicator
import messageClass

def main():
	endMain = False
	os.system('clear')

	print '----------- MODULO DE COMUNICACION -----------\n'
	print '\t\t1 - Enviar mensaje/archivo'
	print '\t\t2 - Enviar instancia de mensaje'
	print '\t\t3 - Leer un mensaje'
	print '\t\t4 - Llamar a un número'
	print '\t\t5 - Atender la llamada'
	print '\t\t6 - Colgar la llamada'
	print '\t\t7 - Conectar GPRS'
	print '\t\t8 - Desconectar GPRS'
	print '\t\tq - Salir'
	print '\t\to - DEBUG: Abrir Comunicador'
	print '\t\tc - DEBUG: Cerrar Comunicador\n'

	communicator.open() # Se abre el comunicador para detectar medios
	print 'El módulo de comunicación está listo para usarse!'

	while not endMain:
		try:
			termios.tcflush(sys.stdin, termios.TCIOFLUSH) # Limpiamos el stdin
			optionSelected = raw_input()
			# Opcion 1 - Enviar mensaje
			if optionSelected is '1':
				# Preguntamos si se desea ver una lista con los clientes registrados
				selectClient = askClients()
				if selectClient is None:
					print 'Abortado.'
					continue
				# Indicamos el cliente al cual se va a enviar el mensaje
				receiver = raw_input('Cliente a enviar: ')
				# Indicamos el mensaje que se desea enviar
				messageToSend = raw_input('Mensaje a enviar: ')
				# Preguntamos si hay alguna preferencia en relación a los medios de comunicación
				selectMedia = askMedia()
				if selectMedia is True:
					# El medio preferido está dado por 'media'
					media = raw_input('Medio de comunicación preferido: ')
					communicator.send(messageToSend, receiver, media) # <----- IMPORTANTE
				elif selectMedia is False:
					# El medio se elige automáticamente
					communicator.send(messageToSend, receiver) # <----- IMPORTANTE
				else:
					print 'Abortado.'
					continue
			# Opcion 2 - Enviar instancia de mensaje
			elif optionSelected is '2':
				# Establecemos el campo 'sender'
				sender = raw_input('Nombre del emisor: ')
				# Preguntamos si se desea ver una lista con los clientes registrados
				selectClient = askClients()
				if selectClient is None:
					print 'Abortado.'
					continue
				# Establecemos el campo 'receiver'
				receiver = raw_input('Cliente a enviar: ')
				# Establecemos el campo 'infoText'
				infoText = raw_input('Mensaje a enviar: ')
				# Creamos la instancia de mensaje
				infoMessage = messageClass.InfoMessage(sender, receiver, infoText)
				# Preguntamos si hay alguna preferencia en relación a los medios de comunicación
				selectMedia = askMedia()
				if selectMedia is True:
					# El medio preferido está dado por 'media'
					media = raw_input('Medio de comunicación preferido: ')
					communicator.send(infoMessage, media = media) # <----- IMPORTANTE
				elif selectMedia is False:
					# El medio se elige automáticamente
					communicator.send(infoMessage) # <----- IMPORTANTE
				else:
					print 'Abortado.'
					continue
			# Opcion 3 - Leer un mensaje
			elif optionSelected is '3':
				messageReceived = communicator.receive()
				if messageReceived is not None:
					if isinstance(messageReceived, messageClass.Message):
						print 'Instancia de mensaje recibida: ' + str(messageReceived)
						print '\tPrioridad: ' + str(messageReceived.priority)
						print '\tEmisor: ' + messageReceived.sender
						if isinstance(messageReceived, messageClass.InfoMessage):
							print '\tMensaje de texto: ' + str(messageReceived.infoText)
					else:
						print 'Mensaje recibido: %s' % messageReceived
			# Opcion 4 - Llamar a un número
			elif optionSelected is '4':
				# Indicamos el número al cual efectuar la llamada de voz
				telephoneNumber = raw_input('Número a llamar: ')
				communicator.sendVoiceCall(telephoneNumber)
			# Opcion 5 - Atender la llamada
			elif optionSelected is '5':
				communicator.answerVoiceCall()
			# Opcion 6 - Colgar la llamada
			elif optionSelected is '6':
				communicator.hangUpVoiceCall()
			# Opcion 7 - Conectar GPRS
			elif optionSelected is '7':
				communicator.connectGprs()
			# Opcion 8 - Desconectar GPRS
			elif optionSelected is '8':
				communicator.disconnectGprs()
				communicator.close()
			elif optionSelected is 'q':
				endMain = True
			elif optionSelected is 'o':
				communicator.open()
			elif optionSelected is 'c':
			# Opcion inválida
			else:
				print 'Opción inválida!'
		except KeyboardInterrupt:
			endMain = True

	print 'Cerrando la aplicación...'
	communicator.close() # Se cierran las conexiones
	print '\n---------------- UNC - Fcefyn ----------------'
	print '---------- Ingeniería en Computación ---------'

def askClients():
	showClients = raw_input('¿Desea ver los clientes registrados? [S/n] ')
	if showClients is 'S' or showClients is 's' or len(showClients) is 0:
		# Creamos una lista de claves (clientes registrados en los diccionarios)
		clientList = list() + contactList.allowedHosts.keys()
		clientList += contactList.allowedMacAddress.keys()
		clientList += contactList.allowedEmails.keys()
		clientList += contactList.allowedNumbers.keys()
		# Quitamos los clientes repetidos
		clientList = list(set(clientList))
		print clientList
		return True
	elif showClients is 'N' or showClients is 'n':
		return False
	else:
		return None

def askMedia():
	selectMedia = raw_input('¿Desea elegir un medio de comunicación preferido? [S/n] ')
	if selectMedia is 'S' or selectMedia is 's' or len(selectMedia) is 0:
		print 'Lista de medios: NETWORK, BLUETOOTH, EMAIL, SMS.'
		return True
	elif selectMedia is 'N' or selectMedia is 'n':
		return False
	else:
		return None

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


<commit_before>import itertools
import string
import sys

class ControllerConfig(object):
  _port_gen = itertools.count(8888)

  def __init__(self, cmdline="", address="127.0.0.1", port=None, cwd=None):
    '''
    Store metadata for the controller.
      - cmdline is an array of command line tokens.

        Note: if you need to pass in the address and port to controller's
        command line, use the aliases __address__ and __port__ to have the
        values interpolated automatically
      - address and port are the sockets switches will bind to
    '''
    if cmdline == "":
      raise RuntimeError("Must specify boot parameters.")
    self.cmdline_string = cmdline
    self.address = address
    if not port:
      port = self._port_gen.next()
    self.port = port
    if "pox" in self.cmdline_string:
      self.name = "pox"
    self.cmdline = map(lambda(x): string.replace(x, "__port__", str(port)),
                       map(lambda(x): string.replace(x, "__address__",
                                                     str(address)), cmdline.split()))
    self.cwd = cwd
    if not cwd:
        sys.stderr.write("""
        =======================================================================
        WARN - no working directory defined for controller with command line
        %s
        The controller is run in the STS base directory. This may result
        in unintended consequences (i.e., POX not logging correctly).
        =======================================================================
        \n""" % (self.cmdline) )

  @property
  def uuid(self):
    return (self.address, self.port)

  def __repr__(self):
    return self.__class__.__name__  + "(cmdline=\"" + self.cmdline_string +\
           "\",address=\"" + self.address + "\",port=" + self.port.__repr__() + ")"
<commit_msg>config/experiment_config_lib: add cwd= parameter to self.__repr__<commit_after>import itertools
import string
import sys

class ControllerConfig(object):
  _port_gen = itertools.count(8888)

  def __init__(self, cmdline="", address="127.0.0.1", port=None, cwd=None):
    '''
    Store metadata for the controller.
      - cmdline is an array of command line tokens.

        Note: if you need to pass in the address and port to controller's
        command line, use the aliases __address__ and __port__ to have the
        values interpolated automatically
      - address and port are the sockets switches will bind to
    '''
    if cmdline == "":
      raise RuntimeError("Must specify boot parameters.")
    self.cmdline_string = cmdline
    self.address = address
    if not port:
      port = self._port_gen.next()
    self.port = port
    if "pox" in self.cmdline_string:
      self.name = "pox"
    self.cmdline = map(lambda(x): string.replace(x, "__port__", str(port)),
                       map(lambda(x): string.replace(x, "__address__",
                                                     str(address)), cmdline.split()))
    self.cwd = cwd
    if not cwd:
        sys.stderr.write("""
        =======================================================================
        WARN - no working directory defined for controller with command line
        %s
        The controller is run in the STS base directory. This may result
        in unintended consequences (i.e., POX not logging correctly).
        =======================================================================
        \n""" % (self.cmdline) )

  @property
  def uuid(self):
    return (self.address, self.port)

  def __repr__(self):
    return self.__class__.__name__  + "(cmdline=\"" + self.cmdline_string +\
           "\", address=\"" + self.address + "\",port=" + self.port.__repr__() + \
          ( (", cwd=\"%s\"" % self.cwd) if self.cwd else "" ) + \
           ")"
<|endoftext|>


<commit_before>import time
import gdal
from gdalconst import *
from osgeo import osr
from osgeo import ogr

from shapely.wkb import loads

import numpy as np
import matplotlib.pyplot as plt

# see http://www.gis.usu.edu/~chrisg/python/2009/lectures/ospy_slides4.pdf

class Reader:
    """
    Loads raster data point one at a time
    """
    def __init__(self,file_name):
        """
        initializes the data_set member
        """
        # register all of the drivers
        gdal.AllRegister()

        # open image
        self.data_set = gdal.Open(file_name, GA_ReadOnly)
        if self.data_set is None:
            print("Could not open file")
            exit(1)
        print(file_name + " read successfully")

        # coordinates:
        #  |
        #--+--------------> x
        #  |
        #  |
        #  |
        #  |
        #  V y
        #
        # instance variables
        # originX and originY are at the upper left corner of the raster image
        # these coordinates are in universal transverse merator coordinate system
        #, a 2-D projection coordinate system that is suitable for a large-`scale`
        # map, i.e., around Lewisburg instead of the entire state
        # UTM could be converted to latitude are longitudes, but UTM
        # might provid more precision
        self._originX = 0           # easting; UTM
        self._originY = 0           # northing; UTM

        self._pixelWidth = 0
        self._pixelHeight = 0
        self._bands = 0             # number of `channels` (like RGB channels) for one pixel
        self._rows = 0              # along y axis
        self._cols = 0              # along x axis
        self.x_list = []            # x-coordinates along the cross-section of choice
        self.y_list = []            # y-coordinates along the cross-section of choice
        self.elevation_list = []    # the elevation at point (x,y), unit: m
        self.k1 = 0                 # slop of transect in x-y plane
        self.b1 = 0                 # y-axis intersection
        self.n_step=0

        self._define_boundaries()   # initialize boundary variables

    def __str__(self):
        """
        returns the projection spec.
        """
        pszProjection = self.data_set.GetProjectionRef()
        if pszProjection is not None:
            hSRS = osr.SpatialReference()
            if hSRS.ImportFromWkt(pszProjection ) == gdal.CE_None:
                pszPrettyWkt = hSRS.ExportToPrettyWkt(False)
                return pszPrettyWkt
            else:
                return pszProjection

    def _define_boundaries(self):
        """
        Defines the boundary of the raster files
        """
        self._cols = self.data_set.RasterXSize
        self._rows = self.data_set.RasterYSize
        self._bands = self.data_set.RasterCount

        geo_transform = self.data_set.GetGeoTransform()

        if geo_transform is None:
            print("geo_transform is None")

        self._originX = geo_transform[0]
        self._originY = geo_transform[3]
        self._pixelWidth = geo_transform[1]
        self._pixelHeight = geo_transform[5]

    def close(self):
        self.data_set = None

    def get_x_offset(self, x):
        """
        gets the pixel index on x-axis
        """
        return int((x - self._originX) / self._pixelWidth)

    def get_y_offset(self, y):
        """
        gets the pixel index on x-axis
        """
        return int((y - self._originY) / self._pixelHeight)

    def get_pixel_value(self, x, y):
        """
        x: easting
        y: northing
        the pixel value is -32768? for data points
        outside the raster image
        """

        x_offset = self.get_x_offset(x)
        y_offset = self.get_y_offset(y)

        for i in range(self._bands):
            band = self.data_set.GetRasterBand(i+1)
            # dataArray: one data point at a time
            data_array = band.ReadAsArray(x_offset, y_offset, 1, 1)
            value = data_array[0, 0]
            return value

    def get_line_feature(self, x1, y1, x2, y2):
        """
        four parameters are in UTM
        x1, x2: easting
        y1, y2: northing
        (x1, y1): coordinate for the transmitter
        (x2, y2): coordinate for the receiver
        samples the transect with interval = pixel width and
        generates the elevation list
        """
        self.k1 = (y2 - y1) / (x2 - x1)
        self.b1 = y1 - self.k1 * x1
        self.n_step = (x2 - x1) // self._pixelWidth

        for i in range(int(self.n_step)):
            x = x1 + i * self._pixelWidth
            y = self.k1 * x + self.b1
            self.x_list.append(x)
            self.y_list.append(y)
            value = self.get_pixel_value(x, y)
            self.elevation_list.append(value)

    def get_hindrance(self):
        """
        this method might be broken
        """
        hindrance_list = []
        sensor_elev = self.elevation_list[0]
        recv_elev = self.elevation_list[-1]
        delta_elev = sensor_elev - recv_elev
        x_square = (self.x_list[0] - self.x_list[-1]) ** 2
        y_square = (self.y_list[0] - self.y_list[-1]) ** 2
        distance = (x_square + y_square) ** 0.5

        k = (delta_elev) / (distance)
        b = self.elevation_list[0] - k * self.x_list[0]

        for i in range(len(self.elevation_list)):
            supposed_elev = self.x_list[i] * self.k1  + self.b1
            if self.elevation_list[i] >= supposed_elev:
                return (self.x_list[i], self.elevation_list[i])

    def plot_results(self):
        """
        this method is broken?
        """
        fig = plt.figure()
        fig.suptitle('Cross section', fontsize=14, fontweight='bold')
        ax = fig.add_subplot(111)
        ax.plot(self.x_list, self.elevation_list)
        ax.set_xlabel('easting')
        ax.set_ylabel('elevation (m)')

        plt.show()

if __name__ == "__main__":
    # some convenient coordinates:
    # Breakiron:
    # lat: 40.954824, long: -76.881087
    # easting: 341685.7, northing: 4535445.9

    # the boat launch
    # lat: 40.955312, long: -76.877387
    # easting: 341998.2, northing: 4535493.4

    # north size of winfield
    # 342279.95, 4532332.21
    t_start = time.time()
    reader = Reader("../lewisburg_pa/lewisburg_pa.dem")

    # print(reader.get_pixel_value(341674.7, 4535455.3))
    reader.get_line_feature(338977.89, 4536688.13, 339514.93, 4534804.52)
    reader.plot_results()
    reader.close()
    t_end = time.time()
    print("Time: " + str(t_end - t_start))

    # add API: get_pixel_value(offset's)
    # another class: ruler:
    #   __init__(self, easting, northing)
    #   loops through every grid and get_pixel_value(offset's)
    # add converter: distance -> easting and northing
<commit_msg>could plot something<commit_after>import time
import gdal
from gdalconst import *
from osgeo import osr
from osgeo import ogr

from shapely.wkb import loads

import numpy as np
import matplotlib.pyplot as plt

# see http://www.gis.usu.edu/~chrisg/python/2009/lectures/ospy_slides4.pdf

class Reader:
    """
    Loads raster data point one at a time
    """
    def __init__(self,file_name):
        """
        initializes the data_set member
        """
        # register all of the drivers
        gdal.AllRegister()

        # open image
        self.data_set = gdal.Open(file_name, GA_ReadOnly)
        if self.data_set is None:
            print("Could not open file")
            exit(1)
        print(file_name + " read successfully")

        # coordinates:
        #  |
        #--+--------------> x
        #  |
        #  |
        #  |
        #  |
        #  V y
        #
        # instance variables
        # originX and originY are at the upper left corner of the raster image
        # these coordinates are in universal transverse merator coordinate system
        #, a 2-D projection coordinate system that is suitable for a large-`scale`
        # map, i.e., around Lewisburg instead of the entire state
        # UTM could be converted to latitude are longitudes, but UTM
        # might provid more precision
        self._originX = 0           # easting; UTM
        self._originY = 0           # northing; UTM

        self._pixelWidth = 0
        self._pixelHeight = 0
        self._bands = 0             # number of `channels` (like RGB channels) for one pixel
        self._rows = 0              # along y axis
        self._cols = 0              # along x axis
        self.x_list = []            # x-coordinates along the cross-section of choice
        self.y_list = []            # y-coordinates along the cross-section of choice
        self.elevation_list = []    # the elevation at point (x,y), unit: m
        self.k1 = 0                 # slop of transect in x-y plane
        self.b1 = 0                 # y-axis intersection
        self.n_step=0

        self._define_boundaries()   # initialize boundary variables

    def __str__(self):
        """
        returns the projection spec.
        """
        pszProjection = self.data_set.GetProjectionRef()
        if pszProjection is not None:
            hSRS = osr.SpatialReference()
            if hSRS.ImportFromWkt(pszProjection ) == gdal.CE_None:
                pszPrettyWkt = hSRS.ExportToPrettyWkt(False)
                return pszPrettyWkt
            else:
                return pszProjection

    def _define_boundaries(self):
        """
        Defines the boundary of the raster files
        """
        self._cols = self.data_set.RasterXSize
        self._rows = self.data_set.RasterYSize
        self._bands = self.data_set.RasterCount

        geo_transform = self.data_set.GetGeoTransform()

        if geo_transform is None:
            print("geo_transform is None")

        self._originX = geo_transform[0]
        self._originY = geo_transform[3]
        self._pixelWidth = geo_transform[1]
        self._pixelHeight = geo_transform[5]

    def close(self):
        self.data_set = None

    def get_x_offset(self, x):
        """
        gets the pixel index on x-axis
        """
        return int((x - self._originX) / self._pixelWidth)

    def get_y_offset(self, y):
        """
        gets the pixel index on x-axis
        """
        return int((y - self._originY) / self._pixelHeight)

    def get_pixel_value(self, x, y):
        """
        x: easting
        y: northing
        the pixel value is -32768? for data points
        outside the raster image
        """

        x_offset = self.get_x_offset(x)
        y_offset = self.get_y_offset(y)

        for i in range(self._bands):
            band = self.data_set.GetRasterBand(i+1)
            # dataArray: one data point at a time
            data_array = band.ReadAsArray(x_offset, y_offset, 1, 1)
            value = data_array[0, 0]
            return value

    def get_line_feature(self, x1, y1, x2, y2):
        """
        four parameters are in UTM
        x1, x2: easting
        y1, y2: northing
        (x1, y1): coordinate for the transmitter
        (x2, y2): coordinate for the receiver
        samples the transect with interval = pixel width and
        generates the elevation list
        """
        self.k1 = (y2 - y1) / (x2 - x1)
        self.b1 = y1 - self.k1 * x1
        self.n_step = (x2 - x1) // self._pixelWidth

        for i in range(int(self.n_step)):
            x = x1 + i * self._pixelWidth
            y = self.k1 * x + self.b1
            self.x_list.append(x)
            self.y_list.append(y)
            value = self.get_pixel_value(x, y)
            self.elevation_list.append(value)

    def get_hindrance(self):
        """
        this method might be broken
        """
        hindrance_list = []
        sensor_elev = self.elevation_list[0]
        recv_elev = self.elevation_list[-1]
        delta_elev = sensor_elev - recv_elev
        x_square = (self.x_list[0] - self.x_list[-1]) ** 2
        y_square = (self.y_list[0] - self.y_list[-1]) ** 2
        distance = (x_square + y_square) ** 0.5

        k = (delta_elev) / (distance)
        b = self.elevation_list[0] - k * self.x_list[0]

        for i in range(len(self.elevation_list)):
            supposed_elev = self.x_list[i] * self.k1  + self.b1
            if self.elevation_list[i] >= supposed_elev:
                return (self.x_list[i], self.elevation_list[i])

    def plot_results(self):
        """
        this method is broken?
        """
        fig = plt.figure()
        fig.suptitle('Cross section', fontsize=14, fontweight='bold')
        ax = fig.add_subplot(111)
        ax.plot(self.x_list, self.elevation_list)
        ax.set_xlabel('easting')
        ax.set_ylabel('elevation (m)')

        plt.show()

if __name__ == "__main__":
    # some convenient coordinates:
    # Breakiron:
    # lat: 40.954824, long: -76.881087
    # easting: 341685.7, northing: 4535445.9

    # the boat launch
    # lat: 40.955312, long: -76.877387
    # easting: 341998.2, northing: 4535493.4

    # north size of winfield
    # 342279.95, 4532332.21
    t_start = time.time()
    reader = Reader("../lewisburg_pa/lewisburg_pa.dem")

    # print(reader.get_pixel_value(341674.7, 4535455.3))
    reader.get_line_feature(338977.89, 4536688.13, 339514.93, 4534804.52)
    reader.plot_results()
    reader.close()
    t_end = time.time()
    print("Time: " + str(t_end - t_start))

    # add converter: distance -> easting and northing
<|endoftext|>


<commit_before>#import the needed modules fo communication with minecraft world
from mcpi.minecraft import *
# import needed block defintiions
from mcpi.block import DIAMOND_BLOCK
# needed to slow down the wall building
from time import sleep
# needed to generate a random number for the colour of wool
from random import randint

def sendToChatAndConsole(minecraft, message):

    # print to the python interpreter standard output (terminal or IDLE probably)
    print(message)
    # send message to the minecraft chat
    minecraft.postToChat(message)

if __name__ == "__main__":
    #    First thing you do is create a connection to minecraft
    #    This is like dialling a phone.
    #    It sets up a communication line between your script and the minecraft world

    # Create a connection to Minecraft
    # Any communication with the world must use this object
    mc = Minecraft.create()

    sendToChatAndConsole(mc, "Saving Checkpoint")
    #Save a checkpoint for the world state
    mc.saveCheckpoint()

    #wait for 2 seconds
    sleep(2)

    # Get the player position
    playerPosition = mc.player.getTilePos()

    wallStartXposn = playerPosition.x + 6
    wallStartYposn = playerPosition.y + 1
    wallZposn      = playerPosition.z + 6

    wallEndXposn = wallStartXposn + 10
    wallEndYposn = wallStartYposn + 6

    # Create a wall
    mc.setBlocks(wallStartXposn , wallStartYposn, wallZposn, \
                   wallEndXposn,    wallEndYposn,   wallZposn, \
                   DIAMOND_BLOCK)

    #wait for 4 seconds
    sleep(4)

    sendToChatAndConsole(mc, "Restoring Checkpoint")
    # Set the world back to the state it was in at the last saved checkpoint
    mc.restoreCheckpoint()

    sendToChatAndConsole(mc, "Making World unbreakable")
    mc.setting('world_immutable', 1)
    #wait for 8 seconds
    sleep(8)
    sendToChatAndConsole(mc, "Making World breakable")
    mc.setting('world_immutable', 0)
    #wait for 4 seconds
    sleep(4)
    #Follow the player
    sendToChatAndConsole(mc, "Set Camera to follow the player")
    mc.camera.setFollow(1)
    #wait for 4 seconds
    sleep(4)
    sendToChatAndConsole(mc, "Making nametags visible")
    mc.setting('nametags_visible', 1)
    #wait for 6 seconds
    sleep(6)
    sendToChatAndConsole(mc, "Making nametags invisible")
    mc.setting('nametags_visible', 0)
    #wait for 4 seconds
    sleep(4)
    sendToChatAndConsole(mc, "Set Camera to normal player first person")
    mc.camera.setNormal(1)

<commit_msg>Add player setting to example<commit_after>#import the needed modules fo communication with minecraft world
from mcpi.minecraft import *
# import needed block defintiions
from mcpi.block import DIAMOND_BLOCK
# needed to slow down the wall building
from time import sleep
# needed to generate a random number for the colour of wool
from random import randint

def sendToChatAndConsole(minecraft, message):

    # print to the python interpreter standard output (terminal or IDLE probably)
    print(message)
    # send message to the minecraft chat
    minecraft.postToChat(message)

if __name__ == "__main__":
    #    First thing you do is create a connection to minecraft
    #    This is like dialling a phone.
    #    It sets up a communication line between your script and the minecraft world

    # Create a connection to Minecraft
    # Any communication with the world must use this object
    mc = Minecraft.create()

    sendToChatAndConsole(mc, "Saving Checkpoint")
    #Save a checkpoint for the world state
    mc.saveCheckpoint()

    #wait for 2 seconds
    sleep(2)
    sendToChatAndConsole(mc, "Building Wall");
    # Get the player position
    playerPosition = mc.player.getTilePos()

    wallStartXposn = playerPosition.x + 6
    wallStartYposn = playerPosition.y + 1
    wallZposn      = playerPosition.z + 6

    wallEndXposn = wallStartXposn + 10
    wallEndYposn = wallStartYposn + 6

    # Create a wall
    mc.setBlocks(wallStartXposn , wallStartYposn, wallZposn, \
                   wallEndXposn,    wallEndYposn,   wallZposn, \
                   DIAMOND_BLOCK)

    #wait for 4 seconds
    sleep(4)

    sendToChatAndConsole(mc, "Restoring Checkpoint")
    # Set the world back to the state it was in at the last saved checkpoint
    mc.restoreCheckpoint()

    sendToChatAndConsole(mc, "Making World unbreakable")
    mc.setting('world_immutable', 1)
    #wait for 8 seconds
    sleep(8)
    sendToChatAndConsole(mc, "Making World breakable")
    mc.setting('world_immutable', 0)
    #wait for 4 seconds
    sleep(4)
    #Follow the player
    sendToChatAndConsole(mc, "Set Camera to follow the player")
    mc.camera.setFollow(1)
    #wait for 4 seconds
    sleep(4)
    sendToChatAndConsole(mc, "Making nametags visible")
    mc.setting('nametags_visible', 1)
    #wait for 6 seconds
    sleep(6)
    sendToChatAndConsole(mc, "Making nametags invisible")
    mc.setting('nametags_visible', 0)
    #wait for 4 seconds
    sleep(4)
    sendToChatAndConsole(mc, "Set Camera to normal player first person")
    mc.camera.setNormal(1)
    #wait for 2 seconds
    sleep(2)
    sendToChatAndConsole(mc, "Turning off AutoJump")
    mc.player.setting('autojump', 0)
    #wait for 8 seconds
    sleep(8)
    sendToChatAndConsole(mc, "Turning on AutoJump")
    mc.player.setting('autojump', 1)

<|endoftext|>


<commit_before>import hexchat
import os
import time
import json
import requests
import threading
import traceback
from random import randint
import twitch.api, twitch.emotes, twitch.normalize, twitch.logger
import twitch.settings
from twitch.exceptions import NetworkFailure
from twitch import irc
log = twitch.logger.get()

# map channel user modes to user attributes
user_mode_attrs = {
	"o": "mod",
}

# what fields from Twitch API JSON to copy to what attributes of user
twitchattrs = {
	"display_name": "displayName",
	"created_at":   "createdAt",
	"updated_at":   "updatedAt",
	"logo":         "logo",
	"bio":          "bio",
}

# where to store our cache files
cachedir = os.path.join(
	hexchat.get_info("configdir"), "addons", "twitch", "cache", "users")
try:
	os.makedirs(cachedir)
except FileExistsError:
	pass

# map message types to highlight versions
msg_hilight_types = {
	'Channel Message': 'Channel Msg Hilight',
	'Channel Action':  'Channel Action Hilight',
}

# represents a user in Twitch IRC
class user(object):
	def __init__(self, nick):
		nick = twitch.normalize.nick(nick)

		# global attributes
		self.nick        = nick
		self.displayName = nick
		self.color       = None
		self.irc_color   = randint(0, 15)
		self.emoteSet    = None
		self.createdAt   = None
		self.updatedAt   = None
		self.logo        = None
		self.bio         = None
		self.attributes  = {
			"turbo":      False,
			"global_mod": False,
			"staff":      False,
			"admin":      False,
			"bot":        False, # not set by Twitch; we set this automatically
			# for some known bots, and user can set it as well.
		}
		self.chanAttrs = {} # per-channel attributes
		self.lookup() # get info from API or cache

	def __str__(self):
		return "twitch.user(%s)" % self.nick

	# Look up more info about this user.
	def lookup(self):
		data = None
		path = os.path.join(cachedir, self.nick)
		try:
			# read the saved .json file for this user
			with open(path) as f:
				# log.debug("%s.lookup cache hit" % str(self))
				data = json.load(f)
				for k, v in data.items(): #merge this into ourself
					setattr(self, k, v)

			# old versions saved chanAttrs but shouldn't, so clear it here.
			self.chanAttrs = {}
		except FileNotFoundError:
			# we don't have a saved .json file for this user,
			# so we need to fetch their info from Twitch
			log.debug("%s.lookup cache miss" % str(self))
			self.lookupAPI()

	# Look up this user in Twitch API (in a separate thread).
	def lookupAPI(self):
		here = str(self) + ".lookupAPI.thread"
		def thread():
			log.debug("%s: started" % here)
			while True: # repeat until success
				try:
					data = twitch.api.getUser(self.nick)
					log.debug("%s: data: %s" % (here, data))
					for src, dst in twitchattrs.items(): # merge into self
						if src in data:
							setattr(self, dst, data[src])
					log.debug("%s: Set attrs OK" % here)
					self.save()
					log.debug("%s: done" % here)
					return
				except NetworkFailure:
					log.debug("%s: network error; retrying" % here)
					time.sleep(60) # wait and try again.
				except:
					log.exception("Unhandled exception in %s" % here)
					return
		# end of thread()

		t = threading.Thread(
			target = thread,
			args   = (),
			name   = "%s.lookup" % self,
			daemon = True)
		t.start()
	# end of lookupAPI()

	# Dump this user to a local JSON file so we don't have to look them up
	# again next time we run hexchat.
	def save(self):
		#stack  = traceback.extract_stack()
		#frames = []
		## (filename, line number, function name, text)
		#frames.extend(map(lambda f: "{0}:{1}: in '{2}': {3}".format(*f), stack))
		#log.debug("%s.save called from:\n\t%s" %
		#	(str(self), "\n\t".join(frames)))
		path = os.path.join(cachedir, self.nick)
		#log.debug("%s.save(%s)" % (self, path))

		# HACK XXX there must be a better way to do this
		chanAttrs = self.chanAttrs
		del self.chanAttrs
		with open(path, 'w') as f:
			json.dump(self.__dict__, f)
		self.chanAttrs = chanAttrs
		log.debug("%s.save OK" % self)

	# Set RGB nick colour (from USERCOLOR message).
	# Will map to the closest matching IRC colour.
	def setColor(self, col):
		if col != self.color:
			self.color     = col
			self.irc_color = irc.mapColor(col)
			self.save()

	# Get a dict of the user's types, with settings for that type as value
	def getTypes(self, chan):
		types     = {}
		attrs     = self.getChanAttrs(chan)
		usertypes = twitch.settings.get('usertypes')

		# iterate attrs where value == True
		for attr in filter(lambda v: attrs[v], attrs):
			types[attr] = usertypes.get(attr, {})

		return types

	# Get a list of name badges this user should have
	def getNameBadges(self, chan):
		badges = []
		for name, utype in self.getTypes(chan).items():
			if 'badge' in utype:
				badges.append(irc.format(utype['badge']))
		return badges

	# Get the actual message type we should use for a message from this user
	def getMsgType(self, chan, msgtype):
		if msgtype in msg_hilight_types: # if this msgtype can be hilighted
			for name, utype in self.getTypes(chan).items():
				if utype.get('hilight', False):
					tp = msg_hilight_types[msgtype]
					return tp
		return msgtype

	# Get formatted nick for displaying in given channel.
	# Includes badges and colours.
	def getPrettyNick(self, chan):
		badges = self.getNameBadges(chan)
		return "".join(badges + [irc.color(self.irc_color), self.displayName])

	# Format message text for displaying in given channel.
	def formatMessageText(self, chan, text):
		text = twitch.emotes.insert(text)
		for name, utype in self.getTypes(chan).items():
			if 'format' in utype:
				text = irc.format(utype['format'].format(text))
		return text

	# Print user's chat message in channel.
	def printMessage(self, chan, text, msgtype):
		chan      = twitch.channel.get(chan)
		text      = self.formatMessageText(chan, text)
		usertypes = twitch.settings.get('usertypes')
		msgtype   = self.getMsgType(chan, msgtype)
		chan.emit_print(msgtype, self.getPrettyNick(chan), text)

	# Add user to a channel if they aren't there already.
	def joinChannel(self, chan):
		chan = twitch.channel.get(chan)
		if chan.name in self.chanAttrs:
			return

		log.debug("User '%s' joined channel '%s'" % (self.nick, chan.name))
		self.chanAttrs[chan.name] = {
			"broadcaster": False,
			"subscriber":  False,
			"mod":         False,
		}

		# synthesize a JOIN event to make sure hexchat knows about this user,
		# so that tab complete and user list will work.
		cmd = "RECV :{0}!{0}@{0}{2}.tmi.twitch.tv JOIN #{1}".format(
			self.nick, chan.name, ".twitch.hexchat.please.stop.being.butts")
		log.debug(cmd)
		hexchat.command(cmd)

		chan.addUser(self)

	# Remove user from a channel if they're there
	def leaveChannel(self, chan):
		chan = twitch.channel.get(chan)
		if chan.name not in self.chanAttrs:
			return

		log.debug("User '%s' left channel '%s'" % (self.nick, chan.name))
		cmd = "RECV :{0}!{0}@{0}.tmi.twitch.tv PART #{1}".format(
			self.nick, chan.name)
		log.debug(cmd)
		hexchat.command(cmd)
		del self.chanAttrs[chan.name]
		chan.removeUser(self)

	# Set a channel attribute for this user.
	def setChanAttr(self, chan, attr, val):
		chan = twitch.channel.get(chan)
		self.joinChannel(chan)

		if self.chanAttrs[chan.name].get(attr) != val:
			self.chanAttrs[chan.name][attr] = val
			self.save() # avoid excessive saving

	# Get channel attributes for this user.
	def getChanAttrs(self, chan):
		chan = twitch.channel.get(chan).name

		# create entry for this channel if not existing
		if chan not in self.chanAttrs:
			self.joinChannel(chan)
			#self.chanAttrs[chan] = {}

		attrs = self.attributes.copy()
		attrs.update(self.chanAttrs[chan]) # merge
		return attrs

	# Set an IRC channel mode for this user.
	def setChannelMode(self, chan, mode, val):
		if mode in user_mode_attrs:
			attr = user_mode_attrs[mode]
			self.setChanAttr(chan, attr, val)
		else:
			log.warn("Unrecognized user mode '%s'" % mode)

	# Set single global attribute.
	def setAttr(self, attr, val):
		if self.attributes.get(attr) != val:
			self.attributes[attr] = val
			self.save()

	# Set global attributes.
	def setAttrs(self, attrs):
		changed = False
		for k, v in attrs.items():
			if self.attributes.get(k) != v:
				self.attributes[k] = v
				changed = True
		if changed:
			self.save()

# users we know about (nick => obj)
users = {}

# look up user by nick; create if not existing
def get(nick):
	if type(nick) is user:
		return nick
	nick = twitch.normalize.nick(nick)

	if nick not in users:
		#stack  = traceback.extract_stack()
		#frames = []
		## (filename, line number, function name, text)
		#frames.extend(map(lambda f: "{0}:{1}: in '{2}': {3}".format(*f), stack))

		#log.debug("user.create(%s) from:\n\t%s" % (nick, "\n\t".join(frames)))
		u = user(nick)
		users[nick] = u
	return users[nick]
<commit_msg>user: add ability to prevent creating the object when looking up a user<commit_after>import hexchat
import os
import time
import json
import requests
import threading
import traceback
from random import randint
import twitch.api, twitch.emotes, twitch.normalize, twitch.logger
import twitch.settings
from twitch.exceptions import NetworkFailure
from twitch import irc
log = twitch.logger.get()

# map channel user modes to user attributes
user_mode_attrs = {
	"o": "mod",
}

# what fields from Twitch API JSON to copy to what attributes of user
twitchattrs = {
	"display_name": "displayName",
	"created_at":   "createdAt",
	"updated_at":   "updatedAt",
	"logo":         "logo",
	"bio":          "bio",
}

# where to store our cache files
cachedir = os.path.join(
	hexchat.get_info("configdir"), "addons", "twitch", "cache", "users")
try:
	os.makedirs(cachedir)
except FileExistsError:
	pass

# map message types to highlight versions
msg_hilight_types = {
	'Channel Message': 'Channel Msg Hilight',
	'Channel Action':  'Channel Action Hilight',
}

# represents a user in Twitch IRC
class user(object):
	def __init__(self, nick):
		nick = twitch.normalize.nick(nick)

		# global attributes
		self.nick        = nick
		self.displayName = nick
		self.color       = None
		self.irc_color   = randint(0, 15)
		self.emoteSet    = None
		self.createdAt   = None
		self.updatedAt   = None
		self.logo        = None
		self.bio         = None

		# Twitch user type flags
		# "bot" isn't set by Twitch; this script sets it for some known bots,
		# and the user can manually set it. It's included here because it's
		# considered a user type flag and (by default) we have a nick prefix
		# for it like we do for the others.
		self.attributes  = {
			"turbo":      False,
			"global_mod": False,
			"staff":      False,
			"admin":      False,
			"bot":        False,
		}
		self.chanAttrs = {} # per-channel attributes
		self.lookup() # get info from API or cache

	def __str__(self):
		return "twitch.user(%s)" % self.nick

	# Look up more info about this user.
	def lookup(self):
		data = None
		path = os.path.join(cachedir, self.nick)
		try:
			# read the saved .json file for this user
			with open(path) as f:
				# log.debug("%s.lookup cache hit" % str(self))
				data = json.load(f)
				for k, v in data.items(): #merge this into ourself
					setattr(self, k, v)

			# old versions saved chanAttrs but shouldn't, so clear it here.
			self.chanAttrs = {}
		except FileNotFoundError:
			# we don't have a saved .json file for this user,
			# so we need to fetch their info from Twitch
			log.debug("%s.lookup cache miss" % str(self))
			self.lookupAPI()

	# Look up this user in Twitch API (in a separate thread).
	def lookupAPI(self):
		here = str(self) + ".lookupAPI.thread"
		def thread():
			log.debug("%s: started" % here)
			while True: # repeat until success
				try:
					data = twitch.api.getUser(self.nick)
					log.debug("%s: data: %s" % (here, data))
					for src, dst in twitchattrs.items(): # merge into self
						if src in data:
							setattr(self, dst, data[src])
					log.debug("%s: Set attrs OK" % here)
					self.save()
					log.debug("%s: done" % here)
					return
				except NetworkFailure:
					log.debug("%s: network error; retrying" % here)
					time.sleep(60) # wait and try again.
				except:
					log.exception("Unhandled exception in %s" % here)
					return
		# end of thread()

		t = threading.Thread(
			target = thread,
			args   = (),
			name   = "%s.lookup" % self,
			daemon = True)
		t.start()
	# end of lookupAPI()

	# Dump this user to a local JSON file so we don't have to look them up
	# again next time we run hexchat.
	def save(self):
		#stack  = traceback.extract_stack()
		#frames = []
		## (filename, line number, function name, text)
		#frames.extend(map(lambda f: "{0}:{1}: in '{2}': {3}".format(*f), stack))
		#log.debug("%s.save called from:\n\t%s" %
		#	(str(self), "\n\t".join(frames)))
		path = os.path.join(cachedir, self.nick)
		#log.debug("%s.save(%s)" % (self, path))

		# HACK XXX there must be a better way to do this
		chanAttrs = self.chanAttrs
		del self.chanAttrs
		with open(path, 'w') as f:
			json.dump(self.__dict__, f)
		self.chanAttrs = chanAttrs
		log.debug("%s.save OK" % self)

	# Set RGB nick colour (from USERCOLOR message).
	# Will map to the closest matching IRC colour.
	def setColor(self, col):
		if col != self.color:
			self.color     = col
			self.irc_color = irc.mapColor(col)
			self.save()

	# Get a dict of the user's types, with settings for that type as value
	def getTypes(self, chan):
		types     = {}
		attrs     = self.getChanAttrs(chan)
		usertypes = twitch.settings.get('usertypes')

		# iterate attrs where value == True
		for attr in filter(lambda v: attrs[v], attrs):
			types[attr] = usertypes.get(attr, {})

		return types

	# Get a list of name badges this user should have
	def getNameBadges(self, chan):
		badges = []
		for name, utype in self.getTypes(chan).items():
			if 'badge' in utype:
				badges.append(irc.format(utype['badge']))
		return badges

	# Get the actual message type we should use for a message from this user
	def getMsgType(self, chan, msgtype):
		if msgtype in msg_hilight_types: # if this msgtype can be hilighted
			for name, utype in self.getTypes(chan).items():
				if utype.get('hilight', False):
					tp = msg_hilight_types[msgtype]
					return tp
		return msgtype

	# Get formatted nick for displaying in given channel.
	# Includes badges and colours.
	def getPrettyNick(self, chan):
		badges = self.getNameBadges(chan)
		return "".join(badges + [irc.color(self.irc_color), self.displayName])

	# Format message text for displaying in given channel.
	def formatMessageText(self, chan, text):
		text = twitch.emotes.insert(text)
		for name, utype in self.getTypes(chan).items():
			if 'format' in utype:
				text = irc.format(utype['format'].format(text))
		return text

	# Print user's chat message in channel.
	def printMessage(self, chan, text, msgtype):
		chan      = twitch.channel.get(chan)
		text      = self.formatMessageText(chan, text)
		usertypes = twitch.settings.get('usertypes')
		msgtype   = self.getMsgType(chan, msgtype)
		chan.emit_print(msgtype, self.getPrettyNick(chan), text)

	# Add user to a channel if they aren't there already.
	def joinChannel(self, chan):
		chan = twitch.channel.get(chan)
		if chan.name in self.chanAttrs:
			return

		log.debug("User '%s' joined channel '%s'" % (self.nick, chan.name))
		self.chanAttrs[chan.name] = {
			"broadcaster": False,
			"subscriber":  False,
			"mod":         False,
		}

		# synthesize a JOIN event to make sure hexchat knows about this user,
		# so that tab complete and user list will work.
		cmd = "RECV :{0}!{0}@{0}{2}.tmi.twitch.tv JOIN #{1}".format(
			self.nick, chan.name, ".twitch.hexchat.please.stop.being.butts")
		log.debug(cmd)
		hexchat.command(cmd)

		chan.addUser(self)

	# Remove user from a channel if they're there
	def leaveChannel(self, chan):
		chan = twitch.channel.get(chan)
		if chan.name not in self.chanAttrs:
			return

		log.debug("User '%s' left channel '%s'" % (self.nick, chan.name))
		cmd = "RECV :{0}!{0}@{0}.tmi.twitch.tv PART #{1}".format(
			self.nick, chan.name)
		log.debug(cmd)
		hexchat.command(cmd)
		del self.chanAttrs[chan.name]
		chan.removeUser(self)

	# Set a channel attribute for this user.
	def setChanAttr(self, chan, attr, val):
		chan = twitch.channel.get(chan)
		self.joinChannel(chan)

		if self.chanAttrs[chan.name].get(attr) != val:
			self.chanAttrs[chan.name][attr] = val
			self.save() # avoid excessive saving

	# Get channel attributes for this user.
	def getChanAttrs(self, chan):
		chan = twitch.channel.get(chan).name

		# create entry for this channel if not existing
		if chan not in self.chanAttrs:
			self.joinChannel(chan)
			#self.chanAttrs[chan] = {}

		attrs = self.attributes.copy()
		attrs.update(self.chanAttrs[chan]) # merge
		return attrs

	# Set an IRC channel mode for this user.
	def setChannelMode(self, chan, mode, val):
		if mode in user_mode_attrs:
			attr = user_mode_attrs[mode]
			self.setChanAttr(chan, attr, val)
		else:
			log.warn("Unrecognized user mode '%s'" % mode)

	# Set single global attribute.
	def setAttr(self, attr, val):
		if self.attributes.get(attr) != val:
			self.attributes[attr] = val
			self.save()

	# Set global attributes.
	def setAttrs(self, attrs):
		changed = False
		for k, v in attrs.items():
			if self.attributes.get(k) != v:
				self.attributes[k] = v
				changed = True
		if changed:
			self.save()

# users we know about (nick => obj)
users = {}

# look up user by nick; create if not existing unless create=False
def get(nick, create=True):
	if type(nick) is user:
		return nick
	nick = twitch.normalize.nick(nick)

	if nick not in users:
		if not create:
			return None
		#stack  = traceback.extract_stack()
		#frames = []
		## (filename, line number, function name, text)
		#frames.extend(map(lambda f: "{0}:{1}: in '{2}': {3}".format(*f), stack))

		#log.debug("user.create(%s) from:\n\t%s" % (nick, "\n\t".join(frames)))
		u = user(nick)
		users[nick] = u
	return users[nick]

<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup
import urllib2
import re
import arrow
import config
from jinja2 import Template

class Tweet(object):

    def __init__(self, text, meta, get_pics=False):
        self.raw_text = str(text).decode('UTF-8')
        self.set_info(meta)
        self.get_pics = get_pics

    def set_info(self, meta):
        for href in meta.findAll('a'):
            self.link = re.sub(r'\(u\'href\', u\'(.*)\'\)', r'\1', str(
                href.attrs[0]))

            span = meta.find('span')
            timestamp = re.sub(r'\(u\'data-time\', u\'(.*)\'\)', r'\1', str(span.attrs[1]))

            self.date = self.clean_timestamp(timestamp)
            self.author = self.link.split('/')[1]

    def __repr__(self):
        return '<Tweet "{text}"" at {date}'.format(text=self.__str__(), date=self.date)

    def __str__(self):
        return self.clean_text(True)

    def clean_text(self):
        output = self.raw_text

        to_delete = self.TWIT_DELETE
        to_replace = [{'<s>@</s>': '@'},
                      {'href="/': 'href="http://twitter.com/'}]
        for item in to_delete:
            output = re.sub(item, '', output)
        for item in to_replace:
            for old, new in item.items():
                output = re.sub(old, new, output)

        title = output
        to_delete = self.TWEET_DELETE
        for item in to_delete:
            title = re.sub(item, '', title)

        return [output, title]

    def get_pic(self):
        pic = None
        if 'pic.twitter.com' in self.raw_text:
            pic_url = 'http://' + str(re.sub(r'.*dir="ltr">pic.twitter.com/(.*?).*', r'pic.twitter.com/\1', self.raw_text.encode('utf8')))

            content = urllib2.urlopen(pic_url)
            soup = BeautifulSoup(content)
            pic = re.findall(r'(https?://pbs.twimg.com/media/\S+.\S+:large)', str(soup))[0]
        return pic

    def clean_timestamp(self,timestamp):
        return arrow.Arrow.fromtimestamp(float(timestamp))

    def to_jinja2(self):
        template = {
                'title' : self.clean_text()[1],
                'author'  : self.author,
                'link' : self.link,
                'date' : self.date.strftime('%a, %d %b %Y %H:%M:%S %z'),
                'content' : self.clean_text()[0]
            }
        if config.PICS is True and self.get_pic() != None:
            template.update({'pic' : self.get_pic()})
        return template

    TWIT_DELETE = [
        ' class="js-tweet-text tweet-text"',
        ' class="twitter-atreply pretty-link"',
        ' class="invisible"',
        ' class="js-display-url"',
        ' class="twitter-hashtag pretty-link js-nav"',
        ' class="twitter-timeline-link"',
        ' class="tco-ellipsis"',
        ' class="invisible"',
        ' data-query-source="hashtag_click"',
        ' rel="nofollow"',
        ' target="_blank"',
        ' data-expanded-url=".*?"',
        ' title=".*?"',
        ' data-query-source="hashtag_click"',
        ' dir="ltr"',
        ' .*',
        'http://',
        ' data-pre-embedded="true"',
        '
', '
', '', '', '', '']

    TWEET_DELETE = [
        '
', '
', r'', '<s>', '</s>', r'http://twitter.com/search\?q=.*?&src=hash',
        '', '', '', '', '']

class TweetGetter(object):

    def parse_twitter(self):
        try:
            content = urllib2.urlopen(self.url)
            print 'Connection successful!'
            soup = BeautifulSoup(content)

            self.title = soup.title.string
            self.tweets = []

            for content in soup.findAll("div", "content"):
                for meta, text in zip(content.findAll("small", "time"), content.findAll("p", "js-tweet-text tweet-text")):
                    self.tweets.append(Tweet(text, meta))
        except urllib2.HTTPError:
            print 'Error 404: Account not found'

    def to_rss(self, server=config.SERVER):
        try:
            with open(config.INSTALL_DIR + 'rss-model.tpl') as template_file:
                items = list(map(lambda tweet: tweet.to_jinja2(), self.tweets))
                try:
                    descriptor = self.hashtag
                    directory = 'htag'
                except AttributeError:
                    descriptor = self.username
                    directory = 'user'
                template = Template(template_file.read())
                return template.render(server=server, directory=directory, descriptor=descriptor, title=self.title, url=self.url, tweets=items)
        except IOError:
            return 'Template could not be open'

class UserTweetGetter(TweetGetter):
    def __init__(self, username, get_pics = False):
        self.username = username
        self.url = "https://twitter.com/{0}".format(self.username)

        self.parse_twitter()

class HashtagTweetGetter(TweetGetter):
    def __init__(self, hashtag, get_pics = False):
        self.hashtag = hashtag
        self.url = "https://twitter.com/search?q=%23{0}".format(self.hashtag)

        self.parse_twitter()
<commit_msg>urllib2 replaced by requests<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup
import requests
import re
import arrow
import config
from jinja2 import Template

class Tweet(object):

    def __init__(self, text, meta, get_pics=False):
        self.raw_text = str(text).decode('UTF-8')
        self.set_info(meta)
        self.get_pics = get_pics

    def set_info(self, meta):
        for href in meta.findAll('a'):
            self.link = re.sub(r'\(u\'href\', u\'(.*)\'\)', r'\1', str(
                href.attrs[0]))

            span = meta.find('span')
            timestamp = re.sub(r'\(u\'data-time\', u\'(.*)\'\)', r'\1', str(span.attrs[1]))

            self.date = self.clean_timestamp(timestamp)
            self.author = self.link.split('/')[1]

    def __repr__(self):
        return '<Tweet "{text}"" at {date}'.format(text=self.__str__(), date=self.date)

    def __str__(self):
        return self.clean_text(True)

    def clean_text(self):
        output = self.raw_text

        to_delete = self.TWIT_DELETE
        to_replace = [{'<s>@</s>': '@'},
                      {'href="/': 'href="http://twitter.com/'}]
        for item in to_delete:
            output = re.sub(item, '', output)
        for item in to_replace:
            for old, new in item.items():
                output = re.sub(old, new, output)

        title = output
        to_delete = self.TWEET_DELETE
        for item in to_delete:
            title = re.sub(item, '', title)

        return [output, title]

    def get_pic(self):
        pic = None
        if 'pic.twitter.com' in self.raw_text:
            pic_url = 'http://' + str(re.sub(r'.*dir="ltr">pic.twitter.com/(.*?).*', r'pic.twitter.com/\1', self.raw_text.encode('utf8')))

            content = requests.get(pic_url)
            soup = BeautifulSoup(content.text)
            pic = re.findall(r'(https?://pbs.twimg.com/media/\S+.\S+:large)', str(soup))[0]
        return pic

    def clean_timestamp(self,timestamp):
        return arrow.Arrow.fromtimestamp(float(timestamp))

    def to_jinja2(self):
        template = {
                'title' : self.clean_text()[1],
                'author'  : self.author,
                'link' : self.link,
                'date' : self.date.strftime('%a, %d %b %Y %H:%M:%S %z'),
                'content' : self.clean_text()[0]
            }
        if config.PICS is True and self.get_pic() != None:
            template.update({'pic' : self.get_pic()})
        return template

    TWIT_DELETE = [
        ' class="js-tweet-text tweet-text"',
        ' class="twitter-atreply pretty-link"',
        ' class="invisible"',
        ' class="js-display-url"',
        ' class="twitter-hashtag pretty-link js-nav"',
        ' class="twitter-timeline-link"',
        ' class="tco-ellipsis"',
        ' class="invisible"',
        ' data-query-source="hashtag_click"',
        ' rel="nofollow"',
        ' target="_blank"',
        ' data-expanded-url=".*?"',
        ' title=".*?"',
        ' data-query-source="hashtag_click"',
        ' dir="ltr"',
        ' .*',
        'http://',
        ' data-pre-embedded="true"',
        '
', '
', '', '', '', '']

    TWEET_DELETE = [
        '
', '
', r'', '<s>', '</s>', r'http://twitter.com/search\?q=.*?&src=hash',
        '', '', '', '', '']

class TweetGetter(object):

    def parse_twitter(self):
        try:
            content = requests.get(self.url)
            if content.status_code == 404:
                raise requests.HTTPError
            print 'Connection successful!'
            soup = BeautifulSoup(content.text)

            self.title = soup.title.string
            self.tweets = []

            for content in soup.findAll("div", "content"):
                for meta, text in zip(content.findAll("small", "time"), content.findAll("p", "js-tweet-text tweet-text")):
                    self.tweets.append(Tweet(text, meta))
        except requests.HTTPError:
            print 'Error 404: Account not found'

    def to_rss(self, server=config.SERVER):
        try:
            with open(config.INSTALL_DIR + 'rss-model.tpl') as template_file:
                items = list(map(lambda tweet: tweet.to_jinja2(), self.tweets))
                try:
                    descriptor = self.hashtag
                    directory = 'htag'
                except AttributeError:
                    descriptor = self.username
                    directory = 'user'
                template = Template(template_file.read())
                return template.render(server=server, directory=directory, descriptor=descriptor, title=self.title, url=self.url, tweets=items)
        except IOError:
            return 'Template could not be open'

class UserTweetGetter(TweetGetter):
    def __init__(self, username, get_pics = False):
        self.username = username
        self.url = "https://twitter.com/{0}".format(self.username)

        self.parse_twitter()

class HashtagTweetGetter(TweetGetter):
    def __init__(self, hashtag, get_pics = False):
        self.hashtag = hashtag
        self.url = "https://twitter.com/search?q=%23{0}".format(self.hashtag)

        self.parse_twitter()
<|endoftext|>


<commit_before>from .git_cloner import clone
from .model_loader import ModelLoader

def get_model(url):
    """

    Provides utilities to download foolbox-compatible robust models
    to easily test attacks against them by simply providing a git-URL.

    Examples
    --------

    Instantiate a model:

    >>> from foolbox import zoo
    >>> url = "https://github.com/bveliqi/foolbox-zoo-dummy.git"
    >>> model = zoo.get_model(url)  # doctest: +SKIP

    Only works with a foolbox-zoo compatible repository.
    I.e. models need to have a `foolbox_model.py` file
    with a `create()`-function, which returns a foolbox-wrapped model.

    Example repositories:

        - https://github.com/bethgelab/AnalysisBySynthesis
        - https://github.com/bethgelab/mnist_challenge
        - https://github.com/bethgelab/cifar10_challenge
        - https://github.com/bethgelab/convex_adversarial

    :param url: URL to the git repository
    :return: a foolbox-wrapped model instance
    """
    repo_path = clone(url)
    loader = ModelLoader.get()
    model = loader.load(repo_path)

    return model
<commit_msg>Added logit pairing to zoo<commit_after>from .git_cloner import clone
from .model_loader import ModelLoader

def get_model(url):
    """

    Provides utilities to download foolbox-compatible robust models
    to easily test attacks against them by simply providing a git-URL.

    Examples
    --------

    Instantiate a model:

    >>> from foolbox import zoo
    >>> url = "https://github.com/bveliqi/foolbox-zoo-dummy.git"
    >>> model = zoo.get_model(url)  # doctest: +SKIP

    Only works with a foolbox-zoo compatible repository.
    I.e. models need to have a `foolbox_model.py` file
    with a `create()`-function, which returns a foolbox-wrapped model.

    Example repositories:

        - https://github.com/bethgelab/AnalysisBySynthesis
        - https://github.com/bethgelab/mnist_challenge
        - https://github.com/bethgelab/cifar10_challenge
        - https://github.com/bethgelab/convex_adversarial
        - https://github.com/wielandbrendel/logit-pairing-foolbox.git

    :param url: URL to the git repository
    :return: a foolbox-wrapped model instance
    """
    repo_path = clone(url)
    loader = ModelLoader.get()
    model = loader.load(repo_path)

    return model
<|endoftext|>


<commit_before>from functools import wraps
import logging
import re
import time

import six

from .exceptions import LcdCommandError

logger = logging.getLogger(__name__)

COMMANDS = {}

def command(fn):
    @wraps(fn)
    def wrapped(*args):
        self = args[0]
        logger.debug(
            'Executing %s%s',
            fn.func_name,
            args
        )
        response = fn(*args)
        logger.debug(
            'Response %s',
            response
        )
        if response:
            self.send_manager_data('response', response)
    COMMANDS[fn.func_name] = wrapped
    return fn

class CallableLcdCommand(object):
    def __init__(self, manager, command):
        self._manager = manager
        self._command = command

    def __call__(self, *args):
        result = self._command(*args)
        self._manager.send(result)

@six.python_2_unicode_compatible
class LcdCommand(object):
    COMMAND_PREFIX = '\xfe'

    def __init__(self, byte, args=None, prefix='\n'):
        if args is None:
            args = []

        self._byte = byte
        self._args = args
        self._prefix = prefix

    def build_command(self, *args):
        cmd = self.COMMAND_PREFIX

        if len(args) != len(self._args):
            raise LcdCommandError(
                "Argument count mismatch; expected {expected}, but "
                "only {actual} were received.".format(
                    expected=len(self._args),
                    actual=len(args),
                )
            )

        cmd += self._byte

        for idx, processor in enumerate(self._args):
            arg = args[idx]
            cmd += str(processor(arg))

        return cmd

    def __call__(self, *args):
        return self.build_command(*args)

    def __str__(self):
        return u'LCD Command "{command}"'.format(
            command=self._byte.encode('string-escape')
        )

@six.python_2_unicode_compatible
class LcdClient(object):
    COMMANDS = {
        'on': LcdCommand('\x42', args=[chr]),
        'off': LcdCommand('\x46'),
        'set_brightness': LcdCommand('\x99', args=[chr]),
        'set_contrast': LcdCommand('\x50', args=[chr]),
        'enable_autoscroll': LcdCommand('\x51'),
        'disable_autoscroll': LcdCommand('\x52'),
        'clear': LcdCommand('\x58'),
        'set_splash_screen': LcdCommand('\x40', args=[str]),
        'set_cursor_position': LcdCommand('\x47', args=[chr, chr]),
        'cursor_home': LcdCommand('\x48', prefix=''),
        'cursor_backward': LcdCommand('\x4c', prefix=''),
        'cursor_forward': LcdCommand('\x4d', prefix=''),
        'cursor_underline_on': LcdCommand('\x4a', prefix=''),
        'cursor_underline_off': LcdCommand('\x4b', prefix=''),
        'cursor_block_on': LcdCommand('\x53', prefix=''),
        'cursor_block_off': LcdCommand('\x54', prefix=''),
        'set_backlight_color': LcdCommand('\xd0', args=[chr, chr, chr]),
        'set_lcd_size': LcdCommand('\xd1', args=[chr, chr]),
        'gpo_off': LcdCommand('\x56'),
        'gpo_on': LcdCommand('\x57'),
    }

    def __init__(self, device_path):
        self.device_path = device_path

    def __getattr__(self, name):
        if name not in self.COMMANDS:
            raise AttributeError(name)

        return CallableLcdCommand(self, self.COMMANDS[name])

    def send(self, cmd):
        logger.debug(
            'Sending command: "%s"' % cmd.encode('string-escape')
        )
        try:
            with open(self.device_path, 'wb') as dev:
                dev.write(cmd)
        except IOError:
            logger.error(
                'Device unavailable; command \'%s\' dropped.',
                cmd
            )

    def send_text(self, text):
        self.send(text.encode('ascii', 'replace'))

    def __str__(self):
        return 'LCD Screen at {path}'.format(path=self.device_path)

class LcdManager(object):
    def __init__(
        self, device_path, pipe=None, size=None,
        blink_interval=0.25, text_cycle_interval=2, size_x=16, size_y=2
    ):
        self.client = LcdClient(device_path)

        self.pipe = pipe
        if not size:
            size = [16, 2]
        self.size = size

        self.message = ''
        self.message_lines = []
        self.color = 0, 0, 0
        self.backlight = True

        self.sleep = 0.1

        self.blink = []
        self.blink_idx = 0
        self.blink_counter = 0
        self.blink_interval = int(
            (1.0 / self.sleep) * blink_interval
        )

        self.text_idx = 0
        self.text_cycle_counter = 0
        self.text_cycle_interval = int(
            (1.0 / self.sleep) * text_cycle_interval
        )

    def initialize(self):
        self.client.disable_autoscroll()
        self.clear()

    def run(self):
        while True:
            if self.pipe.poll():
                cmd, args = self.pipe.recv()
                args.insert(0, self)
                if cmd in COMMANDS:
                    COMMANDS[cmd](*args)
                else:
                    logger.error(
                        'Received unknown command \'%s\' from manager.',
                        cmd
                    )
                    self.send_manager_data(
                        'error', 'Command %s does not exist' % cmd
                    )
            if self.blink_counter >= self.blink_interval:
                self.blink_counter = 0
                self.handle_blink()
            else:
                self.blink_counter += 1
            if self.text_cycle_counter >= self.text_cycle_interval:
                self.text_cycle_counter = 0
                self.handle_text_cycle()
            else:
                self.text_cycle_counter += 1
            time.sleep(self.sleep)

    def handle_text_cycle(self):
        if len(self.message_lines) <= self.text_idx:
            self.text_idx = 0

        self.client.cursor_home()
        cleaned_lines = [
            line.ljust(self.size[0])
            for line in self.message_lines[
                self.text_idx:self.text_idx+self.size[1]
            ]
        ]
        display_text = ''.join(cleaned_lines)[0:self.size[0]*self.size[1]]
        if not display_text:
            self.off()
        self.client.send_text(display_text)
        self.text_idx += 2

    def handle_blink(self):
        if not self.blink:
            return
        self.blink_idx += 1
        if len(self.blink) <= self.blink_idx:
            self.blink_idx = 0
        self.client.set_backlight_color(
            *self.blink[self.blink_idx]
        )

    def send_manager_data(self, msg, data=None):
        if not data:
            data = []
        if not isinstance(data, (list, tuple)):
            data = [data, ]
        self.pipe.send((
            msg, data
        ))

    def get_message_lines(self, message):
        lines = []
        original_lines = re.split('\r|\n', message)
        for line in original_lines:
            lines.extend(
                line[i:i+self.size[0]]
                for i in range(0, len(line), self.size[0])
            )
        return lines

    @command
    def set_contrast(self, value):
        logger.debug('Setting contrast to %s', value)
        self.client.set_contrast(value)

    @command
    def set_brightness(self, value):
        logger.debug('Setting brightness to %s', value)
        self.client.set_brightness(value)

    @command
    def message(self, message):
        # If the backlight is off, just turn it off and be done with it.
        if message['backlight'] != self.backlight and not message['backlight']:
            self.off()
            return

        if 'message' in message and self.message != message['message']:
            self.set_message(message['message'])

        if 'blink' in message and self.blink != message['blink']:
            self.set_blink(message['blink'])
        if not 'blink' in message:
            self.set_blink([])
        if not self.blink and message['color'] != self.color:
            self.set_backlight_color(message['color'])

        if message['backlight'] != self.backlight:
            if message['backlight']:
                self.on()
            else:
                self.off()

    @command
    def set_blink(self, colors):
        self.blink = colors
        self.blink_idx = 0
        if self.blink:
            self.set_backlight_color(self.blink[self.blink_idx])

    @command
    def set_message(self, message):
        logger.debug('Setting message \'%s\'', message)
        self.clear()
        self.text_idx = 0
        self.message = message.replace('\n', '')
        self.message_lines = self.get_message_lines(self.message)
        self.handle_text_cycle()

    @command
    def off(self, *args):
        logger.debug('Setting backlight to off')
        self.backlight = False
        self.client.off()

    @command
    def on(self, *args):
        logger.debug('Setting backlight to on')
        self.backlight = True
        self.client.on(255)

    @command
    def clear(self, *args):
        self.message = ''
        self.text_idx = 0
        self.message_lines = []
        self.client.clear()

    @command
    def set_backlight_color(self, color):
        logger.debug('Setting backlight color to %s', color)
        self.color = color
        self.client.set_backlight_color(*color)
<commit_msg>Handle message handling in a rather simpler way.<commit_after>from functools import wraps
import logging
import re
import time

import six

from .exceptions import LcdCommandError

logger = logging.getLogger(__name__)

COMMANDS = {}

def command(fn):
    @wraps(fn)
    def wrapped(*args):
        self = args[0]
        logger.debug(
            'Executing %s%s',
            fn.func_name,
            args
        )
        response = fn(*args)
        logger.debug(
            'Response %s',
            response
        )
        if response:
            self.send_manager_data('response', response)
    COMMANDS[fn.func_name] = wrapped
    return fn

class CallableLcdCommand(object):
    def __init__(self, manager, command):
        self._manager = manager
        self._command = command

    def __call__(self, *args):
        result = self._command(*args)
        self._manager.send(result)

@six.python_2_unicode_compatible
class LcdCommand(object):
    COMMAND_PREFIX = '\xfe'

    def __init__(self, byte, args=None, prefix='\n'):
        if args is None:
            args = []

        self._byte = byte
        self._args = args
        self._prefix = prefix

    def build_command(self, *args):
        cmd = self.COMMAND_PREFIX

        if len(args) != len(self._args):
            raise LcdCommandError(
                "Argument count mismatch; expected {expected}, but "
                "only {actual} were received.".format(
                    expected=len(self._args),
                    actual=len(args),
                )
            )

        cmd += self._byte

        for idx, processor in enumerate(self._args):
            arg = args[idx]
            cmd += str(processor(arg))

        return cmd

    def __call__(self, *args):
        return self.build_command(*args)

    def __str__(self):
        return u'LCD Command "{command}"'.format(
            command=self._byte.encode('string-escape')
        )

@six.python_2_unicode_compatible
class LcdClient(object):
    COMMANDS = {
        'on': LcdCommand('\x42', args=[chr]),
        'off': LcdCommand('\x46'),
        'set_brightness': LcdCommand('\x99', args=[chr]),
        'set_contrast': LcdCommand('\x50', args=[chr]),
        'enable_autoscroll': LcdCommand('\x51'),
        'disable_autoscroll': LcdCommand('\x52'),
        'clear': LcdCommand('\x58'),
        'set_splash_screen': LcdCommand('\x40', args=[str]),
        'set_cursor_position': LcdCommand('\x47', args=[chr, chr]),
        'cursor_home': LcdCommand('\x48', prefix=''),
        'cursor_backward': LcdCommand('\x4c', prefix=''),
        'cursor_forward': LcdCommand('\x4d', prefix=''),
        'cursor_underline_on': LcdCommand('\x4a', prefix=''),
        'cursor_underline_off': LcdCommand('\x4b', prefix=''),
        'cursor_block_on': LcdCommand('\x53', prefix=''),
        'cursor_block_off': LcdCommand('\x54', prefix=''),
        'set_backlight_color': LcdCommand('\xd0', args=[chr, chr, chr]),
        'set_lcd_size': LcdCommand('\xd1', args=[chr, chr]),
        'gpo_off': LcdCommand('\x56'),
        'gpo_on': LcdCommand('\x57'),
    }

    def __init__(self, device_path):
        self.device_path = device_path

    def __getattr__(self, name):
        if name not in self.COMMANDS:
            raise AttributeError(name)

        return CallableLcdCommand(self, self.COMMANDS[name])

    def send(self, cmd):
        logger.debug(
            'Sending command: "%s"' % cmd.encode('string-escape')
        )
        try:
            with open(self.device_path, 'wb') as dev:
                dev.write(cmd)
        except IOError:
            logger.error(
                'Device unavailable; command \'%s\' dropped.',
                cmd
            )

    def send_text(self, text):
        self.send(text.encode('ascii', 'replace'))

    def __str__(self):
        return 'LCD Screen at {path}'.format(path=self.device_path)

class LcdManager(object):
    def __init__(
        self, device_path, pipe=None, size=None,
        blink_interval=0.25, text_cycle_interval=2, size_x=16, size_y=2
    ):
        self.client = LcdClient(device_path)

        self.pipe = pipe
        if not size:
            size = [16, 2]
        self.size = size

        self.message = ''
        self.message_lines = []
        self.color = 0, 0, 0
        self.backlight = True

        self.sleep = 0.1

        self.blink = []
        self.blink_idx = 0
        self.blink_counter = 0
        self.blink_interval = int(
            (1.0 / self.sleep) * blink_interval
        )

        self.text_idx = 0
        self.text_cycle_counter = 0
        self.text_cycle_interval = int(
            (1.0 / self.sleep) * text_cycle_interval
        )

    def initialize(self):
        self.client.disable_autoscroll()
        self.clear()

    def run(self):
        while True:
            if self.pipe.poll():
                cmd, args = self.pipe.recv()
                args.insert(0, self)
                if cmd in COMMANDS:
                    COMMANDS[cmd](*args)
                else:
                    logger.error(
                        'Received unknown command \'%s\' from manager.',
                        cmd
                    )
                    self.send_manager_data(
                        'error', 'Command %s does not exist' % cmd
                    )
            if self.blink_counter >= self.blink_interval:
                self.blink_counter = 0
                self.handle_blink()
            else:
                self.blink_counter += 1
            if self.text_cycle_counter >= self.text_cycle_interval:
                self.text_cycle_counter = 0
                self.handle_text_cycle()
            else:
                self.text_cycle_counter += 1
            time.sleep(self.sleep)

    def handle_text_cycle(self):
        if len(self.message_lines) <= self.text_idx:
            self.text_idx = 0

        self.client.cursor_home()
        cleaned_lines = [
            line.ljust(self.size[0])
            for line in self.message_lines[
                self.text_idx:self.text_idx+self.size[1]
            ]
        ]
        display_text = ''.join(cleaned_lines)[0:self.size[0]*self.size[1]]
        if not display_text:
            self.off()
        self.client.send_text(display_text)
        self.text_idx += 2

    def handle_blink(self):
        if not self.blink:
            return
        self.blink_idx += 1
        if len(self.blink) <= self.blink_idx:
            self.blink_idx = 0
        self.client.set_backlight_color(
            *self.blink[self.blink_idx]
        )

    def send_manager_data(self, msg, data=None):
        if not data:
            data = []
        if not isinstance(data, (list, tuple)):
            data = [data, ]
        self.pipe.send((
            msg, data
        ))

    def get_message_lines(self, message):
        lines = []
        original_lines = re.split('\r|\n', message)
        for line in original_lines:
            lines.extend(
                line[i:i+self.size[0]]
                for i in range(0, len(line), self.size[0])
            )
        return lines

    @command
    def set_contrast(self, value):
        logger.debug('Setting contrast to %s', value)
        self.client.set_contrast(value)

    @command
    def set_brightness(self, value):
        logger.debug('Setting brightness to %s', value)
        self.client.set_brightness(value)

    @command
    def message(self, message):
        backlight = message.get('backlight', True)
        text = message.get('message', '')
        blink = message.get('blink', [])
        color = message.get('color', [255, 255, 255])

        # If the backlight is off, just turn it off and be done with it.
        if not backlight:
            self.off()
            return

        if self.message != text:
            self.set_message(text)

        if blink and self.blink != blink:
            self.set_blink(blink)
        if not blink:
            self.set_blink([])
        if (
            not self.blink and
            color != self.color
        ):
            self.set_backlight_color(color)

        if backlight != self.backlight:
            if backlight:
                self.on()
            else:
                self.off()

    @command
    def set_blink(self, colors):
        self.blink = colors
        self.blink_idx = 0
        if self.blink:
            self.set_backlight_color(self.blink[self.blink_idx])

    @command
    def set_message(self, message):
        logger.debug('Setting message \'%s\'', message)
        self.clear()
        self.text_idx = 0
        self.message = message.replace('\n', '')
        self.message_lines = self.get_message_lines(self.message)
        self.handle_text_cycle()

    @command
    def off(self, *args):
        logger.debug('Setting backlight to off')
        self.backlight = False
        self.client.off()

    @command
    def on(self, *args):
        logger.debug('Setting backlight to on')
        self.backlight = True
        self.client.on(255)

    @command
    def clear(self, *args):
        self.message = ''
        self.text_idx = 0
        self.message_lines = []
        self.client.clear()

    @command
    def set_backlight_color(self, color):
        logger.debug('Setting backlight color to %s', color)
        self.color = color
        self.client.set_backlight_color(*color)
<|endoftext|>


<commit_before>#!/usr/bin/env python
#######################################################################
#
#     Monary
#
#     Convert Mongo queries into Numpy column arrays
#
#     Copyright 2005-2010  David J. C. Beach
#     DJC Innovations LLC  http://www.djcinnovations.com
#
#     Licensed under the Apache License, Version 2.0 (the "License");
#     you may not use this file except in compliance with the License.
#     You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#     Unless required by applicable law or agreed to in writing, software
#     distributed under the License is distributed on an "AS IS" BASIS,
#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#     See the License for the specific language governing permissions and
#     limitations under the License.
#
#######################################################################

import operator

import pymongo
import numpy as np

OBJECTID_DTYPE = "|S12"

def column_arrays(query, fields, count=None, log=False):
    """Returns column arrays corresponding to the requested fields
       from documents in the given PyMongo query object.  Fields
       is a list of strings, written as "fieldname:typecode".
       Typecode should be a valid Numpy dtype, and must be present
       in every field.  The special typecode "id" may be used to
       extract and store ObjectIDs.

       If provided, 'count' is be the number of objects returned
       by the query.  If not provided, query.count() will be called
       to determine the appropriate value.

       This function returns a numpy.ma.masked_array() instance for
       each requested column.  If a field is not present in a record,
       or if its value is not compatible with the array type, then
       the corresponding element will be masked in the result.

       Example:

       column_arrays(collection.find(),
           ["_id:id", "name:10unicode", "age:int", "weight:float"])
       (Returns id, name, age, and weight columns.)
    """

    if count is None:
        count = query.count()

    getters_columns = [ _setup_field(field, count) for field in fields ]

    for i, record in enumerate(query):
        if log and i % 100000 == 0:
            print "... processing record %i / %i" % (i, count)
        for getter, column in getters_columns:
            try:
                column[i] = getter(record)
            except (KeyError, ValueError):
                column.mask[i] = True

    return [ column for getter, column in getters_columns ]

def _setup_field(field, count):
    fname, dtype = field.split(':', 1)

    if dtype == "id":
        getter = lambda record: record[fname].binary
        dtype = OBJECTID_DTYPE
    else:
        getter = operator.itemgetter(fname)

    array = np.zeros([count], dtype=dtype)
    mask = np.zeros([count], dtype=bool)
    storage = np.ma.masked_array(array, mask)

    return getter, storage

def insert_records(coll, valdict):
    fields_values = list(valdict.items())
    size = len(valdict.values()[0])
    if "_id" not in valdict:
        idcol = np.ma.masked_array(np.empty([count], dtype=OBJECTID_DTYPE), False)
        set_ids = True
    else:
        idcol = valdict["_id"]
    for i in xrange(size):
        record = { field: values[i] for field, values in fields_values }
        coll.insert(record)
        if set_ids:
            idcol[i] = record['_id']
    return idcol

def update_records(coll, wheredict, valdict):
    size = len(wheredict.values()[0])
    where_values = list(wheredict.items())
    set_values = list(valdict.items())
    for i in xrange(size):
        where = { field: values[i] for field, values in where_values }
        changes = { field: values[i] for field, values in set_values }
        coll.update(where, changes)
<commit_msg>Removed unneeded file.<commit_after><|endoftext|>