Exemplo n.º 1
0
	def _handleError(self, err=None, execInfo=None, caughtException=False):
		if not err:
			return

		self._errors += 1

		if not self.bail:
			colors('red', '\nError:\n')
			# if err is an actual error and not a string
			# and we have execInfo, print that instead
			if type(err) == Exception and execInfo:
				err = execInfo
			print str(err)

			# if the error is a caught exception
			# _finishTest won't have been called, so call it here
			if caughtException:
				return self._finishTest()
			return

		self._numTests = 0
		# if we have a callback, let that handle the errors
		if self._callback:
			self._callback(err, execInfo)
			self._callback = None
			return

		print ''
		if type(err) == str:
			raise Exception(err)
		raise err
Exemplo n.º 2
0
class printer:
    #
    red = colors.colors().red(1)
    white = colors.colors().white(0)
    green = colors.colors().green(1)
    blue = colors.colors().blue(1)
    end = colors.colors().reset()

    #
    def plus(self, string, flag="+"):
        print "%s[%s]%s %s%s%s" % (self.green, flag, self.end, self.white,
                                   string, self.end)

    def test(self, string, flag="*"):
        print "%s[%s]%s %s%s%s" % (self.blue, flag, self.end, self.blue,
                                   string, self.end)

    def error(self, string, flag="!"):
        print "%s[%s]%s %s%s%s" % (self.red, flag, self.end, self.red, string,
                                   self.end)

    def ip(self, string, flag="|"):
        print " %s%s%s  %s%s%s\n" % (self.green, flag, self.end, self.white,
                                     string, self.end)

    def info(self, string, color="g", flag="|"):
        if color == "g":
            print "\t  %s%s%s  %s%s%s" % (self.green, flag, self.end,
                                          self.white, string, self.end)
        if color == "r":
            print "\t  %s%s%s  %s%s%s" % (self.red, flag, self.end, self.red,
                                          string, self.end)
Exemplo n.º 3
0
		def runTest():
			# the callback is optional so we check if this test
			# needs one
			hasCallback = len(
				inspect.getargspec(testFunction).args) > 1

			erroredOnTest = True
			try:
				if hasCallback:
					self.callbackCalled = False
					functionThread = threading.Thread(
						target=startThread,
						args=(testFunction, tearDown)
						)
					functionThread.start()
					waitOnTest()
				else:
					testFunction()
					erroredOnTest = False
					tearDown()
			except Exception as err:
				if self.bail:
					colors('red', '\nError:\n')
					# try to run the tearDown even though we've
					# errored
					if erroredOnTest:
						tearDown()
					if hasattr(err, 'message') and \
						'\n' not in err.message:
						print traceback.format_exc()
						sys.exit()
					else:
						raise err
				# if we're not bailing, just handle the error
				self._handleError(err, traceback.format_exc(), caughtException=True)
Exemplo n.º 4
0
    def __init__(self, orchestra):
        self.orchestra = orchestra
        self.score = orchestra.score

        self.width = 800
        self.height = 600
        self.min_byte = min(orchestra.chunks, key=lambda chunk: chunk["begin"])["begin"]
        self.max_byte = max(orchestra.chunks, key=lambda chunk: chunk["end"])["end"]
        self._segments_being_played = {}
        self._zoom_selection_taking_place = False
        self._state = self.STOPPED
        self._reset_displayed_time()
        self._reset_displayed_bytes()
        self.chunks_and_score_display_list = None
        self.app = wx.App(False)
        self.unplayed_pen = wx.Pen(wx.LIGHT_GREY, width=2)
        self.peer_colors = [wx.Colour(r*255, g*255, b*255)
                            for (r,g,b,a) in colors.colors(len(orchestra.tr_log.peers))]
        self.player_pens = [wx.Pen(color, width=2)
                            for color in self.peer_colors]
        style = wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE
        wx.Frame.__init__(self, None, wx.ID_ANY, "Torrential Forms",
                          size=wx.Size(self.width, self.height), style=style)
        self.Bind(wx.EVT_SIZE, self._OnSize)
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER,self._on_timer)
        self._vbox = wx.BoxSizer(wx.VERTICAL)
        self._create_control_buttons()
        self._create_clock()
        self._create_layer_buttons()
        self._create_timeline()
        self.SetSizer(self._vbox)
        self.catch_key_events()
        self.Show()
        orchestra.gui = self
Exemplo n.º 5
0
    def spatialplot(self, file_name):
        #statetocolor = {'S':'k', 'E':'y', 'I':'r', 'H':'m', 'F':'c', 'R':'g', 'D':'b'}

        legend = colors()
        categories = [[[] for j in range(2)] for i in range(7)]

        fig, ax = plt.subplots(figsize=(10,10))
        for z in self.pop:
            categories[statetonum[z.state]][0].append(random.gauss(z.pos.y,.5))
            categories[statetonum[z.state]][1].append(random.gauss(z.pos.x,.5))

        for i in range(7):
            ax.scatter(categories[i][0], categories[i][1], color = legend.tableau20[i], label = numtostate[i])

        for z in self.cities:
            ax.scatter(z.loc.y, z.loc.x, color='black', marker='*')
#            print z.loc.x, z.loc.y

        ax.set_xlim([0, self.width])
        ax.set_ylim([0, self.height])
        #red_patch = mpatches.Patch(color='r', label='The red data')
        #plt.legend(handles=[red_patch])
        plt.legend(bbox_to_anchor=(1, 1), loc=2)
        plt.setp(ax.get_xticklabels(), visible=False)
        plt.setp(ax.get_yticklabels(), visible=False)
        plt.savefig(file_name)
Exemplo n.º 6
0
 def analyze(self, marker, body):
     if marker != Markers.SOF[2]:
         raise ValueError("invailed marker. class SOF excepting marker is " + Markers.SOF[2].to_bytes(1, 'big') + ". but " + marker.to_bytes(1, 'big') + " found.")
     analyzed = {}
     analyzed["length"] = len(body) + 2
     analyzed["segmentName"] = "SOF"
     analyzed["p"] = body[0]
     analyzed["y_size"] = body[1] * 0x100 + body[2]
     analyzed["x_size"] = body[3] * 0x100 + body[4]
     analyzed["nf"] = body[5]
     analyzed["nfData"] = []
     nfHead = 6
     nfLength = 3
     for i in range(analyzed["nf"]):
         nfDict = {}
         nfDict["id"] = i + 1
         nfDict["name"] = colors(analyzed["nf"])[i]
         nf = body[nfHead:nfHead + nfLength]
         nfDict["cn"] = nf[0]
         hv = nf[1]
         nfDict["hn"] = (hv & 0b11110000) >> 4
         nfDict["vn"] = hv & 0b00001111
         nfDict["tqn"] = nf[2]
         analyzed["nfData"].append(nfDict)
         nfHead = nfHead + nfLength
     return analyzed
Exemplo n.º 7
0
    def readMesh(self, path, casename):
        #read the mesh
        self.data.loadMesh(path, casename)

        # Create actors based on grid parts
        self.vtkActorList = []
        vtkgrids = self.data.buildVTKGrids()
        itag = 0
        c = colors()
        for vtkgrid in vtkgrids:
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInput(vtkgrid)
            self.vtkActorList.append(vtk.vtkActor())
            self.vtkActorList[-1].SetMapper(mapper)
            self.vtkActorList[-1].GetProperty().SetColor(c.getNext())
            # set visibility of volumes to false on startup
            if int(self.data.elemGroups[itag]) < 0:
                self.vtkActorList[-1].VisibilityOff()
            itag = itag + 1
            
        #visualize the grid
        for actor in self.vtkActorList:
            self.ren.AddActor(actor)
        self.iren.Render()
        
        #update mesh visibility options
        self.BCTab1.drawBCVizBoxes()
Exemplo n.º 8
0
def test_all_set():
    """
    Test that it works if you pass in all four parameters as positional arguments
    :return:
    """
    result = colors('red', 'blue', 'yellow', 'chartreuse')
    assert result == ('red', 'blue', 'yellow', 'chartreuse')
def test_all_sets():
    '''
    test that it works if you pass in all four paramenters as positional argusments
    '''
    result = colors('red', 'blue', 'yellow', 'chartreuse')

    assert result == ('red', 'blue', 'yellow', 'chartreuse')
def test_all_twokeyword():
    '''
    test that it works if you pass in all four paramenters as positional argusments
    '''
    result = colors(link_color='red', back_color='blue')

    assert result == ('black', 'blue', 'red', 'pink')
def test_dict_duplicate_param():
    colors_dict = {"fore_color": 'purple', "link_color": 'red'}
    #                   "back_color": 'green',
    #               "visited_color": 'magenta'}

    with pytest.raises(TypeError):
        result = colors('blue', **colors_dict)
Exemplo n.º 12
0
    def readMesh(self, path, casename):
        #read the mesh
        self.data.loadMesh(path, casename)

        # Create actors based on grid parts
        self.vtkActorList = []
        vtkgrids = self.data.buildVTKGrids()
        itag = 0
        c = colors()
        for vtkgrid in vtkgrids:
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInput(vtkgrid)
            self.vtkActorList.append(vtk.vtkActor())
            self.vtkActorList[-1].SetMapper(mapper)
            self.vtkActorList[-1].GetProperty().SetColor(c.getNext())
            # set visibility of volumes to false on startup
            if int(self.data.elemGroups[itag]) < 0:
                self.vtkActorList[-1].VisibilityOff()
            itag = itag + 1

        #visualize the grid
        for actor in self.vtkActorList:
            self.ren.AddActor(actor)
        self.iren.Render()

        #update mesh visibility options
        self.BCTab1.drawBCVizBoxes()
def test_all_two_keywords():
    """
    test that it works if you pass in all four parameters as
    positional arguments
    """

    result = colors(link_color='red', back_color='blue')
    assert result == ('black', 'blue', 'red', 'pink')
def test_colors_kwargs():
    colrs = {
        'fore_color': 'red',
        'back_color': 'blue',
        'link_color': 'purple',
        'visited_color': 'green'
    }
    assert (colors(**colrs) == tuple(colrs.values()))
def test_colors_args_kwargs_tup():
    colrs = {
        'link_color': 'red',
        'back_color': 'blue',
        'visited_color': 'green'
    }
    colr = ('yellow')
    assert (colors(colr, **colrs) == ('yellow', 'blue', 'red', 'green'))
def test_dict_params():
    colors_dict = {"fore_color": 'purple',
                    "back_color": 'green',
                    "link_color": 'red',
                    "visited_color": 'magenta'}

    result = colors(*colors_dict.values())
    assert result == ('purple', 'green', 'red', 'magenta')
Exemplo n.º 17
0
def test_dict_params():
    colors_dict = {
        "fore_color": "Purple",
        "back_color": "Green",
        "link_color": "Red",
        "visited_color": "Magenta"
    }
    result = colors(**colors_dict)
    assert result == ("Purple", "Green", "Red", "Magenta")
def test_dict_tup_params():
    # colors_dict = {"fore_color": 'purple', "link_color": 'red'}

    colors_dict = {"link_color": 'red', "visited_color": 'magenta'}

    #with pytest.raises(TypeError):
    result = colors('blue', **colors_dict)

    assert result == ('blue', 'red', 'red', 'magenta')
def test_dict_parameters():
    colors_dict = {
        "fore_color": "purple",
        "back_color": "green",
        "link_color": "red",
        "visited_color": "magenta"
    }

    result = colors(*colors_dict.values())
    assert result == ("purple", "green", "red", "magenta")
Exemplo n.º 20
0
def test_dict_tupe_params():
    colors_dict = {  # "fore_color": "Purple",
        "link_color": "Red",
        "visited_color": "Magenta"
    }

    with pytest.raises(TypeError):
        result = colors("blue", **colors_dict)

    assert result == ("Blue", "Red", "Red", "Magenta")
def test_colors_typeerror():
    colrs = {
        'fore_color': 'red',
        'back_color': 'blue',
        'link_color': 'purple',
        'visited_color': 'green'
    }

    with pytest.raises(TypeError):
        assert (colors('blue', **colrs) == tuple(colrs.values()))
def test_dict_tup_params():
    colors_dict = {#"fore_color": 'purple',
                   "link_color": 'red',
    #              "back_color": 'green',
                   "visited_color": 'magenta',
                   }

    result = colors('blue', **colors_dict)

    assert result == ('blue', 'red', 'red', 'magenta')
def test_dict_tup_parameters():
    colors_dict = {
        "fore_color": "purple",
        "back_color": "green",
        "link_color": "red",
        "visited_color": "magenta"
    }

    with pytest.raises(TypeError):
        result = colors('blue', **colors_dict)

        assert result == ('purple', 'green', 'red', 'magenta')
Exemplo n.º 24
0
		def tearDown():
			self.callbackCalled = True
			try:
				hasCallback = len(
					inspect.getargspec(self.tearDown).args) > 1
				if hasCallback:
					self.callbackCalled = False
					functionThread = threading.Thread(
						target=startThread,
						args=(self.tearDown, self._finishTest)
						)
					functionThread.start()
					waitOnTest()
				else:
					self.tearDown()
					self._finishTest()
			except Exception as err:
				if self.bail:
					colors('red', '\nError:\n')
					raise err
				self._handleError(err, traceback.format_exc(), caughtException=True)
Exemplo n.º 25
0
    def curveplot(self, file_name):

        legend = colors()
        fig, ax = plt.subplots(figsize=(16,10))

        for i in range(7):
            plt.plot(range(self.days+1), self.numlist[i], '-', color = legend.tableau20[i], linewidth = 4, label = numtostate[i])

#        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, mode="expand", borderaxespad=0.)
        handles, labels = ax.get_legend_handles_labels()
        lgd = ax.legend(handles, labels, bbox_to_anchor=(1, 1), loc=2)
        ax.set_xlim([0, self.days+1])
        ax.set_ylim([0, self.pop_size])
        ax.set_xlabel("Time")
        ax.set_ylabel("Population")
        plt.rcParams.update({'font.size': 24})
        plt.savefig(file_name, bbox_extra_artists=(lgd,), bbox_inches='tight')
Exemplo n.º 26
0
 def __init__(self,conf):
     with open(conf,'r') as fd:
         config = yaml.load(fd)
     self.deps = config['Dependences']
     self.config = config['Config']
     self.dataDir = self.config['dataDir']
     self.webMntPlg = self.config['enable_web_management']
     self.user = self.config['user']
     self.userTag = self.config['tag']
     self.vhost = self.config['vhost']
     self.vhost_enable = self.vhost['enable']
     self.vhost_path = self.vhost['path']
     self.userPermission = self.config['permission']
     self.worker = worker()
     self.color = colors()
     self.clusterNodes = self.config['clusterNodes']
     self.master = self.clusterNodes['mq01']
Exemplo n.º 27
0
def styles():
    """
    Function returns the styles for the HTML to be exported.
    """

    color_codes = c.colors()

    style = '\n'.join((
        '*{text-align: center;color: ' + color_codes[0] +
        ' !important; -webkit-print-color-adjust: exact; font-size: 25px;font-family:calibri;}',
        'body{width: 794px; margin: auto;}',
        '.split {width:390px; height: 1063;  overflow-x:hidden; margin: auto; margin-top: 40px; margin-bottom: 40px; }',
        '.left {float: left; position:relative;}',
        '.right {position:relative; page-break-after:always;}',
        '.page {margin: auto; border:1px solid; border-color: #FFFFFF; height: 1223px; width: 794px;}',
        'table{margin: auto; margin-top: 35px; margin-bottom: 35px; width: 380px; height: 130px; border-radius: 10px 10px 10px 10px;border: 1px solid; background-color: '
        + color_codes[1] + ' !important;}',
        'td{border-radius: 10px 10px 10px 10px;background-color: #FFFFFF !important;}',
        'td.blank{background-color: ' + color_codes[2] + ' !important;}'))

    return f'<style>{style}</style>'
Exemplo n.º 28
0
 def __init__(self, configFile):
     fd = open(configFile)
     self.color = colors.colors()
     self.config = yaml.load(fd)
     fd.close()
     self.zkConfig = self.config['zkConfig']
     self.resourcePath = self.config['Packages']['path']
     self.codisPassword = self.config['codisConfig']['password']
     codisRolesFile = self.config['Dependencies']['roleFile']
     with open(codisRolesFile, 'r') as fd:
         self.codisRoles = yaml.load(fd)
     self.zkNodes = self.codisRoles['zk']
     zkPort = self.config['zkConfig']['port']
     m = ''
     for i in self.zkNodes:
         m += i + ':' + str(zkPort) + ','
     self.zkAddress = m.strip(',').strip()
     try:
         os.mknod('%s/install.txt' % self.resourcePath)
     except Exception as e:
         pass
def test_tup_params():
    colors_tuple = ('purple', 'green', 'red', 'magenta')

    result = colors(*colors_tuple)

    assert result == ('purple', 'green', 'red', 'magenta')
def test_combine():
    '''
    test that it works if you pass in all four paramenters as positional argusments
    '''
    result = colors('purple', link_color='red', back_color='blue')
    assert result == ('purple', 'blue', 'red', 'pink')
Exemplo n.º 31
0
logfilename = "%s/session.log" % options.sessiondir
log = TrLogReader(logfilename, options.torrentname, options.filenum).get_log()
print >> sys.stderr, "found %d chunks" % len(log.chunks)

total_size = max([chunk["end"] for chunk in log.chunks])

def time_to_x(t): return int(t / log.lastchunktime() * options.width)
def byte_to_y(byte_pos): return min(int(float(byte_pos) / total_size * options.height), options.height-1)

class Piece:
    def __init__(self, begin, end):
        self.begin = begin
        self.end = end

peer_colors = [(int(r*255), int(g*255), int(b*255))
                for (r,g,b,a) in colors.colors(len(log.peers))]
peers = {}

image = Image.new("RGB", (options.width, options.height), "white")
pixels = image.load()

def render_slice(x):
    for (gatherer, color) in zip(peers.values(), peer_colors):
        for piece in gatherer.pieces():
            y1 = byte_to_y(piece.begin)
            y2 = byte_to_y(piece.end)
            for y in range(y1, y2):
                pixels[x, y] = color

previous_x = None
for chunk in log.chunks:
Exemplo n.º 32
0
def test_all_keyword():
    result = colors(link_color='red', back_color='blue')
    assert 'link_color=red' in result
    assert 'back_color=blue' in result
Exemplo n.º 33
0
def test_pos_key():
    result = colors('purple', link_color='red', back_color='blue')
    assert 'purple' in result
    assert 'link_color=red' in result
    assert 'back_color=blue' in result
Exemplo n.º 34
0
 def __init__(self, parent, color="cmyk(0, 0, 0, 255)"):
     self.parent = parent
     self.frame = self.parent.GetTopLevelParent()
     self.myColor = colors(color)
     self.setColor(color)
def test_defaults():
    result = colors()

    assert result == ('black', 'red', 'blue', 'pink')
Exemplo n.º 36
0
from flask import *
import onoff
import colors
import brightness
import effects

onoff = onoff.onoff()
colors = colors.colors()
brightness = brightness.brightness()
effects = effects.effects()

#Create flask app
app = Flask(__name__, template_folder='templates')

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/onoff/on", methods=['POST'])
def on():
    print "LEDs ON"
    onoff.on()
    return ('', 204)

@app.route("/onoff/off", methods=['POST'])
def off():
    print "LEDs OFF"
    onoff.off()
    return ('', 204)

@app.route("/brightness/updown/up", methods=['POST'])
Exemplo n.º 37
0
        screen.fill(color["YELLOW"])
        page("Game Page", color["BLUE"], screen, (), font)
        display_text("U sure? Gonna get Hard!", color["PURPLE"], screen, "rect", (125, 400))
        pause_button.display()  
                
    elif mode == "hard":
        #run the game here in hard mode
        pause_button.clicked = False
        screen.fill(color["YELLOW"])
        page("Game Page", color["BLUE"], screen, (), font)
        display_text("Hey Tough Guy, Strap ur Boots cos u r in for a", color["PURPLE"], screen, "rect", (30, 400))
        display_text("HELL'of a RIDE!!!", color["PURPLE"], screen, "rect", (170, 430))
        pause_button.display()
    
        
color = colors.colors()
width = 500
height = 700
screen = pygame.display.set_mode((width, height))
#background = Background(background_image)
font = pygame.font.Font("Xerox Sans Serif Narrow Bold Oblique.ttf", 70)
play_button = CircButton(screen, (100), color["SPRING GREEN"], color["LAWN GREEN"], (30, 550), "Play", color["PURPLE"])
exit_button = EllipButton(screen, (100, 75), color["RED"], color["DEEP PINK"], (333, 560), "Exit", color["LAWN GREEN"])
pause_button = EllipButton(screen, (100, 75), color["RED"], color["DEEP PINK"], (1, 1), "Pause", color["LAWN GREEN"])
back_button = RectButton(screen, (75, 50), color["RED"], color["DEEP PINK"], (424,1), "back", color["LAWN GREEN"])       
mode = ""   
pause_button_pressed = False
back_button_pressed = False
play_button_pressed = False
clock = pygame.time.Clock()
done = False
Exemplo n.º 38
0
def test_all_positional():
    result = colors('red', 'blue', 'yellow', 'chartreuse')
    assert 'red' in result
    assert 'blue' in result
    assert 'chartreuse' in result
Exemplo n.º 39
0
 def __init__(self, parent, color="cmyk(0, 0, 0, 255)"):
     self.parent = parent
     self.frame = self.parent.GetTopLevelParent()
     self.myColor = colors(color)
     self.setColor(color)
Exemplo n.º 40
0
from libqtile.lazy import lazy
from libqtile.utils import guess_terminal
from keys import keys
from groups import groups
from widgets import widgets
import os, subprocess, numpy
from colors import colors


@hook.subscribe.startup_once
def autostart():
    home = os.path.expanduser('~')
    subprocess.Popen([home + '/.config/qtile/autostart.sh'])


colors = colors()

layouts = [
    layout.MonadTall(
        border_width=1,
        border_focus=colors[1],
        border_normal=colors[0],
        margin=2,
        single_border_width=0,
        single_margin=0,
    ),
    layout.Max(),
]

screens = [
    Screen(top=bar.Bar(widgets(), 20), ),
Exemplo n.º 41
0
	def _runTest(self):
		testFunction = getattr(self, self._methods[self._testNum])

		# run the tearDown function w/ optional callback
		# when tearDown is done, call _finishTest
		def tearDown():
			self.callbackCalled = True
			try:
				hasCallback = len(
					inspect.getargspec(self.tearDown).args) > 1
				if hasCallback:
					self.callbackCalled = False
					functionThread = threading.Thread(
						target=startThread,
						args=(self.tearDown, self._finishTest)
						)
					functionThread.start()
					waitOnTest()
				else:
					self.tearDown()
					self._finishTest()
			except Exception as err:
				if self.bail:
					colors('red', '\nError:\n')
					raise err
				self._handleError(err, traceback.format_exc(), caughtException=True)

		def startThread(func, callback):
			func(callback)

		# wait on the callback to be called
		# if it's not been called, error out
		def waitOnTest():
			startTime = time.time()
			calls = 0
			callsPerPrint = 1 / self._timeoutCheckin
			while time.time() < startTime + self.timeout and \
				not self.callbackCalled:
				if calls > 0 and calls % callsPerPrint == 0:
					print 'Waiting on callback'
				time.sleep(self._timeoutCheckin)
				calls += 1

			# if we're out of the loop and the callback still
			# hasn't been called we've timed out and should bail
			if not self.callbackCalled:
				raise Exception('Test timed out after ' +
					str(self.timeout) + ' seconds')

		# run the test w/ tearDown as the callback
		def runTest():
			# the callback is optional so we check if this test
			# needs one
			hasCallback = len(
				inspect.getargspec(testFunction).args) > 1

			erroredOnTest = True
			try:
				if hasCallback:
					self.callbackCalled = False
					functionThread = threading.Thread(
						target=startThread,
						args=(testFunction, tearDown)
						)
					functionThread.start()
					waitOnTest()
				else:
					testFunction()
					erroredOnTest = False
					tearDown()
			except Exception as err:
				if self.bail:
					colors('red', '\nError:\n')
					# try to run the tearDown even though we've
					# errored
					if erroredOnTest:
						tearDown()
					if hasattr(err, 'message') and \
						'\n' not in err.message:
						print traceback.format_exc()
						sys.exit()
					else:
						raise err
				# if we're not bailing, just handle the error
				self._handleError(err, traceback.format_exc(), caughtException=True)

		# run the setUp function w/ optional callback
		try:
			hasCallback = len(
					inspect.getargspec(self.setUp).args) > 1
			if hasCallback:
				self.callbackCalled = False
				functionThread = threading.Thread(
					target=startThread,
					args=(self.setUp, runTest)
					)
				functionThread.start()
				waitOnTest()
			else:
				self.setUp()
				runTest()
		except Exception as err:
			if self.bail:
				colors('red', '\nError:\n')
				raise err
			self._handleError(err, traceback.format_exc(), caughtException=True)
Exemplo n.º 42
0
	def run(self, callback=None):
		colors('magenta', '\n\n Suite:', colors.end + self.title)
		colors('magenta', '=' * self._lineLength)

		self._callback = callback
		self._testNum = 0
		self._errors = 0
		self._numTests = len(self._methods)

		self._runningTests = True

		while self._testNum < self._numTests:
			startingErrors = self._errors

			# update the start time so self._timeoutThread
			# doesn't error out
			self._startTime = time.time()
			methodName = self._methods[self._testNum] \
				.replace('_', ' ')

			colors('cyan', '\n Test:', colors.end + methodName)
			colors(self._lineColor, '=' * self._lineLength)

			self._runTest()

			if self._errors > startingErrors:
				colors('red', '\n Failed')
			else:
				colors('green', ' Passed')

		self._runningTests = False
		colors('cyan','\n\n Results:')
		colors(self._lineColor, '=' * self._lineLength)
		passed = self._numTests - self._errors
		passed = str(passed) + ' passed'
		failed = self._errors
		failed = str(failed) + ' failed'
		title = '    ' + self.title + ':' + colors.end
		if self._errors > 0:
			colors('red', title, passed + ',', failed)
		else:
			colors('green', title, passed)
		colors(self._lineColor, '=' * self._lineLength)

		if self._callback:
			self._callback(None)
Exemplo n.º 43
0
    def drawPageData(self, xml, dc, logUnits):
        self.preparePageData(xml)

        #set font
        dc.SetFont(wx.Font(9, wx.FONTFAMILY_SWISS, wx.NORMAL, wx.NORMAL))
        dc.SetTextForeground(wx.Color(0,0,0,0))

        #main frame
        rectangle = self.convertFrameData(xml, dc)
        penclr   = wx.Colour(228, 228, 228, 228)
        brushclr = wx.Colour(228, 228, 228, 228)
        dc.SetPen(wx.Pen(penclr))
        dc.SetBrush(wx.Brush(brushclr))
        dc.DrawRectangleRect(rectangle)

        #other frames
        frames = xml.findall("{http://www.bitplant.de/template}frame")
        for frame in frames:
            x, y, w, h = self.convertFrameData(frame, dc)
            rectangle = wx.Rect(x, y, w, h)
            content = frame.find("{http://www.bitplant.de/template}content")
            if content.get("type") == "color":
                myColor=colors(content.text)
                r, g, b = myColor.getRgb()
                brushclr = wx.Colour(r, g, b, 255)
                penclr   = wx.Colour(r, g, b, 255)
                dc.SetBrush(wx.Brush(brushclr))
                dc.SetPen(wx.Pen(penclr))
                dc.DrawRectangleRect(rectangle)

            if content.get("type") == "text" or content.get("type") == "vartext":
                text = content.text
                text = text.replace("\\t", "\t")

                penclr   = wx.Colour(128, 128, 128)
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                dc.SetPen(wx.Pen(penclr))
                dc.DrawRectangleRect(rectangle)

                brushclr = wx.Colour(0, 0, 0, 255)
                penclr   = wx.Colour(0, 0, 0, 255)
                dc.SetBrush(wx.Brush(brushclr))
                dc.SetPen(wx.Pen(penclr))
                dc.SetLayoutDirection(2)
                angle = int(content.get("angle", 0))
                if angle == 270:
                    angle = 90
                    y = y + h
                elif angle == 90:
                    angle = 270
                elif angle == 180:
                    x = x + w
                    y = y + h
                dc.DrawRotatedText(content.text, x, y, angle)
                dc.SetLayoutDirection(0)

            if content.get("type") == "image":
                penclr   = wx.Colour(128, 128, 128)
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                dc.SetPen(wx.Pen(penclr))
                dc.DrawRectangleRect(rectangle)

                dir = self.__getDir(content)
                if not content.text:
                    return True
                if content.text.count(":") == 2:
                    file = content.text.split(":")[1]
                    orifile = content.text.split(":")[2]
                    if os.path.isfile(dir + "/" + file):
                        bmp = self.getPreview(dir + "/" + file)
                        if bmp != None:
                            dc.DrawBitmap(bmp, x, y)