<commit_before>__author__ = 'matthieu'

from docker import Client
import argparse
from cStringIO import StringIO

parser = argparse.ArgumentParser(description='PGXL startpack')
parser.add_argument('--ip', dest="ip", action="store_true", help="print container IP")
parser.add_argument('--ncontainers', dest="ncontainers", action="store", type=int, default=4, help="N containers")
parser.add_argument('--conf', dest='conf', action="store", type=str, help="generate configuration file")

args = parser.parse_args()
dcl = Client()

def get_containers(dcl):
    containers = dcl.containers()
    cts = []
    for c in containers:
        info = dcl.inspect_container(c)
        name = info['Name']
        ip = info['NetworkSettings']['IPAddress']
        cts.append({"name": name, "ip": ip})
    return cts

def get_conf(ips):
    servers = ["PGXL%d" %i for i in range(len(ips))]
    servers_ip = ips
    datanodes = servers[1:]
    datanodes_ip = servers_ip[1:]
    nnodes = len(datanodes)
    gtm_server = servers_ip[0]
    gtm_port = 20001
    #coord_server = datanodes_ip[0]
    conf = StringIO()
    conf.write("""
pgxcOwner=pom
pgxcUser=$pgxcOwner
tmpDir=/tmp
localTmpDir=$tmpDir
configBackup=n
""")
    conf.write("""
gtmName=gtm
gtmMasterServer={0}
gtmMasterPort={1}
gtmMasterDir=$HOME/pgxc/nodes/gtm
gtmExtraConfig=none
gtmMasterSpecificExtraConfig=none
""".format(gtm_server, gtm_port))

    conf.write("""
gtmProxyDir=$HOME/pgxc/nodes/gtm_pxy
gtmProxy=y
gtmProxyNames=({0})
gtmProxyServers=({1})
gtmProxyPorts=({2})
gtmProxyDirs=({3})
gtmPxyExtraConfig=none
gtmPxySpecificExtraConfig=({4})
""".format(' '.join(["PROXY%d" %i for i in range(nnodes)]),
           ' '.join(datanodes_ip),
           ' '.join(["20001"] * nnodes),
           ' '.join(["$gtmProxyDir"] * nnodes),
           ' '.join(["none"] * nnodes)))

    conf.write("""
coordMasterDir=$HOME/pgxc/nodes/coord
coordSlaveDir=$HOME/pgxc/nodes/coord_slave
coordArchLogDir=$HOME/pgxc/nodes/coord_archlog
coordNames=({0})
coordPorts=({1})
poolerPorts=({2})
coordPgHbaEntries=({3})
coordMasterServers=({4})
coordMasterDirs=({5})
coordMaxWALsender=5
coordMaxWALSenders=({6})
coordSlave=n
coordExtraConfig=coordExtraConfig
cat > $coordExtraConfig <<EOF
#================================================
# Added to all the coordinator postgresql.conf
# Original: $coordExtraConfig
log_destination = 'stderr'
logging_collector = on
log_directory = 'pg_log'
listen_addresses = '*'
max_connections = 100
log_filename = 'coordinator.log'
EOF
coordSpecificExtraConfig=({7})
coordExtraPgHba=none
coordSpecificExtraPgHba=({7})
""".format(' '.join("COORD%d" %node for node in range(nnodes)),
           ' '.join(["5432"] * nnodes),
           ' '.join(["20010"] * nnodes),
           ' '.join(["all"] * nnodes),
           ' '.join(datanodes_ip),
           ' '.join("$coordMasterDir/%d" %i for i in range(nnodes)),
           ' '.join(["$coordMaxWALsender"] * nnodes),
           ' '.join(["none"] * nnodes)))
    conf.write("""
datanodeMasterDir=$HOME/pgxc/nodes/dn_master
datanodeSlaveDir=$HOME/pgxc/nodes/dn_slave
datanodeArchLogDir=$HOME/pgxc/nodes/datanode_archlog
primaryDatanode={0}
datanodeNames=({1})
datanodePorts=({2})
datanodePoolerPorts=({3})
datanodePgHbaEntries=(all)
""".format(datanodes[0], ' '.join(datanodes),
           ' '.join(["21000"] * nnodes), ' '.join(["21010"] * nnodes)))
    conf.write("""
datanodeMasterServers=({0})
datanodeMasterDirs=({1})
datanodeMaxWalSender=5
datanodeMaxWALSenders=({3})
datanodeSlave=n
datanodeExtraConfig=node.conf
datanodeSpecificExtraConfig=({2})
datanodeExtraPgHba=none
datanodeSpecificExtraPgHba=({2})
datanodeAdditionalSlaves=n
""".format(' '.join(ip for ip in datanodes_ip), ' '.join("$datanodeMasterDir/%d" %i for i in range(nnodes)),
           ' '.join(["none"] * nnodes),
           ' '.join(["$datanodeMaxWalSender"] * nnodes)))
    return conf

def get_haproxy(ips):
    conf = StringIO()
    conf.write("""
global
    log         127.0.0.1 local2 debug

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

defaults
    timeout client 1m
    timeout server 1m
    timeout connect 10s

listen stats 0.0.0.0:9000
    mode http
    stats uri /stats

listen PGSQL 0.0.0.0:5432
    mode tcp
    option tcplog
    balance static-rr
""")

    for i in range(1, len(ips)):
        conf.write("""    server s%d %s:5432 check\n""" %(i, ips[i]))
    return conf

if args.ip:
    print get_containers(dcl)

if args.conf:
    ctn = get_containers(dcl)
    ips = [c["ip"] for c in ctn]
    conf = get_conf(ips)
    with open("%s/pgxc_ctl.conf" %args.conf, "w+") as fp:
        fp.write(conf.getvalue())
    with open("%s/haproxy.cfg" %args.conf, "w+") as fp:
        fp.write(get_haproxy(ips).getvalue())
    conf.close()

<commit_msg>custom ip<commit_after>__author__ = 'matthieu'

from docker import Client
import argparse
from cStringIO import StringIO

parser = argparse.ArgumentParser(description='PGXL startpack')
parser.add_argument('--ip', dest="ip", action="store_true", help="print container IP")
parser.add_argument('--ncontainers', dest="ncontainers", action="store", type=int, default=4, help="N containers")
parser.add_argument('--conf', dest='conf', action="store", type=str, help="generate configuration file")

args = parser.parse_args()
dcl = Client()

def get_containers(dcl):
    containers = dcl.containers()
    cts = []
    for c in containers:
        info = dcl.inspect_container(c)
        name = info['Name']
        ip = info['NetworkSettings']['IPAddress']
        cts.append({"name": name, "ip": ip})
    return cts

def get_conf(ips):
    servers = ["PGXL%d" %i for i in range(len(ips))]
    servers_ip = ips
    datanodes = servers[1:]
    datanodes_ip = servers_ip[1:]
    nnodes = len(datanodes)
    gtm_server = servers_ip[0]
    gtm_port = 20001
    #coord_server = datanodes_ip[0]
    conf = StringIO()
    conf.write("""
pgxcOwner=pom
pgxcUser=$pgxcOwner
tmpDir=/tmp
localTmpDir=$tmpDir
configBackup=n
""")
    conf.write("""
gtmName=gtm
gtmMasterServer={0}
gtmMasterPort={1}
gtmMasterDir=$HOME/pgxc/nodes/gtm
gtmExtraConfig=none
gtmMasterSpecificExtraConfig=none
""".format(gtm_server, gtm_port))

    conf.write("""
gtmProxyDir=$HOME/pgxc/nodes/gtm_pxy
gtmProxy=y
gtmProxyNames=({0})
gtmProxyServers=({1})
gtmProxyPorts=({2})
gtmProxyDirs=({3})
gtmPxyExtraConfig=none
gtmPxySpecificExtraConfig=({4})
""".format(' '.join(["PROXY%d" %i for i in range(nnodes)]),
           ' '.join(datanodes_ip),
           ' '.join(["20001"] * nnodes),
           ' '.join(["$gtmProxyDir"] * nnodes),
           ' '.join(["none"] * nnodes)))

    conf.write("""
coordMasterDir=$HOME/pgxc/nodes/coord
coordSlaveDir=$HOME/pgxc/nodes/coord_slave
coordArchLogDir=$HOME/pgxc/nodes/coord_archlog
coordNames=({0})
coordPorts=({1})
poolerPorts=({2})
coordPgHbaEntries=({3})
coordMasterServers=({4})
coordMasterDirs=({5})
coordMaxWALsender=5
coordMaxWALSenders=({6})
coordSlave=n
coordExtraConfig=coordExtraConfig
cat > $coordExtraConfig <<EOF
#================================================
# Added to all the coordinator postgresql.conf
# Original: $coordExtraConfig
log_destination = 'stderr'
logging_collector = on
log_directory = 'pg_log'
listen_addresses = '*'
max_connections = 100
log_filename = 'coordinator.log'
EOF
coordSpecificExtraConfig=({7})
coordExtraPgHba=none
coordSpecificExtraPgHba=({7})
""".format(' '.join("COORD%d" %node for node in range(nnodes)),
           ' '.join(["5432"] * nnodes),
           ' '.join(["20010"] * nnodes),
           ' '.join(["all"] * nnodes),
           ' '.join(datanodes_ip),
           ' '.join("$coordMasterDir/%d" %i for i in range(nnodes)),
           ' '.join(["$coordMaxWALsender"] * nnodes),
           ' '.join(["none"] * nnodes)))
    conf.write("""
datanodeMasterDir=$HOME/pgxc/nodes/dn_master
datanodeSlaveDir=$HOME/pgxc/nodes/dn_slave
datanodeArchLogDir=$HOME/pgxc/nodes/datanode_archlog
primaryDatanode={0}
datanodeNames=({1})
datanodePorts=({2})
datanodePoolerPorts=({3})
datanodePgHbaEntries=(all)
""".format(datanodes[0], ' '.join(datanodes),
           ' '.join(["21000"] * nnodes), ' '.join(["21010"] * nnodes)))
    conf.write("""
datanodeMasterServers=({0})
datanodeMasterDirs=({1})
datanodeMaxWalSender=5
datanodeMaxWALSenders=({3})
datanodeSlave=n
datanodeExtraConfig=node.conf
datanodeSpecificExtraConfig=({2})
datanodeExtraPgHba=none
datanodeSpecificExtraPgHba=({2})
datanodeAdditionalSlaves=n
""".format(' '.join(ip for ip in datanodes_ip), ' '.join("$datanodeMasterDir/%d" %i for i in range(nnodes)),
           ' '.join(["none"] * nnodes),
           ' '.join(["$datanodeMaxWalSender"] * nnodes)))
    return conf

def get_haproxy(ips):
    conf = StringIO()
    conf.write("""
global
    log         127.0.0.1 local2 debug

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

defaults
    timeout client 1m
    timeout server 1m
    timeout connect 10s

listen stats 0.0.0.0:9000
    mode http
    stats uri /stats

listen PGSQL 0.0.0.0:5432
    mode tcp
    option tcplog
    balance static-rr
""")

    for i in range(1, len(ips)):
        conf.write("""    server s%d %s:5432 check\n""" %(i, ips[i]))
    return conf

if args.ip:
    print get_containers(dcl)

if args.conf:
    ctn = get_containers(dcl)
    ips = [c["ip"] for c in ctn]
    ips = ["10.0.1.%d" %i for i in range(1, 4)]
    conf = get_conf(ips)
    with open("%s/pgxc_ctl.conf" %args.conf, "w+") as fp:
        fp.write(conf.getvalue())
    with open("%s/haproxy.cfg" %args.conf, "w+") as fp:
        fp.write(get_haproxy(ips).getvalue())
    conf.close()

<|endoftext|>


<commit_before>#coding: utf-8
import sys
import os
import platform
if '32' in platform.architecture()[0]:
	os.chdir("libtcod32-1.5.2")
else:
	os.chdir("libtcod-1.5.2")
# sys.path.append("tcod-1.5.2/python")
sys.path.append("python")
import libtcodpy as tcod
import random
from random import randint
import util
import math
import towers
import enemies
import abilities

FPS_LIMIT = 60
WINDOW_TITLE = "TD RL"

tile_types = dict(
	grass = dict(
		sym = '.',
		color = tcod.darker_green,
	)
)

class state (object):
	pass

class Map (object):
	def __init__ (self, w, h):
		assert w % 2 == 1, "heart is in the center of map"
		assert h % 2 == 1, "heart is in the center of map"
		self.w = w
		self.h = h

		self.tiles = [
			['grass'] * w,
		] * h

	def render (self):
		for y, row in enumerate(self.tiles):
			for x, tile_type in enumerate(row):
				tcod.console_put_char(0, x, y, tile_types[tile_type]['sym'], tcod.BKGND_NONE)
				tcod.console_set_char_foreground(0, x, y, tile_types[tile_type]['color'])
				# tcod.console_put_char_ex(0, x + 1, y + 1, cell, color.grass, 0)

def run ():
	os.putenv('SDL_VIDEO_CENTERED', '1')
	tcod.sys_set_fps(FPS_LIMIT)
	tcod.console_set_custom_font('data/fonts/dejavu16x16_gs_tc.png', tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD)
	tcod.console_init_root(60, 50, WINDOW_TITLE, False)

	# c1 = tcod.Color(255, 255, 255)
	# tcod.console_set_default_background(0, c1)
	# tcod.console_clear(0)

	state.timers = util.Timers()
	state.is_paused = False
	state.map = Map(41, 41)
	state.entities = entities = util.Entities()
	state.energy = 10

	#enemies
	map_sides = [
		#top
		lambda: (randint(0, state.map.w - 1), 0),
		#bottom
		lambda: (randint(0, state.map.w - 1), state.map.h - 1),
		#left
		lambda: (0, randint(0, state.map.h - 1)),
		#right
		lambda: (state.map.w - 1, randint(0, state.map.h - 1)),
	]
	state.enemy_i = 0

	def spawn_enemy_group (start_x, start_y, rows, cols):
		es = [random.choice([enemies.Wolf, enemies.Rat]) for _ in range(rows * cols)]

		y = start_y
		for c in range(cols):
			x = start_x
			for r in range(rows):
				entities.append(es[c + r](state, x, y))
				x += 1
			y += 1

	def spawn_enemy ():
		if random.random() >= 0.8:
			x, y = random.choice(map_sides)()
			rows = random.randint(1, 4)
			cols = random.randint(1, 4)
			spawn_enemy_group(x, y, rows, cols)

			state.enemy_i += rows * cols

		# x, y = random.choice(map_sides)()
		x, y = random.choice([(5,5), (6,5)])
		entities.append(enemies.Rat(state, x, y))

		if state.enemy_i > 4:
			x, y = random.choice(map_sides)()
			entities.append(enemies.Wolf(state, x, y))

			state.enemy_i += 1

		state.enemy_i += 1
	state.timers.start(500, spawn_enemy)

	#towers
	heart = towers.Heart(state, state.map.w // 2, state.map.h // 2)
	entities.append(heart)
	state.heart = heart

	towers.BasicTower(state, heart.x - 1, heart.y).put()
	towers.ResearchBuilding(state, heart.x + 1, heart.y).put()
	towers.IceTower(state, heart.x, heart.y - 1).put()
	towers.AoeTower(state, heart.x, heart.y + 1).put()

	#panel
	pan_w = 50
	pan_h = 6
	panel = tcod.console_new(pan_w, pan_h)
	tcod.console_set_default_foreground(panel, tcod.white)

	tcod.console_set_default_background(panel, tcod.Color(5, 5, 5))
	tcod.console_rect(panel, 0, 0, pan_w, pan_h, False, tcod.BKGND_SCREEN)
	# tcod.console_set_default_background(panel, tcod.black)

	def map_to_entity (cx, cy):
		for e in state.entities:
			if (e.x, e.y) == (cx, cy):
				return e

	key = tcod.Key()
	mouse = tcod.Mouse()
	while not tcod.console_is_window_closed():
		#handle input
		ev = tcod.sys_check_for_event(tcod.EVENT_KEY_PRESS | tcod.EVENT_MOUSE, key, mouse) #TODO loop?
		if key.vk == tcod.KEY_ESCAPE:
			break
		elif key.vk == tcod.KEY_SPACE:
			if state.is_paused:
				state.timers.resume()
			else:
				state.timers.pause()
			state.is_paused = not state.is_paused

		if mouse.lbutton_pressed:
			print "left mouse, cell:", mouse.cx, mouse.cy

			e = map_to_entity(mouse.cx, mouse.cy)
			if not isinstance(e, towers.Building):
				# towers.ResearchTower(state, mouse.cx, mouse.cy).put()

				a = abilities.BaitAbility(None, state, mouse.cx, mouse.cy)
				a.use()
		elif mouse.rbutton_pressed:
			e = map_to_entity(mouse.cx, mouse.cy)
			if isinstance(e, towers.Tower):
				e.delete()

		for e in entities:
			if e.x == mouse.cx and e.y == mouse.cy:
				e.mouse_over = True
			else:
				e.mouse_over = False

		#update
		if not state.is_paused:
			state.timers.update()

		if not state.is_paused:
			for e in entities:
				e.update()

		#render
		tcod.console_clear(0)  #TODO dont use?

		state.map.render()

		for e in entities:
			e.render()

		if state.is_paused:
			tcod.console_print_ex(0, 0, 0, tcod.BKGND_NONE, tcod.LEFT, "paused")
		else:
			tcod.console_print_ex(0, 0, 0, tcod.BKGND_NONE, tcod.LEFT, " " * len("paused"))

		tcod.console_print_ex(0, 14, 0, tcod.BKGND_NONE, tcod.LEFT, "energy: %s" % state.energy)

		tcod.console_print_ex(panel, 0, 0, tcod.BKGND_NONE, tcod.LEFT, "123 The quick brown fox jumps over the lazy dog.")
		tcod.console_print_ex(panel, 0, 2, tcod.BKGND_NONE, tcod.LEFT, "Adviser: Eew! Rats.. I have musophobia, I told you.")
		# tcod.console_print_ex(panel, 0, 1, tcod.BKGND_NONE, tcod.LEFT, "Эх, чужд кайф, сплющь объём вши, грызя цент.")
		tcod.console_blit(panel, 0, 0, pan_w, pan_h, 0, 0, 43)

		tcod.console_flush()

if __name__ == '__main__':
	run()
<commit_msg>popup<commit_after>#coding: utf-8
import sys
import os
import platform
if '32' in platform.architecture()[0]:
	os.chdir("libtcod32-1.5.2")
else:
	os.chdir("libtcod-1.5.2")
# sys.path.append("tcod-1.5.2/python")
sys.path.append("python")
import libtcodpy as tcod
import random
from random import randint
import util
import math
import towers
import enemies
import abilities

FPS_LIMIT = 60
WINDOW_TITLE = "TD RL"

tile_types = dict(
	grass = dict(
		sym = '.',
		color = tcod.darker_green,
	)
)

class state (object):
	pass

class Popup (object):
	width = 10
	height = 5
	x = 0
	y = 0
	text = None

	def __init__ (self):
		self.obj = tcod.console_new(self.width, self.height)
		tcod.console_set_default_foreground(self.obj, tcod.white)

		tcod.console_set_default_background(self.obj, tcod.Color(5, 5, 5))
		tcod.console_rect(self.obj, 0, 0, self.width, self.height, False, tcod.BKGND_SCREEN)

	def set_params (self, x, y, text):
		self.text = text
		self.x = x
		self.y = y

	def show (self):
		if self.text:
			tcod.console_print_ex(self.obj, 0, 0, tcod.BKGND_OVERLAY, tcod.LEFT, self.text)
			tcod.console_blit(self.obj, 0, 0, self.width, self.height, 0, self.x, self.y)
		#self.text = None

class Map (object):
	def __init__ (self, w, h):
		assert w % 2 == 1, "heart is in the center of map"
		assert h % 2 == 1, "heart is in the center of map"
		self.w = w
		self.h = h

		self.tiles = [
			['grass'] * w,
		] * h

	def render (self):
		for y, row in enumerate(self.tiles):
			for x, tile_type in enumerate(row):
				tcod.console_put_char(0, x, y, tile_types[tile_type]['sym'], tcod.BKGND_NONE)
				tcod.console_set_char_foreground(0, x, y, tile_types[tile_type]['color'])
				# tcod.console_put_char_ex(0, x + 1, y + 1, cell, color.grass, 0)

def run ():
	os.putenv('SDL_VIDEO_CENTERED', '1')
	tcod.sys_set_fps(FPS_LIMIT)
	tcod.console_set_custom_font('data/fonts/dejavu16x16_gs_tc.png', tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD)
	tcod.console_init_root(60, 50, WINDOW_TITLE, False)

	# c1 = tcod.Color(255, 255, 255)
	# tcod.console_set_default_background(0, c1)
	# tcod.console_clear(0)

	state.timers = util.Timers()
	state.is_paused = False
	state.map = Map(41, 41)
	state.entities = entities = util.Entities()
	state.energy = 10

	#enemies
	map_sides = [
		#top
		lambda: (randint(0, state.map.w - 1), 0),
		#bottom
		lambda: (randint(0, state.map.w - 1), state.map.h - 1),
		#left
		lambda: (0, randint(0, state.map.h - 1)),
		#right
		lambda: (state.map.w - 1, randint(0, state.map.h - 1)),
	]
	state.enemy_i = 0

	def spawn_enemy_group (start_x, start_y, rows, cols):
		es = [random.choice([enemies.Wolf, enemies.Rat]) for _ in range(rows * cols)]

		y = start_y
		for c in range(cols):
			x = start_x
			for r in range(rows):
				entities.append(es[c + r](state, x, y))
				x += 1
			y += 1

	def spawn_enemy ():
		if random.random() >= 0.8:
			x, y = random.choice(map_sides)()
			rows = random.randint(1, 4)
			cols = random.randint(1, 4)
			spawn_enemy_group(x, y, rows, cols)

			state.enemy_i += rows * cols

		# x, y = random.choice(map_sides)()
		x, y = random.choice([(5,5), (6,5)])
		entities.append(enemies.Rat(state, x, y))

		if state.enemy_i > 4:
			x, y = random.choice(map_sides)()
			entities.append(enemies.Wolf(state, x, y))

			state.enemy_i += 1

		state.enemy_i += 1
	state.timers.start(500, spawn_enemy)

	#towers
	heart = towers.Heart(state, state.map.w // 2, state.map.h // 2)
	entities.append(heart)
	state.heart = heart

	towers.BasicTower(state, heart.x - 1, heart.y).put()
	towers.ResearchBuilding(state, heart.x + 1, heart.y).put()
	towers.IceTower(state, heart.x, heart.y - 1).put()
	towers.AoeTower(state, heart.x, heart.y + 1).put()

	#panel
	pan_w = 50
	pan_h = 6
	panel = tcod.console_new(pan_w, pan_h)
	tcod.console_set_default_foreground(panel, tcod.white)

	tcod.console_set_default_background(panel, tcod.Color(5, 5, 5))
	tcod.console_rect(panel, 0, 0, pan_w, pan_h, False, tcod.BKGND_SCREEN)
	# tcod.console_set_default_background(panel, tcod.black)

	popup = Popup()

	def map_to_entity (cx, cy):
		for e in state.entities:
			if (e.x, e.y) == (cx, cy):
				return e

	key = tcod.Key()
	mouse = tcod.Mouse()
	while not tcod.console_is_window_closed():
		#handle input
		ev = tcod.sys_check_for_event(tcod.EVENT_KEY_PRESS | tcod.EVENT_MOUSE, key, mouse) #TODO loop?
		if key.vk == tcod.KEY_ESCAPE:
			break
		elif key.vk == tcod.KEY_SPACE:
			if state.is_paused:
				state.timers.resume()
			else:
				state.timers.pause()
			state.is_paused = not state.is_paused

		entity_under_mouse = map_to_entity(mouse.cx, mouse.cy)
		if entity_under_mouse:
			px, py = mouse.cx, mouse.cy
			#if isinstance(entity_under_mouse, util.Building):
			popup.set_params(px, py, entity_under_mouse.__class__.__name__)

		if mouse.lbutton_pressed:
			print "left mouse, cell:", mouse.cx, mouse.cy

			e = map_to_entity(mouse.cx, mouse.cy)
			if not isinstance(e, towers.Building):
				# towers.ResearchTower(state, mouse.cx, mouse.cy).put()

				a = abilities.BaitAbility(None, state, mouse.cx, mouse.cy)
				a.use()
		elif mouse.rbutton_pressed:
			e = map_to_entity(mouse.cx, mouse.cy)
			if isinstance(e, towers.Tower):
				e.delete()

		for e in entities:
			if e.x == mouse.cx and e.y == mouse.cy:
				e.mouse_over = True
			else:
				e.mouse_over = False

		#update
		if not state.is_paused:
			state.timers.update()

		if not state.is_paused:
			for e in entities:
				e.update()

		#render
		tcod.console_clear(0)  #TODO dont use?

		state.map.render()

		for e in entities:
			e.render()

		if state.is_paused:
			tcod.console_print_ex(0, 0, 0, tcod.BKGND_NONE, tcod.LEFT, "paused")
		else:
			tcod.console_print_ex(0, 0, 0, tcod.BKGND_NONE, tcod.LEFT, " " * len("paused"))

		tcod.console_print_ex(0, 14, 0, tcod.BKGND_NONE, tcod.LEFT, "energy: %s" % state.energy)

		tcod.console_print_ex(panel, 0, 0, tcod.BKGND_NONE, tcod.LEFT, "123 The quick brown fox jumps over the lazy dog.")
		tcod.console_print_ex(panel, 0, 2, tcod.BKGND_NONE, tcod.LEFT, "Adviser: Eew! Rats.. I have musophobia, I told you.")
		# tcod.console_print_ex(panel, 0, 1, tcod.BKGND_NONE, tcod.LEFT, "Эх, чужд кайф, сплющь объём вши, грызя цент.")
		tcod.console_blit(panel, 0, 0, pan_w, pan_h, 0, 0, 43)
		popup.show()

		tcod.console_flush()

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


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

import bz2
import emcee
import numpy as np
import os
import os.path as op
import plotutils.autocorr as ac
import posterior
import uuid

if __name__ == '__main__':
    threads = 3
    walkers = 100
    nstep = 100
    nthin = 10

    data = np.loadtxt('../test/ps-rs.dat.bz2')

    logpost = posterior.Posterior(data[:,0], data[:,1])

    sampler = emcee.EnsembleSampler(walkers, logpost.nparams, logpost, threads=threads)

    with bz2.BZ2File(op.join('..', 'test', 'chain.npy.bz2'), 'r') as inp:
        chain = np.load(inp)
    with bz2.BZ2File(op.join('..', 'test', 'lnprob.npy.bz2'), 'r') as inp:
        lnprob = np.load(inp)

    sampler._chain = chain
    sampler._lnprob = lnprob

    while True:
        sampler.run_mcmc(sampler.chain[:,-1,:], nstep, thin=nthin)

        istart = int(round(0.1*sampler.chain.shape[1]))

        print 'Saving state after ', sampler.chain.shape[1], ' samples....'
        print 'Autocorrelations are ', ac.emcee_chain_autocorrelation_lengths(sampler.chain[:,istart:,:])

        chain_name = uuid.uuid4().hex
        lnprob_name = uuid.uuid4().hex

        chain_name = chain_name + '.npy.bz2'
        lnprob_name = lnprob_name + '.npy.bz2'

        chain_file = op.join('..', 'test', chain_name)
        lnprob_file = op.join('..', 'test', lnprob_name)

        with bz2.BZ2File(chain_file, 'w') as out:
            np.save(out, sampler.chain)
        with bz2.BZ2File(lnprob_file, 'w') as out:
            np.save(out, sampler.lnprobability)

        os.rename(chain_file, op.join('..', 'test', 'chain.npy.bz2'))
        os.rename(lnprob_file, op.join('..', 'test', 'lnprob.npy.bz2'))
<commit_msg>Increased number of threads in run.py for BlueBear.<commit_after>#!/usr/bin/env python

import bz2
import emcee
import numpy as np
import os
import os.path as op
import plotutils.autocorr as ac
import posterior
import uuid

if __name__ == '__main__':
    threads = 15
    walkers = 100
    nstep = 100
    nthin = 10

    data = np.loadtxt('../test/ps-rs.dat.bz2')

    logpost = posterior.Posterior(data[:,0], data[:,1])

    sampler = emcee.EnsembleSampler(walkers, logpost.nparams, logpost, threads=threads)

    with bz2.BZ2File(op.join('..', 'test', 'chain.npy.bz2'), 'r') as inp:
        chain = np.load(inp)
    with bz2.BZ2File(op.join('..', 'test', 'lnprob.npy.bz2'), 'r') as inp:
        lnprob = np.load(inp)

    sampler._chain = chain
    sampler._lnprob = lnprob

    while True:
        sampler.run_mcmc(sampler.chain[:,-1,:], nstep, thin=nthin)

        istart = int(round(0.1*sampler.chain.shape[1]))

        print 'Saving state after ', sampler.chain.shape[1], ' samples....'
        print 'Autocorrelations are ', ac.emcee_chain_autocorrelation_lengths(sampler.chain[:,istart:,:])

        chain_name = uuid.uuid4().hex
        lnprob_name = uuid.uuid4().hex

        chain_name = chain_name + '.npy.bz2'
        lnprob_name = lnprob_name + '.npy.bz2'

        chain_file = op.join('..', 'test', chain_name)
        lnprob_file = op.join('..', 'test', lnprob_name)

        with bz2.BZ2File(chain_file, 'w') as out:
            np.save(out, sampler.chain)
        with bz2.BZ2File(lnprob_file, 'w') as out:
            np.save(out, sampler.lnprobability)

        os.rename(chain_file, op.join('..', 'test', 'chain.npy.bz2'))
        os.rename(lnprob_file, op.join('..', 'test', 'lnprob.npy.bz2'))
<|endoftext|>


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

from flask_debugtoolbar import DebugToolbarExtension

from app import app
from app.models import connect_to_db

if __name__ == '__main__':

    # debug = True as DebugToolbarExtension is invoked

    connect_to_db(app)

    # User the DebugToolbar
    # DebugToolbarExtension(app)

    PORT = int(os.environ.get("PORT", 5000))

    app.run(debug=True, host="0.0.0.0", port=PORT)
<commit_msg>Added os to run.py<commit_after>#!/usr/bin/env python

from flask_debugtoolbar import DebugToolbarExtension

from app import app
from app.models import connect_to_db
import os

if __name__ == '__main__':

    # debug = True as DebugToolbarExtension is invoked

    connect_to_db(app)

    # User the DebugToolbar
    # DebugToolbarExtension(app)

    PORT = int(os.environ.get("PORT", 5000))

    app.run(debug=True, host="0.0.0.0", port=PORT)
<|endoftext|>


<commit_before>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(27, GPIO.INPUT)

try:
    while not GPIO.input(27):
        GPIO.output(4, False)
        print("off")
        time.sleep(2)
        GPIO.output(4, True)
        print("on")
        time.sleep(2)
finally:
    GPIO.cleanup()

<commit_msg>Fix Mistype<commit_after>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(27, GPIO.IN)

try:
    while not GPIO.input(27):
        GPIO.output(4, False)
        print("off")
        time.sleep(2)
        GPIO.output(4, True)
        print("on")
        time.sleep(2)
finally:
    GPIO.cleanup()

<|endoftext|>


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

import argparse
import cv2
from numpy import empty, nan
import os
import sys
import time

import CMT
import numpy as np
import util

CMT = CMT.CMT()

parser = argparse.ArgumentParser(description='Track an object.')

parser.add_argument('inputpath', nargs='?', help='The input path.')
parser.add_argument('--challenge', dest='challenge', action='store_true', help='Enter challenge mode.')
parser.add_argument('--preview', dest='preview', action='store_const', const=True, default=None, help='Force preview')
parser.add_argument('--no-preview', dest='preview', action='store_const', const=False, default=None, help='Disable preview')
parser.add_argument('--no-scale', dest='estimate_scale', action='store_false', help='Disable scale estimation')
parser.add_argument('--with-rotation', dest='estimate_rotation', action='store_true', help='Enable rotation estimation')
parser.add_argument('--bbox', dest='bbox', help='Specify initial bounding box.')
parser.add_argument('--pause', dest='pause', action='store_true', help='Specify initial bounding box.')
parser.add_argument('--output-dir', dest='output', help='Specify a directory for output data.')
parser.add_argument('--quiet', dest='quiet', action='store_true', help='Do not show graphical output (Useful in combination with --output-dir ).')
parser.add_argument('--skip', dest='skip', action='store', default=None, help='Skip the first n frames', type=int)

args = parser.parse_args()

CMT.estimate_scale = args.estimate_scale
CMT.estimate_rotation = args.estimate_rotation

if args.pause:
	pause_time = 0
else:
	pause_time = 10

if args.output is not None:
	if not os.path.exists(args.output):
		os.mkdir(args.output)
	elif not os.path.isdir(args.output):
		raise Exception(args.output + ' exists, but is not a directory')

if args.challenge:
	with open('images.txt') as f:
		images = [line.strip() for line in f]

	init_region = np.genfromtxt('region.txt', delimiter=',')
	num_frames = len(images)

	results = empty((num_frames, 4))
	results[:] = nan

	results[0, :] = init_region

	frame = 0

	im0 = cv2.imread(images[frame])
	im_gray0 = cv2.cvtColor(im0, cv2.COLOR_BGR2GRAY)
	im_draw = np.copy(im0)

	tl, br = (util.array_to_int_tuple(init_region[:2]), util.array_to_int_tuple(init_region[:2] + init_region[2:4] - 1))

	try:
		CMT.initialise(im_gray0, tl, br)
		while frame < num_frames:
			im = cv2.imread(images[frame])
			im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
			CMT.process_frame(im_gray)
			results[frame, :] = CMT.bb

			# Advance frame number
			frame += 1
	except:
		pass  # Swallow errors

	np.savetxt('output.txt', results, delimiter=',')

else:
	# Clean up
	cv2.destroyAllWindows()

	preview = args.preview

	if args.inputpath is not None:

		# If a path to a file was given, assume it is a single video file
		if os.path.isfile(args.inputpath):
			cap = cv2.VideoCapture(args.inputpath)

			#Skip first frames if required
			if args.skip is not None:
				cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, args.skip)

		# Otherwise assume it is a format string for reading images
		else:
			cap = util.FileVideoCapture(args.inputpath)

			#Skip first frames if required
			if args.skip is not None:
				cap.frame = 1 + args.skip

		# By default do not show preview in both cases
		if preview is None:
			preview = False

	else:
		# If no input path was specified, open camera device
		cap = cv2.VideoCapture(0)
		if preview is None:
			preview = True

	# Check if videocapture is working
	if not cap.isOpened():
		print 'Unable to open video input.'
		sys.exit(1)

	while preview:
		status, im = cap.read()
		cv2.imshow('Preview', im)
		k = cv2.waitKey(10)
		if not k == -1:
			break

	# Read first frame
	status, im0 = cap.read()
	im_gray0 = cv2.cvtColor(im0, cv2.COLOR_BGR2GRAY)
	im_draw = np.copy(im0)

	if args.bbox is not None:
		# Try to disassemble user specified bounding box
		values = args.bbox.split(',')
		try:
			values = [int(v) for v in values]
		except:
			raise Exception('Unable to parse bounding box')
		if len(values) != 4:
			raise Exception('Bounding box must have exactly 4 elements')
		bbox = np.array(values)

		# Convert to point representation, adding singleton dimension
		bbox = util.bb2pts(bbox[None, :])

		# Squeeze
		bbox = bbox[0, :]

		tl = bbox[:2]
		br = bbox[2:4]
	else:
		# Get rectangle input from user
		(tl, br) = util.get_rect(im_draw)

	print 'using', tl, br, 'as init bb'

	CMT.initialise(im_gray0, tl, br)

	frame = 1
	while True:
		# Read image
		status, im = cap.read()
		if not status:
			break
		im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
		im_draw = np.copy(im)

		tic = time.time()
		CMT.process_frame(im_gray)
		toc = time.time()

		# Display results

		# Draw updated estimate
		if CMT.has_result:

			cv2.line(im_draw, CMT.tl, CMT.tr, (255, 0, 0), 4)
			cv2.line(im_draw, CMT.tr, CMT.br, (255, 0, 0), 4)
			cv2.line(im_draw, CMT.br, CMT.bl, (255, 0, 0), 4)
			cv2.line(im_draw, CMT.bl, CMT.tl, (255, 0, 0), 4)

		util.draw_keypoints(CMT.tracked_keypoints, im_draw, (255, 255, 255))
		# this is from simplescale
		util.draw_keypoints(CMT.votes[:, :2], im_draw)  # blue
		util.draw_keypoints(CMT.outliers[:, :2], im_draw, (0, 0, 255))

		if args.output is not None:
			# Original image
			cv2.imwrite('{0}/input_{1:08d}.png'.format(args.output, frame), im)
			# Output image
			cv2.imwrite('{0}/output_{1:08d}.png'.format(args.output, frame), im_draw)

			# Keypoints
			with open('{0}/keypoints_{1:08d}.csv'.format(args.output, frame), 'w') as f:
				f.write('x y\n')
				np.savetxt(f, CMT.tracked_keypoints[:, :2], fmt='%.2f')

			# Outlier
			with open('{0}/outliers_{1:08d}.csv'.format(args.output, frame), 'w') as f:
				f.write('x y\n')
				np.savetxt(f, CMT.outliers, fmt='%.2f')

			# Votes
			with open('{0}/votes_{1:08d}.csv'.format(args.output, frame), 'w') as f:
				f.write('x y\n')
				np.savetxt(f, CMT.votes, fmt='%.2f')

			# Bounding box
			with open('{0}/bbox_{1:08d}.csv'.format(args.output, frame), 'w') as f:
				f.write('x y\n')
				# Duplicate entry tl is not a mistake, as it is used as a drawing instruction
				np.savetxt(f, np.array((CMT.tl, CMT.tr, CMT.br, CMT.bl, CMT.tl)), fmt='%.2f')

		if not args.quiet:
			cv2.imshow('main', im_draw)

			# Check key input
			k = cv2.waitKey(pause_time)
			key = chr(k & 255)
			if key == 'q':
				break
			if key == 'd':
				import ipdb; ipdb.set_trace()

		# Remember image
		im_prev = im_gray

		# Advance frame number
		frame += 1

		print '{5:04d}: center: {0:.2f},{1:.2f} scale: {2:.2f}, active: {3:03d}, {4:04.0f}ms'.format(CMT.center[0], CMT.center[1], CMT.scale_estimate, CMT.active_keypoints.shape[0], 1000 * (toc - tic), frame)
<commit_msg>Fix --help message<commit_after>#!/usr/bin/env python

import argparse
import cv2
from numpy import empty, nan
import os
import sys
import time

import CMT
import numpy as np
import util

CMT = CMT.CMT()

parser = argparse.ArgumentParser(description='Track an object.')

parser.add_argument('inputpath', nargs='?', help='The input path.')
parser.add_argument('--challenge', dest='challenge', action='store_true', help='Enter challenge mode.')
parser.add_argument('--preview', dest='preview', action='store_const', const=True, default=None, help='Force preview')
parser.add_argument('--no-preview', dest='preview', action='store_const', const=False, default=None, help='Disable preview')
parser.add_argument('--no-scale', dest='estimate_scale', action='store_false', help='Disable scale estimation')
parser.add_argument('--with-rotation', dest='estimate_rotation', action='store_true', help='Enable rotation estimation')
parser.add_argument('--bbox', dest='bbox', help='Specify initial bounding box.')
parser.add_argument('--pause', dest='pause', action='store_true', help='Pause after every frame and wait for any key.')
parser.add_argument('--output-dir', dest='output', help='Specify a directory for output data.')
parser.add_argument('--quiet', dest='quiet', action='store_true', help='Do not show graphical output (Useful in combination with --output-dir ).')
parser.add_argument('--skip', dest='skip', action='store', default=None, help='Skip the first n frames', type=int)

args = parser.parse_args()

CMT.estimate_scale = args.estimate_scale
CMT.estimate_rotation = args.estimate_rotation

if args.pause:
	pause_time = 0
else:
	pause_time = 10

if args.output is not None:
	if not os.path.exists(args.output):
		os.mkdir(args.output)
	elif not os.path.isdir(args.output):
		raise Exception(args.output + ' exists, but is not a directory')

if args.challenge:
	with open('images.txt') as f:
		images = [line.strip() for line in f]

	init_region = np.genfromtxt('region.txt', delimiter=',')
	num_frames = len(images)

	results = empty((num_frames, 4))
	results[:] = nan

	results[0, :] = init_region

	frame = 0

	im0 = cv2.imread(images[frame])
	im_gray0 = cv2.cvtColor(im0, cv2.COLOR_BGR2GRAY)
	im_draw = np.copy(im0)

	tl, br = (util.array_to_int_tuple(init_region[:2]), util.array_to_int_tuple(init_region[:2] + init_region[2:4] - 1))

	try:
		CMT.initialise(im_gray0, tl, br)
		while frame < num_frames:
			im = cv2.imread(images[frame])
			im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
			CMT.process_frame(im_gray)
			results[frame, :] = CMT.bb

			# Advance frame number
			frame += 1
	except:
		pass  # Swallow errors

	np.savetxt('output.txt', results, delimiter=',')

else:
	# Clean up
	cv2.destroyAllWindows()

	preview = args.preview

	if args.inputpath is not None:

		# If a path to a file was given, assume it is a single video file
		if os.path.isfile(args.inputpath):
			cap = cv2.VideoCapture(args.inputpath)

			#Skip first frames if required
			if args.skip is not None:
				cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, args.skip)

		# Otherwise assume it is a format string for reading images
		else:
			cap = util.FileVideoCapture(args.inputpath)

			#Skip first frames if required
			if args.skip is not None:
				cap.frame = 1 + args.skip

		# By default do not show preview in both cases
		if preview is None:
			preview = False

	else:
		# If no input path was specified, open camera device
		cap = cv2.VideoCapture(0)
		if preview is None:
			preview = True

	# Check if videocapture is working
	if not cap.isOpened():
		print 'Unable to open video input.'
		sys.exit(1)

	while preview:
		status, im = cap.read()
		cv2.imshow('Preview', im)
		k = cv2.waitKey(10)
		if not k == -1:
			break

	# Read first frame
	status, im0 = cap.read()
	im_gray0 = cv2.cvtColor(im0, cv2.COLOR_BGR2GRAY)
	im_draw = np.copy(im0)

	if args.bbox is not None:
		# Try to disassemble user specified bounding box
		values = args.bbox.split(',')
		try:
			values = [int(v) for v in values]
		except:
			raise Exception('Unable to parse bounding box')
		if len(values) != 4:
			raise Exception('Bounding box must have exactly 4 elements')
		bbox = np.array(values)

		# Convert to point representation, adding singleton dimension
		bbox = util.bb2pts(bbox[None, :])

		# Squeeze
		bbox = bbox[0, :]

		tl = bbox[:2]
		br = bbox[2:4]
	else:
		# Get rectangle input from user
		(tl, br) = util.get_rect(im_draw)

	print 'using', tl, br, 'as init bb'

	CMT.initialise(im_gray0, tl, br)

	frame = 1
	while True:
		# Read image
		status, im = cap.read()
		if not status:
			break
		im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
		im_draw = np.copy(im)

		tic = time.time()
		CMT.process_frame(im_gray)
		toc = time.time()

		# Display results

		# Draw updated estimate
		if CMT.has_result:

			cv2.line(im_draw, CMT.tl, CMT.tr, (255, 0, 0), 4)
			cv2.line(im_draw, CMT.tr, CMT.br, (255, 0, 0), 4)
			cv2.line(im_draw, CMT.br, CMT.bl, (255, 0, 0), 4)
			cv2.line(im_draw, CMT.bl, CMT.tl, (255, 0, 0), 4)

		util.draw_keypoints(CMT.tracked_keypoints, im_draw, (255, 255, 255))
		# this is from simplescale
		util.draw_keypoints(CMT.votes[:, :2], im_draw)  # blue
		util.draw_keypoints(CMT.outliers[:, :2], im_draw, (0, 0, 255))

		if args.output is not None:
			# Original image
			cv2.imwrite('{0}/input_{1:08d}.png'.format(args.output, frame), im)
			# Output image
			cv2.imwrite('{0}/output_{1:08d}.png'.format(args.output, frame), im_draw)

			# Keypoints
			with open('{0}/keypoints_{1:08d}.csv'.format(args.output, frame), 'w') as f:
				f.write('x y\n')
				np.savetxt(f, CMT.tracked_keypoints[:, :2], fmt='%.2f')

			# Outlier
			with open('{0}/outliers_{1:08d}.csv'.format(args.output, frame), 'w') as f:
				f.write('x y\n')
				np.savetxt(f, CMT.outliers, fmt='%.2f')

			# Votes
			with open('{0}/votes_{1:08d}.csv'.format(args.output, frame), 'w') as f:
				f.write('x y\n')
				np.savetxt(f, CMT.votes, fmt='%.2f')

			# Bounding box
			with open('{0}/bbox_{1:08d}.csv'.format(args.output, frame), 'w') as f:
				f.write('x y\n')
				# Duplicate entry tl is not a mistake, as it is used as a drawing instruction
				np.savetxt(f, np.array((CMT.tl, CMT.tr, CMT.br, CMT.bl, CMT.tl)), fmt='%.2f')

		if not args.quiet:
			cv2.imshow('main', im_draw)

			# Check key input
			k = cv2.waitKey(pause_time)
			key = chr(k & 255)
			if key == 'q':
				break
			if key == 'd':
				import ipdb; ipdb.set_trace()

		# Remember image
		im_prev = im_gray

		# Advance frame number
		frame += 1

		print '{5:04d}: center: {0:.2f},{1:.2f} scale: {2:.2f}, active: {3:03d}, {4:04.0f}ms'.format(CMT.center[0], CMT.center[1], CMT.scale_estimate, CMT.active_keypoints.shape[0], 1000 * (toc - tic), frame)
<|endoftext|>


<commit_before>import os
import unittest
from git import Repo
from six import text_type

VERBOSE = True

if os.path.exists('vigra_cmake'):
    if not os.path.isdir('vigra_cmake'):
        raise RuntimeError('"vigra_cmake" is not a directory')
    print("The vigra_cmake repository already exists.")
else:
    print("Cloning the vigra_cmake repository.")
    Repo.clone_from(
        "https://github.com/vigralibs/vigra_cmake.git", "vigra_cmake")
    repo = Repo("vigra_cmake")

def run_unbuffered_command(raw_command, directory, **kwargs):
    import shlex
    from subprocess import Popen, PIPE, STDOUT
    proc = Popen(shlex.split(raw_command), cwd=directory,
                 stdout=PIPE, stderr=STDOUT, **kwargs)
    output = ''
    while True:
        line = proc.stdout.readline()
        if not line:
            break
        line = text_type(line, 'utf-8', errors='ignore')
        if VERBOSE:
            print(line[:-1])
        output += line
    proc.communicate()
    if proc.returncode:
        raise RuntimeError(output)
    return output

def grep(s, substr):
    l = s.split('\n')
    return '\n'.join([_ for _ in l if substr in _])

def default_build_dir(testname):
    import os
    base_dir = os.path.dirname(os.path.realpath(__file__))
    return os.path.join(base_dir, testname, 'build')

def default_external_dir(testname):
    import os
    base_dir = os.path.dirname(os.path.realpath(__file__))
    return os.path.join(base_dir, testname, 'external')

def rm_fr(path):
    import os
    import shutil
    import stat
    def del_rw(action, name, exc):
        os.chmod(name, stat.S_IWRITE)
        os.remove(name)
    if os.path.isdir(path) and not os.path.islink(path):
        # NOTE: the idea here is that certain git dirs in Windows
        # might be read-only after checkout by cmake, and that prevents
        # rmtree from working. We then forcibly remove the read-only flag
        # and remove the offending file.
        shutil.rmtree(path, onerror=del_rw)
    elif os.path.exists(path):
        os.remove(path)

def cmake_configure(testname, extra_param=None):
    import shutil
    import os
    build_dir = default_build_dir(testname)
    if os.path.exists(build_dir):
        if VERBOSE:
            print("Removing previous build dir: " + build_dir)
        shutil.rmtree(build_dir)
    if VERBOSE:
        print("Creating build dir: " + build_dir)
    os.mkdir(build_dir)
    if extra_param is None:
        return run_unbuffered_command(r'cmake ..', build_dir)
    else:
        return run_unbuffered_command(r'cmake .. ' + extra_param, build_dir)

def cmake_build(testname):
    build_dir = default_build_dir(testname)
    return run_unbuffered_command(r'cmake --build .', build_dir)

def cmake_test(testname, extra_param=None):
    build_dir = default_build_dir(testname)
    if extra_param is None:
        return run_unbuffered_command(r'ctest', build_dir)
    else:
        return run_unbuffered_command(r'ctest ' + extra_param, build_dir)

class zlib_test_00(unittest.TestCase):

    def test_main(self):
        import platform
        tname = type(self).__name__
        if 'Windows' in platform.system():
            return
        rm_fr(default_build_dir(tname))
        rm_fr(default_external_dir(tname))
        cmake_configure(tname)
        cmake_build(tname)
        cmake_test(tname)

class zlib_test_01(unittest.TestCase):

    def test_main(self):
        import os
        import platform
        tname = type(self).__name__
        include_dirs = [os.path.join(tname, 'external', 'ZLIB'), os.path.join(
            tname, 'external', 'ZLIB', 'build_external_dep')]
        rm_fr(default_build_dir(tname))
        rm_fr(default_external_dir(tname))
        if 'Windows' in platform.system():
            conf_opts = '-G "Visual Studio 14 2015 Win64"'
            test_opts = '-C Debug'
        else:
            conf_opts = None
            test_opts = None
        cmake_configure(tname, conf_opts)
        out = grep(cmake_build(tname), 'main.cpp')
        # Check that the include dirs of the live dependency are passed in
        # while building main.
        self.assertTrue(grep(out, include_dirs[0]))
        self.assertTrue(grep(out, include_dirs[1]))
        if 'Windows' in platform.system():
            original_path = os.environ['PATH']
            fpath = open(os.path.join(default_build_dir(
                tname), '.vad', 'vad_path_Debug'))
            extra_path = fpath.readline()[:-1]
            fpath.close()
            os.environ['PATH'] = extra_path + ';' + os.environ['PATH']
        cmake_test(tname, test_opts)
        if 'Windows' in platform.system():
            os.environ['PATH'] = original_path

class tiff_test_00(unittest.TestCase):

    def test_main(self):
        import platform
        tname = type(self).__name__
        if 'Windows' in platform.system():
            return
        rm_fr(default_build_dir(tname))
        rm_fr(default_external_dir(tname))
        cmake_configure(tname)
        cmake_build(tname)
        cmake_test(tname)

class tiff_test_01(unittest.TestCase):

    def test_main(self):
        import os
        import platform
        tname = type(self).__name__
        include_dirs = [os.path.join(tname, 'external', 'TIFF'), os.path.join(
            tname, 'external', 'TIFF', 'build_external_dep')]
        rm_fr(default_build_dir(tname))
        rm_fr(default_external_dir(tname))
        if 'Windows' in platform.system():
            conf_opts = '-G "Visual Studio 14 2015 Win64"'
            test_opts = '-C Debug'
        else:
            conf_opts = None
            test_opts = None
        cmake_configure(tname, conf_opts)
        out = grep(cmake_build(tname), 'main.cpp')
        # Check that the include dirs of the live dependency are passed in
        # while building main.
        self.assertTrue(grep(out, include_dirs[0]))
        self.assertTrue(grep(out, include_dirs[1]))
        if 'Windows' in platform.system():
            original_path = os.environ['PATH']
            fpath = open(os.path.join(default_build_dir(
                tname), '.vad', 'vad_path_Debug'))
            extra_path = fpath.readline()[:-1]
            fpath.close()
            print("Adding the following entries to the PATH: " + extra_path)
            os.environ['PATH'] = extra_path + ';' + os.environ['PATH']
        cmake_test(tname, test_opts)
        if 'Windows' in platform.system():
            os.environ['PATH'] = original_path

if __name__ == '__main__':
    unittest.main()
<commit_msg>Try a context manager for setting the path.<commit_after>import os
import unittest
from git import Repo
from six import text_type

VERBOSE = True

if os.path.exists('vigra_cmake'):
    if not os.path.isdir('vigra_cmake'):
        raise RuntimeError('"vigra_cmake" is not a directory')
    print("The vigra_cmake repository already exists.")
else:
    print("Cloning the vigra_cmake repository.")
    Repo.clone_from(
        "https://github.com/vigralibs/vigra_cmake.git", "vigra_cmake")
    repo = Repo("vigra_cmake")

def run_unbuffered_command(raw_command, directory, **kwargs):
    import shlex
    from subprocess import Popen, PIPE, STDOUT
    proc = Popen(shlex.split(raw_command), cwd=directory,
                 stdout=PIPE, stderr=STDOUT, **kwargs)
    output = ''
    while True:
        line = proc.stdout.readline()
        if not line:
            break
        line = text_type(line, 'utf-8', errors='ignore')
        if VERBOSE:
            print(line[:-1])
        output += line
    proc.communicate()
    if proc.returncode:
        raise RuntimeError(output)
    return output

def grep(s, substr):
    l = s.split('\n')
    return '\n'.join([_ for _ in l if substr in _])

def default_build_dir(testname):
    import os
    base_dir = os.path.dirname(os.path.realpath(__file__))
    return os.path.join(base_dir, testname, 'build')

def default_external_dir(testname):
    import os
    base_dir = os.path.dirname(os.path.realpath(__file__))
    return os.path.join(base_dir, testname, 'external')

def rm_fr(path):
    import os
    import shutil
    import stat
    def del_rw(action, name, exc):
        os.chmod(name, stat.S_IWRITE)
        os.remove(name)
    if os.path.isdir(path) and not os.path.islink(path):
        # NOTE: the idea here is that certain git dirs in Windows
        # might be read-only after checkout by cmake, and that prevents
        # rmtree from working. We then forcibly remove the read-only flag
        # and remove the offending file.
        shutil.rmtree(path, onerror=del_rw)
    elif os.path.exists(path):
        os.remove(path)

def cmake_configure(testname, extra_param=None):
    import shutil
    import os
    build_dir = default_build_dir(testname)
    if os.path.exists(build_dir):
        if VERBOSE:
            print("Removing previous build dir: " + build_dir)
        shutil.rmtree(build_dir)
    if VERBOSE:
        print("Creating build dir: " + build_dir)
    os.mkdir(build_dir)
    if extra_param is None:
        return run_unbuffered_command(r'cmake ..', build_dir)
    else:
        return run_unbuffered_command(r'cmake .. ' + extra_param, build_dir)

def cmake_build(testname):
    build_dir = default_build_dir(testname)
    return run_unbuffered_command(r'cmake --build .', build_dir)

def cmake_test(testname, extra_param=None):
    build_dir = default_build_dir(testname)
    if extra_param is None:
        return run_unbuffered_command(r'ctest', build_dir)
    else:
        return run_unbuffered_command(r'ctest ' + extra_param, build_dir)

class path_ctx(object):

    def __init__(self, tname):
        self._tname = tname

    def __enter__(self):
        import platform
        import os
        if 'Windows' in platform.system():
            self._original_path = os.environ['PATH']
            with open(os.path.join(default_build_dir(self._tname), '.vad', 'vad_path_Debug')) as fpath:
                extra_path = fpath.readline()[:-1]
            os.environ['PATH'] = extra_path + ';' + os.environ['PATH']

    def __exit__(self, *args):
        import platform
        import os
        if 'Windows' in platform.system():
            os.environ['PATH'] = self._original_path

class zlib_test_00(unittest.TestCase):

    def test_main(self):
        import platform
        tname = type(self).__name__
        if 'Windows' in platform.system():
            return
        rm_fr(default_build_dir(tname))
        rm_fr(default_external_dir(tname))
        cmake_configure(tname)
        cmake_build(tname)
        cmake_test(tname)

class zlib_test_01(unittest.TestCase):

    def test_main(self):
        import os
        import platform
        tname = type(self).__name__
        include_dirs = [os.path.join(tname, 'external', 'ZLIB'), os.path.join(
            tname, 'external', 'ZLIB', 'build_external_dep')]
        rm_fr(default_build_dir(tname))
        rm_fr(default_external_dir(tname))
        if 'Windows' in platform.system():
            conf_opts = '-G "Visual Studio 14 2015 Win64"'
            test_opts = '-C Debug'
        else:
            conf_opts = None
            test_opts = None
        cmake_configure(tname, conf_opts)
        out = grep(cmake_build(tname), 'main.cpp')
        # Check that the include dirs of the live dependency are passed in
        # while building main.
        self.assertTrue(grep(out, include_dirs[0]))
        self.assertTrue(grep(out, include_dirs[1]))
        with path_ctx(tname):
            cmake_test(tname, test_opts)

class tiff_test_00(unittest.TestCase):

    def test_main(self):
        import platform
        tname = type(self).__name__
        if 'Windows' in platform.system():
            return
        rm_fr(default_build_dir(tname))
        rm_fr(default_external_dir(tname))
        cmake_configure(tname)
        cmake_build(tname)
        cmake_test(tname)

class tiff_test_01(unittest.TestCase):

    def test_main(self):
        import os
        import platform
        tname = type(self).__name__
        include_dirs = [os.path.join(tname, 'external', 'TIFF'), os.path.join(
            tname, 'external', 'TIFF', 'build_external_dep')]
        rm_fr(default_build_dir(tname))
        rm_fr(default_external_dir(tname))
        if 'Windows' in platform.system():
            conf_opts = '-G "Visual Studio 14 2015 Win64"'
            test_opts = '-C Debug'
        else:
            conf_opts = None
            test_opts = None
        cmake_configure(tname, conf_opts)
        out = grep(cmake_build(tname), 'main.cpp')
        # Check that the include dirs of the live dependency are passed in
        # while building main.
        self.assertTrue(grep(out, include_dirs[0]))
        self.assertTrue(grep(out, include_dirs[1]))
        with path_ctx(tname):
            cmake_test(tname, test_opts)

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


<commit_before>#!/usr/bin/env python
"""
Run sasview in place.  This allows sasview to use the python
files in the source tree without having to call setup.py install
first.  A rebuild is still necessary when working on sas models
or c modules.

Usage:

./run.py [(module|script) args...]

Without arguments run.py runs sasview.  With arguments, run.py will run
the given module or script.
"""

import imp
import logging
import logging.config
import os
import sys
from contextlib import contextmanager
from os.path import join as joinpath
from os.path import abspath, dirname

try:
    # running from a local computer as developer
    from sasview.logger_config import SetupLogger
except ImportError:
    from logger_config import SetupLogger

l = SetupLogger(__name__)
logger = l.config_development()

def addpath(path):
    """
    Add a directory to the python path environment, and to the PYTHONPATH
    environment variable for subprocesses.
    """
    path = abspath(path)
    if 'PYTHONPATH' in os.environ:
        PYTHONPATH = path + os.pathsep + os.environ['PYTHONPATH']
    else:
        PYTHONPATH = path
    os.environ['PYTHONPATH'] = PYTHONPATH
    sys.path.insert(0, path)

@contextmanager
def cd(path):
    """
    Change directory for duration of "with" context.
    """
    old_dir = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(old_dir)

def import_package(modname, path):
    """Import a package into a particular point in the python namespace"""
    mod = imp.load_source(modname, abspath(joinpath(path,'__init__.py')))
    sys.modules[modname] = mod
    mod.__path__ = [abspath(path)]
    return mod

def import_dll(modname, build_path):
    """Import a DLL from the build directory"""
    import sysconfig
    ext = sysconfig.get_config_var('SO')
    # build_path comes from context
    path = joinpath(build_path, *modname.split('.'))+ext
    #print "importing", modname, "from", path
    return imp.load_dynamic(modname, path)

def prepare():
    # Don't create *.pyc files
    sys.dont_write_bytecode = True

    # Debug numpy warnings
    #import numpy; numpy.seterr(all='raise')

    # find the directories for the source and build
    from distutils.util import get_platform
    root = abspath(dirname(__file__))
    platform = '%s-%s'%(get_platform(),sys.version[:3])
    build_path = joinpath(root, 'build','lib.'+platform)

    # Notify the help menu that the Sphinx documentation is in a different
    # place than it otherwise would be.
    os.environ['SASVIEW_DOC_PATH'] = joinpath(build_path, "doc")

    # Make sure that we have a private version of mplconfig
    #mplconfig = joinpath(abspath(dirname(__file__)), '.mplconfig')
    #os.environ['MPLCONFIGDIR'] = mplconfig
    #if not os.path.exists(mplconfig): os.mkdir(mplconfig)
    #import matplotlib
    #matplotlib.use('Agg')
    #print matplotlib.__file__
    #import pylab; pylab.hold(False)
    # add periodictable to the path
    try: import periodictable
    except: addpath(joinpath(root, '..','periodictable'))

    try: import bumps
    except: addpath(joinpath(root, '..','bumps'))

    # select wx version
    #addpath(os.path.join(root, '..','wxPython-src-3.0.0.0','wxPython'))

    # Build project if the build directory does not already exist.
    if not os.path.exists(build_path):
        import subprocess
        with cd(root):
            subprocess.call((sys.executable, "setup.py", "build"), shell=False)

    # Put the source trees on the path
    addpath(joinpath(root, 'src'))

    # sasmodels on the path
    addpath(joinpath(root, '../sasmodels/'))

    # Import the sasview package from root/sasview as sas.sasview.  It would
    # be better to just store the package in src/sas/sasview.
    import sas
    sas.sasview = import_package('sas.sasview', joinpath(root,'sasview'))

    # The sas.models package Compiled Model files should be pulled in from the build directory even though
    # the source is stored in src/sas/models.

    # Compiled modules need to be pulled from the build directory.
    # Some packages are not where they are needed, so load them explicitly.
    import sas.sascalc.pr
    sas.sascalc.pr.core = import_package('sas.sascalc.pr.core',
                                  joinpath(build_path, 'sas', 'sascalc', 'pr', 'core'))

    # Compiled modules need to be pulled from the build directory.
    # Some packages are not where they are needed, so load them explicitly.
    import sas.sascalc.file_converter
    sas.sascalc.file_converter.core = import_package('sas.sascalc.file_converter.core',
                                  joinpath(build_path, 'sas', 'sascalc', 'file_converter', 'core'))

    # Compiled modules need to be pulled from the build directory.
    # Some packages are not where they are needed, so load them explicitly.
    import sas.sascalc.calculator
    sas.sascalc.calculator.core = import_package('sas.sascalc.calculator.core',
                                  joinpath(build_path, 'sas', 'sascalc', 'calculator', 'core'))

    sys.path.append(build_path)

    #print "\n".join(sys.path)

if __name__ == "__main__":
    logger.debug("Starting SASVIEW in debug mode.")
    prepare()
    from sas.sasview.sasview import run
    run()
    logger.debug("Ending SASVIEW in debug mode.")
<commit_msg>Trying to fix logger import by setting absolute path<commit_after>#!/usr/bin/env python
"""
Run sasview in place.  This allows sasview to use the python
files in the source tree without having to call setup.py install
first.  A rebuild is still necessary when working on sas models
or c modules.

Usage:

./run.py [(module|script) args...]

Without arguments run.py runs sasview.  With arguments, run.py will run
the given module or script.
"""

import imp
import logging
import logging.config
import os
import sys
from contextlib import contextmanager
from os.path import join as joinpath
from os.path import abspath, dirname

def addpath(path):
    """
    Add a directory to the python path environment, and to the PYTHONPATH
    environment variable for subprocesses.
    """
    path = abspath(path)
    if 'PYTHONPATH' in os.environ:
        PYTHONPATH = path + os.pathsep + os.environ['PYTHONPATH']
    else:
        PYTHONPATH = path
    os.environ['PYTHONPATH'] = PYTHONPATH
    sys.path.insert(0, path)

root = abspath(dirname(__file__))
addpath(joinpath(root, 'sasview'))
from logger_config import SetupLogger

#try:
#    # running from a local computer as developer
#    from sasview.logger_config import SetupLogger
#except ImportError:
#    from logger_config import SetupLogger

l = SetupLogger(__name__)
logger = l.config_development()

@contextmanager
def cd(path):
    """
    Change directory for duration of "with" context.
    """
    old_dir = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(old_dir)

def import_package(modname, path):
    """Import a package into a particular point in the python namespace"""
    mod = imp.load_source(modname, abspath(joinpath(path,'__init__.py')))
    sys.modules[modname] = mod
    mod.__path__ = [abspath(path)]
    return mod

def import_dll(modname, build_path):
    """Import a DLL from the build directory"""
    import sysconfig
    ext = sysconfig.get_config_var('SO')
    # build_path comes from context
    path = joinpath(build_path, *modname.split('.'))+ext
    #print "importing", modname, "from", path
    return imp.load_dynamic(modname, path)

def prepare():
    # Don't create *.pyc files
    sys.dont_write_bytecode = True

    # Debug numpy warnings
    #import numpy; numpy.seterr(all='raise')

    # find the directories for the source and build
    from distutils.util import get_platform
    root = abspath(dirname(__file__))
    platform = '%s-%s'%(get_platform(),sys.version[:3])
    build_path = joinpath(root, 'build','lib.'+platform)

    # Notify the help menu that the Sphinx documentation is in a different
    # place than it otherwise would be.
    os.environ['SASVIEW_DOC_PATH'] = joinpath(build_path, "doc")

    # Make sure that we have a private version of mplconfig
    #mplconfig = joinpath(abspath(dirname(__file__)), '.mplconfig')
    #os.environ['MPLCONFIGDIR'] = mplconfig
    #if not os.path.exists(mplconfig): os.mkdir(mplconfig)
    #import matplotlib
    #matplotlib.use('Agg')
    #print matplotlib.__file__
    #import pylab; pylab.hold(False)
    # add periodictable to the path
    try: import periodictable
    except: addpath(joinpath(root, '..','periodictable'))

    try: import bumps
    except: addpath(joinpath(root, '..','bumps'))

    # select wx version
    #addpath(os.path.join(root, '..','wxPython-src-3.0.0.0','wxPython'))

    # Build project if the build directory does not already exist.
    if not os.path.exists(build_path):
        import subprocess
        with cd(root):
            subprocess.call((sys.executable, "setup.py", "build"), shell=False)

    # Put the source trees on the path
    addpath(joinpath(root, 'src'))

    # sasmodels on the path
    addpath(joinpath(root, '../sasmodels/'))

    # Import the sasview package from root/sasview as sas.sasview.  It would
    # be better to just store the package in src/sas/sasview.
    import sas
    sas.sasview = import_package('sas.sasview', joinpath(root,'sasview'))

    # The sas.models package Compiled Model files should be pulled in from the build directory even though
    # the source is stored in src/sas/models.

    # Compiled modules need to be pulled from the build directory.
    # Some packages are not where they are needed, so load them explicitly.
    import sas.sascalc.pr
    sas.sascalc.pr.core = import_package('sas.sascalc.pr.core',
                                  joinpath(build_path, 'sas', 'sascalc', 'pr', 'core'))

    # Compiled modules need to be pulled from the build directory.
    # Some packages are not where they are needed, so load them explicitly.
    import sas.sascalc.file_converter
    sas.sascalc.file_converter.core = import_package('sas.sascalc.file_converter.core',
                                  joinpath(build_path, 'sas', 'sascalc', 'file_converter', 'core'))

    # Compiled modules need to be pulled from the build directory.
    # Some packages are not where they are needed, so load them explicitly.
    import sas.sascalc.calculator
    sas.sascalc.calculator.core = import_package('sas.sascalc.calculator.core',
                                  joinpath(build_path, 'sas', 'sascalc', 'calculator', 'core'))

    sys.path.append(build_path)

    #print "\n".join(sys.path)

if __name__ == "__main__":
    logger.debug("Starting SASVIEW in debug mode.")
    prepare()
    from sas.sasview.sasview import run
    run()
    logger.debug("Ending SASVIEW in debug mode.")
<|endoftext|>


<commit_before>import re
import sys

from my_socket import TwitchChatSocket
from initialize import join_room
from read import get_user, get_message, tokenize_new_data
from settings import CHANNEL, POINTS_ALIAS, POINTS_COUNT, ADDED_POINTS, REMOVED_POINTS
from db import connect
from models import Viewer

def check_obj(obj, count):
    if obj:
        if count:
            return 'CURRENT OBJ: {}. {} left!'.format(obj, count)
        else:
            return 'CURRENT OBJ: {}'.format(obj)
    else:
        return 'Hey {} the people want an OBJ to check!'.format(CHANNEL)

class DonkeyBot(object):
    private_msg = re.compile('PRIVMSG #{}'.format(CHANNEL))

    def __init__(self):
        self.session = connect()
        self.afk = False
        self.obj = None
        self.obj_count = 0
        self.socket = TwitchChatSocket()
        join_room(self.socket)
        self.read_buffer = ''

    def get_viewer(self, nickname):
        '''
        Returns the first Viewer with the given nickname.

        @param nickname (str) - Nickname for the requested viewer
        @return (Viewer,None)
        '''
        return self.session.query(Viewer).filter_by(nickname=nickname).first()

    def add_viewer(self, nickname):
        '''
        Adds a new viewer with the given nickname.

        @param nickname (str) - Nickname for the new viewer
        @return (Viewer)
        '''
        viewer = Viewer(nickname=nickname)
        self.session.add(viewer)
        self.session.commit()
        return viewer

    def get_points(self, user):
        '''
        Returns the point count for a viewer with the given nickname.

        @param user (str) - Nickname of the viewer whose points are requested
        @return (int)
        '''
        viewer = self.get_viewer(user)
        return getattr(viewer, 'points', 0)

    def add_points(self, nickname, points):
        '''
        Adds given number of points to the viewer with the given nickname. Will add the viewer if no
        matching one already exists.

        @param nickname (str) - Nickname of the viewer
        @param points (int) - Number of points to award
        '''
        viewer = self.get_viewer(nickname) or self.add_viewer(nickname)
        viewer.points += int(points)
        self.session.commit()

    def remove_points(self, nickname, points):
        '''
        Removes given number of points from the viewer with the given nickname. Will add the viewer
        if no matching one already exists.

        @param nickname (str) - Nickname of the viewer
        @param points (int) - Number of points to demerit
        '''
        viewer = self.get_viewer(nickname) or self.add_viewer(nickname)
        viewer.points = max(viewer.points - int(points), 0)
        self.session.commit()

    def the_thing_donkey_bot_does(self):
        temp, self.read_buffer = tokenize_new_data(self.socket, self.read_buffer)

        if not len(temp):
            print('Socket must have closed')
            sys.exit()
        for line in temp:
            print(line)
            if line.startswith('PING'):
                self.socket.send_pong(line)
            elif self.private_msg.search(line):
                user = get_user(line)
                message = get_message(line)

                if re.match('^!afk', message.lower()):
                    if user.lower() == CHANNEL:
                        self.afk = True
                        self.socket.send_private_message('Have a nice break, {}!'.format(CHANNEL))
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif re.match('^!back', message.lower()):
                    if user.lower() == CHANNEL:
                        if self.afk:
                            self.afk = False
                            self.socket.send_private_message('wb {}!'.format(CHANNEL))
                        else:
                            self.socket.send_private_message("{}, you've literally been here the entire time FailFish".format(CHANNEL))
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif user.lower() not in [CHANNEL, 'donkey_bot'] and self.afk:
                    self.socket.send_private_message("{} is currently AFK. Don't worry, he'll be back soon!".format(CHANNEL))
                elif re.match('^!obj', message.lower()):
                    self.socket.send_private_message(check_obj(self.obj, self.obj_count))
                elif re.match('^!setobj', message.lower()):
                    if user.lower() == CHANNEL:
                        tokens = message.split()
                        if re.match(r'^\d+$', tokens[-1]):
                            self.obj_count = tokens[-1]
                            self.obj = ' '.join(tokens[1:-1])
                        else:
                            self.obj = ' '.join(tokens[1:])
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif re.match('^!incobj', message.lower()):
                    if user.lower() == CHANNEL:
                        tokens = message.split()
                        if re.match(r'^\d+$', tokens[-1]):
                            self.obj_count = str(int(self.obj_count) + int(tokens[-1]))
                        else:
                            self.socket.send_private_message("That ain't a number brah")
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif re.match('^!decobj', message.lower()):
                    if user.lower() == CHANNEL:
                        tokens = message.split()
                        if re.match(r'^\d+$', tokens[-1]):
                            self.obj_count = str(int(self.obj_count) - int(tokens[-1]))
                        else:
                            self.socket.send_private_message("That ain't a number brah")
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif re.match('^!(points|{})'.format(POINTS_ALIAS), message.lower()):
                    tokens = message.split()
                    modifier = None
                    if len(tokens) > 1:
                        iterator = iter(tokens)
                        iterator.next()
                        modifier = iterator.next()
                        args = list(iterator)
                    if modifier == 'add':
                        if user.lower() == CHANNEL:
                            # Adds points to the given viewer. Only callable by the broadcaster.
                            points, viewer = args
                            self.add_points(viewer, points)
                            self.socket.send_private_message(ADDED_POINTS.format(points=points, viewer=viewer, point_alias=POINTS_ALIAS))
                        else:
                            self.socket.send_private_message("{} suh dude? You know you can't do that!".format(user))
                    elif modifier == 'remove':
                        if user.lower() == CHANNEL:
                            # Removes points from the given viewer, but will never go below 0 total points.
                            # Only callable by the broadcaster.
                            points, viewer = args
                            self.remove_points(viewer, points)
                            self.socket.send_private_message(REMOVED_POINTS.format(points=points, viewer=viewer, point_alias=POINTS_ALIAS))
                        else:
                            self.socket.send_private_message("{} suh dude? You know you can't do that!".format(user))
                    else:
                        # Command is customizable by the POINTS_ALIAS setting. Reports calling viewer's total points
                        points = self.get_points(user)
                        self.socket.send_private_message(POINTS_COUNT.format(viewer=user, points=points, point_alias=POINTS_ALIAS))

if __name__ == '__main__':
    bot = DonkeyBot()
    while True:
        bot.the_thing_donkey_bot_does()

<commit_msg>Add '!honkey' game<commit_after>import re
import sys
from datetime import datetime
from dateutil.relativedelta import relativedelta
from random import choice

from my_socket import TwitchChatSocket
from initialize import join_room
from read import get_user, get_message, tokenize_new_data
from settings import CHANNEL, IDENTITY, POINTS_ALIAS, POINTS_COUNT, ADDED_POINTS, REMOVED_POINTS
from db import connect
from models import Viewer

def check_obj(obj, count):
    if obj:
        if count:
            return 'CURRENT OBJ: {}. {} left!'.format(obj, count)
        else:
            return 'CURRENT OBJ: {}'.format(obj)
    else:
        return 'Hey {} the people want an OBJ to check!'.format(CHANNEL)

class DonkeyBot(object):
    private_msg = re.compile('PRIVMSG #{}'.format(CHANNEL))

    def __init__(self):
        self.session = connect()
        self.afk = False
        self.obj = None
        self.obj_count = 0
        self.read_buffer = ''
        self.active_chatters = {}
        self.socket = TwitchChatSocket()
        join_room(self.socket)

    def get_viewer(self, nickname):
        '''
        Returns the first Viewer with the given nickname.

        @param nickname (str) - Nickname for the requested viewer
        @return (Viewer,None)
        '''
        return self.session.query(Viewer).filter_by(nickname=nickname).first()

    def add_viewer(self, nickname):
        '''
        Adds a new viewer with the given nickname.

        @param nickname (str) - Nickname for the new viewer
        @return (Viewer)
        '''
        viewer = Viewer(nickname=nickname)
        self.session.add(viewer)
        self.session.commit()
        return viewer

    def get_points(self, user):
        '''
        Returns the point count for a viewer with the given nickname.

        @param user (str) - Nickname of the viewer whose points are requested
        @return (int)
        '''
        viewer = self.get_viewer(user)
        return getattr(viewer, 'points', 0)

    def add_points(self, nickname, points):
        '''
        Adds given number of points to the viewer with the given nickname. Will add the viewer if no
        matching one already exists.

        @param nickname (str) - Nickname of the viewer
        @param points (int) - Number of points to award
        '''
        viewer = self.get_viewer(nickname) or self.add_viewer(nickname)
        viewer.points += int(points)
        self.session.commit()

    def remove_points(self, nickname, points):
        '''
        Removes given number of points from the viewer with the given nickname. Will add the viewer
        if no matching one already exists.

        @param nickname (str) - Nickname of the viewer
        @param points (int) - Number of points to demerit
        '''
        viewer = self.get_viewer(nickname) or self.add_viewer(nickname)
        viewer.points = max(viewer.points - int(points), 0)
        self.session.commit()

    def record_chat_activity(self, nickname):
        '''
        Updates the given viewer's most recent chat time (stored in memory for now). Ignores the
        executing bot as well as nightbot.

        @param nickname (str) - Nickname of the viewer
        '''
        if nickname not in [IDENTITY, 'nightbot']:
            now = datetime.now()
            self.active_chatters[nickname] = now

    def prune_chat_activity(self, seconds):
        '''
        Prunes recent chatters mapping based on the given time range. Viewers must have chatted
        within the given number of seconds in order to be considered active.

        @param seconds (int) - Number of seconds to consider active chat window
        '''
        time_zero = datetime.now() - relativedelta(seconds=seconds)
        self.active_chatters = {
            chatter: chat_time for chatter, chat_time in self.active_chatters.iteritems() if chat_time > time_zero}

    def the_thing_donkey_bot_does(self):
        temp, self.read_buffer = tokenize_new_data(self.socket, self.read_buffer)

        if not len(temp):
            print('Socket must have closed')
            sys.exit()
        for line in temp:
            print(line)
            if line.startswith('PING'):
                self.socket.send_pong(line)
            elif self.private_msg.search(line):
                user = get_user(line)
                message = get_message(line)

                self.record_chat_activity(user)
                if re.match('^!afk', message.lower()):
                    if user.lower() == CHANNEL:
                        self.afk = True
                        self.socket.send_private_message('Have a nice break, {}!'.format(CHANNEL))
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif re.match('^!back', message.lower()):
                    if user.lower() == CHANNEL:
                        if self.afk:
                            self.afk = False
                            self.socket.send_private_message('wb {}!'.format(CHANNEL))
                        else:
                            self.socket.send_private_message("{}, you've literally been here the entire time FailFish".format(CHANNEL))
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif user.lower() not in [CHANNEL, 'donkey_bot'] and self.afk:
                    self.socket.send_private_message("{} is currently AFK. Don't worry, he'll be back soon!".format(CHANNEL))
                elif re.match('^!obj', message.lower()):
                    self.socket.send_private_message(check_obj(self.obj, self.obj_count))
                elif re.match('^!setobj', message.lower()):
                    if user.lower() == CHANNEL:
                        tokens = message.split()
                        if re.match(r'^\d+$', tokens[-1]):
                            self.obj_count = tokens[-1]
                            self.obj = ' '.join(tokens[1:-1])
                        else:
                            self.obj = ' '.join(tokens[1:])
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif re.match('^!incobj', message.lower()):
                    if user.lower() == CHANNEL:
                        tokens = message.split()
                        if re.match(r'^\d+$', tokens[-1]):
                            self.obj_count = str(int(self.obj_count) + int(tokens[-1]))
                        else:
                            self.socket.send_private_message("That ain't a number brah")
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif re.match('^!decobj', message.lower()):
                    if user.lower() == CHANNEL:
                        tokens = message.split()
                        if re.match(r'^\d+$', tokens[-1]):
                            self.obj_count = str(int(self.obj_count) - int(tokens[-1]))
                        else:
                            self.socket.send_private_message("That ain't a number brah")
                    else:
                        self.socket.send_private_message("Sorry for the confusion {} That's a command for only {}".format(user, CHANNEL))
                elif re.match('^!(points|{})'.format(POINTS_ALIAS), message.lower()):
                    tokens = message.split()
                    modifier = None
                    if len(tokens) > 1:
                        iterator = iter(tokens)
                        iterator.next()
                        modifier = iterator.next()
                        args = list(iterator)
                    if modifier == 'add':
                        if user.lower() == CHANNEL:
                            # Adds points to the given viewer. Only callable by the broadcaster.
                            points, viewer = args
                            self.add_points(viewer, points)
                            self.socket.send_private_message(ADDED_POINTS.format(points=points, viewer=viewer, point_alias=POINTS_ALIAS))
                        else:
                            self.socket.send_private_message("{} suh dude? You know you can't do that!".format(user))
                    elif modifier == 'remove':
                        if user.lower() == CHANNEL:
                            # Removes points from the given viewer, but will never go below 0 total points.
                            # Only callable by the broadcaster.
                            points, viewer = args
                            self.remove_points(viewer, points)
                            self.socket.send_private_message(REMOVED_POINTS.format(points=points, viewer=viewer, point_alias=POINTS_ALIAS))
                        else:
                            self.socket.send_private_message("{} suh dude? You know you can't do that!".format(user))
                    else:
                        # Command is customizable by the POINTS_ALIAS setting. Reports calling viewer's total points
                        points = self.get_points(user)
                        self.socket.send_private_message(POINTS_COUNT.format(viewer=user, points=points, point_alias=POINTS_ALIAS))
                elif re.match('^!honkey', message.lower()):
                    # TODO holding onto this in case we want to use it later.
                    # response = requests.get('https://tmi.twitch.tv/group/user/{}/chatters'.format(CHANNEL),
                                            # headers={'Accept': 'application/json',
                                                     # 'Autorization': 'OAuth ' + STREAM_KEY,
                                                     # 'Content-Type': 'application/json'})
                    # print json.loads(response.text)
                    self.prune_chat_activity(300)
                    print self.active_chatters
                    chatters = self.active_chatters.keys()
                    winner = choice(chatters)
                    self.socket.send_private_message("{} about to honkey {}'s donkey! HONK!!! Kreygasm".format(user, winner))

if __name__ == '__main__':
    bot = DonkeyBot()
    while True:
        bot.the_thing_donkey_bot_does()

<|endoftext|>


<commit_before>#!/usr/bin/python
import os
import sys
from progressBar import progress
from exchange_ec2 import Exchange
from ConfigParser import SafeConfigParser
from time import sleep

flag = []

def cls():
    os.system('cls' if os.name == 'nt' else 'clear')

def limH(rate):
    parser = SafeConfigParser()
    parser.read('rate.conf')
    high_limit = parser.getfloat(rate, 'high')
    return high_limit

def limL(rate):
    parser = SafeConfigParser()
    parser.read('rate.conf')
    low_limit = parser.getfloat(rate, 'low')
    return low_limit

usdtwd = Exchange('USDTWD', max_rate=limH('usdtwd'), min_rate=limL('usdtwd'))
usdjpy = Exchange('USDJPY', max_rate=limH('usdjpy'), min_rate=limL('usdjpy'))
audusd = Exchange('AUDUSD', max_rate=limH('audusd'), min_rate=limL('audusd'))
audtwd = Exchange('AUDTWD', max_rate=None, min_rate=None)
eurtwd = Exchange('EURTWD', max_rate=None, min_rate=None)
twdjpy = Exchange('TWDJPY', max_rate=None, min_rate=None)
cnytwd = Exchange('CNYTWD', max_rate=None, min_rate=None)

exchanges = [usdtwd, usdjpy, audusd, audtwd, eurtwd, twdjpy, cnytwd]

while True:

    for ex in exchanges:
        ex.getExchange()
        ex.show()
        ex.threshold()
        ex.subscription()

    #sys.stdout.write('==========\n')
    #sys.stdout.flush()
    progress(40, 0.5)
<commit_msg>Change import file<commit_after>#!/usr/bin/python
import os
import sys
from progressBar import progress
from exchange import Exchange
from ConfigParser import SafeConfigParser
from time import sleep

flag = []

def cls():
    os.system('cls' if os.name == 'nt' else 'clear')

def limH(rate):
    parser = SafeConfigParser()
    parser.read('rate.conf')
    high_limit = parser.getfloat(rate, 'high')
    return high_limit

def limL(rate):
    parser = SafeConfigParser()
    parser.read('rate.conf')
    low_limit = parser.getfloat(rate, 'low')
    return low_limit

usdtwd = Exchange('USDTWD', max_rate=limH('usdtwd'), min_rate=limL('usdtwd'))
usdjpy = Exchange('USDJPY', max_rate=limH('usdjpy'), min_rate=limL('usdjpy'))
audusd = Exchange('AUDUSD', max_rate=limH('audusd'), min_rate=limL('audusd'))
audtwd = Exchange('AUDTWD', max_rate=None, min_rate=None)
eurtwd = Exchange('EURTWD', max_rate=None, min_rate=None)
twdjpy = Exchange('TWDJPY', max_rate=None, min_rate=None)
cnytwd = Exchange('CNYTWD', max_rate=None, min_rate=None)

exchanges = [usdtwd, usdjpy, audusd, audtwd, eurtwd, twdjpy, cnytwd]

while True:

    for ex in exchanges:
        ex.getExchange()
        ex.show()
        ex.threshold()
        ex.subscription()

    #sys.stdout.write('==========\n')
    #sys.stdout.flush()
    progress(40, 0.5)
<|endoftext|>


<commit_before>import os

def create (directory):
    dir = open(directory+'.sar', 'w')

    directory = {}
    for dirname, dirnames, filenames in os.walk('.', topdown = True):
        found = False
        #print ("mais externo "+ dirname)
        for s in directory:
            print ("s atual: "+s + " dirname atual: " + dirname)
            if (s == dirname):
                pass
                #print (s)
        directory[dirname] = []
        for subdirname in dirnames:
            directory[dirname].append(subdirname)
            #print("subdirname "+ subdirname)

        for filename in filenames:
            #print("filename "+ filename)
            directory[dirname].append(filename)
    #print (directory)

if __name__ == '__main__':
    create('abc')
<commit_msg>Corrigindo commit anterior<commit_after>import os

def create (directory):
    dir = open(directory+'.sar', 'w')

    directory = {}
    for dirname, dirnames, filenames in os.walk('.', topdown = True):
        found = False
        #print ("mais externo "+ dirname)
        for s in directory:
            print ("s atual: "+s + " dirname atual: " + dirname)
        directory[dirname] = []
        for subdirname in dirnames:
            directory[dirname].append(subdirname)
            #print("subdirname "+ subdirname)

        for filename in filenames:
            #print("filename "+ filename)
            directory[dirname].append(filename)
    print (directory)

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


<commit_before>################################################################################
# Copyright (C) 2015-2016 by Arena of Titans Contributors.
#
# This file is part of Arena of Titans.
#
# Arena of Titans is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Arena of Titans is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Arena of Titans. If not, see <http://www.gnu.org/licenses/>.
################################################################################

from aot.board import (
    Square,
    Color,
)
from aot.board import ColorSet
from aot.board.square import SquareSet
# board is a fixture, ignore the unsued import warnig
from aot.test import board

def test_number_squares(board):
    assert len(board) == 288

def test_get_wrong_squares(board):
    assert board[None] is None
    assert board[None, None] is None
    assert board[None, None, None] is None
    assert board[None, 0] is None
    assert board[0, None] is None
    assert board[200, 200] is None

def test_square_coords(board):
    assert board[0, 0] == Square(0, 0, 'yellow')
    assert board[7, 2] == Square(7, 2, 'yellow')
    assert board[-1, 0] == Square(31, 0, 'yellow')

def test_get_lines_squares(board):
    assert board.get_line_squares(board[0, 0], set(['blue'])) == set([
        Square(0, 1, 'blue')
    ])
    assert board.get_line_squares(board[7, 0], set(['yellow'])) == set([
        Square(6, 0, 'yellow'),
        Square(8, 0, 'yellow'),
    ])

def test_get_line_squares_multiple_colors(board):
    colors = set(['blue', 'yellow'])
    assert board.get_line_squares(board[0, 0], colors) == set([
        Square(0, 1, 'blue'),
        Square(1, 0, 'yellow'),
        Square(31, 0, 'yellow'),
    ])

def test_get_line_squares_all_colors(board):
    assert board.get_line_squares(board[0, 0], set(['all'])) == set([
        Square(0, 1, 'blue'),
        Square(1, 0, 'yellow'),
        Square(31, 0, 'yellow'),
    ])

def test_get_diagonal_squares(board):
    assert board.get_diagonal_squares(board[0, 0], set(['blue'])) == set([
        Square(1, 1, 'blue'),
        Square(31, 1, 'blue'),
    ])
    assert board.get_diagonal_squares(board[7, 0], set(['blue'])) == set([
        Square(8, 1, 'blue'),
        Square(6, 1, 'blue'),
    ])

def test_get_line_squares_occupied_square(board):
    board[0, 1].occupied = True
    assert board.get_line_squares(board[0, 0], set(['blue'])) == set([board[0, 1]])

def test_get_line_squares_arm(board):
    assert board.get_line_squares(board[0, 7], set(['black'])) == set()
    assert board.get_line_squares(board[3, 7], set(['red'])) == set()

def test_get_diagonal_squares_multiple_colors(board):
    colors = set(['black', 'yellow'])
    assert board.get_diagonal_squares(board[0, 1], colors) == set([
        Square(31, 0, 'yellow'),
        Square(1, 0, 'yellow'),
        Square(1, 2, 'black'),
        Square(31, 2, 'yellow'),
    ])

def test_get_diagonal_squares_all_colors(board):
    colors = set(['all'])
    assert board.get_diagonal_squares(board[0, 1], colors) == set([
        Square(31, 0, 'yellow'),
        Square(1, 0, 'yellow'),
        Square(1, 2, 'black'),
        Square(31, 2, 'yellow'),
    ])

def test_get_diagonal_squares_on_arm(board):
    assert board.get_diagonal_squares(board[0, 7], set(['black'])) == set()
    assert board.get_diagonal_squares(board[3, 7], set(['red'])) == set()
    assert board.get_diagonal_squares(board[0, 3], set(['yellow'])) == set([
        Square(31, 2, 'yellow'),
        Square(1, 4, 'yellow'),
    ])
    assert board.get_diagonal_squares(board[3, 3], set(['blue'])) == set([
        Square(2, 4, 'blue'),
        Square(4, 2, 'blue'),
    ])

def test_square_set_from_color():
    assert Color['BLUE'] in SquareSet([Color['BLUE']]).colors

def test_color_set():
    assert Color['BLUE'] in ColorSet([Color['BLUE']])

def test_get_neighbors(board):
    square = board[0, 8]
    neighbors = board.get_neighbors(square)
    assert neighbors == set([
        board[1, 8],
        board[1, 7],
        board[0, 7],
    ])

    square = board[1, 7]
    neighbors = board.get_neighbors(square)
    assert neighbors == set([
        board[2, 7],
        board[2, 8],
        board[1, 8],
        board[0, 8],
        board[0, 7],
        board[0, 6],
        board[1, 6],
        board[2, 6],
    ])

def test_get_neighbors_with_movements_types_line(board):
    square = board[0, 8]
    neighbors = board.get_neighbors(square, movements_types={'line'})
    assert neighbors == set([
        board[1, 8],
        board[0, 7],
    ])

def test_get_neighbors_with_movements_types_diagonal(board):
    square = board[0, 8]
    neighbors = board.get_neighbors(square, movements_types={'diagonal'})
    assert neighbors == set([
        board[1, 7],
    ])

def test_get_neighbors_with_movements_types_all(board):
    square = board[0, 8]
    neighbors = board.get_neighbors(square, movements_types={'diagonal', 'line'})
    assert neighbors == set([
        board[1, 8],
        board[1, 7],
        board[0, 7],
    ])
<commit_msg>test(board): add tests for get_neighbors from x1 and x31<commit_after>################################################################################
# Copyright (C) 2015-2016 by Arena of Titans Contributors.
#
# This file is part of Arena of Titans.
#
# Arena of Titans is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Arena of Titans is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Arena of Titans. If not, see <http://www.gnu.org/licenses/>.
################################################################################

from aot.board import (
    Square,
    Color,
)
from aot.board import ColorSet
from aot.board.square import SquareSet
# board is a fixture, ignore the unsued import warnig
from aot.test import board

def test_number_squares(board):
    assert len(board) == 288

def test_get_wrong_squares(board):
    assert board[None] is None
    assert board[None, None] is None
    assert board[None, None, None] is None
    assert board[None, 0] is None
    assert board[0, None] is None
    assert board[200, 200] is None

def test_square_coords(board):
    assert board[0, 0] == Square(0, 0, 'yellow')
    assert board[7, 2] == Square(7, 2, 'yellow')
    assert board[-1, 0] == Square(31, 0, 'yellow')

def test_get_lines_squares(board):
    assert board.get_line_squares(board[0, 0], set(['blue'])) == set([
        Square(0, 1, 'blue')
    ])
    assert board.get_line_squares(board[7, 0], set(['yellow'])) == set([
        Square(6, 0, 'yellow'),
        Square(8, 0, 'yellow'),
    ])

def test_get_line_squares_multiple_colors(board):
    colors = set(['blue', 'yellow'])
    assert board.get_line_squares(board[0, 0], colors) == set([
        Square(0, 1, 'blue'),
        Square(1, 0, 'yellow'),
        Square(31, 0, 'yellow'),
    ])

def test_get_line_squares_all_colors(board):
    assert board.get_line_squares(board[0, 0], set(['all'])) == set([
        Square(0, 1, 'blue'),
        Square(1, 0, 'yellow'),
        Square(31, 0, 'yellow'),
    ])

def test_get_diagonal_squares(board):
    assert board.get_diagonal_squares(board[0, 0], set(['blue'])) == set([
        Square(1, 1, 'blue'),
        Square(31, 1, 'blue'),
    ])
    assert board.get_diagonal_squares(board[7, 0], set(['blue'])) == set([
        Square(8, 1, 'blue'),
        Square(6, 1, 'blue'),
    ])

def test_get_line_squares_occupied_square(board):
    board[0, 1].occupied = True
    assert board.get_line_squares(board[0, 0], set(['blue'])) == set([board[0, 1]])

def test_get_line_squares_arm(board):
    assert board.get_line_squares(board[0, 7], set(['black'])) == set()
    assert board.get_line_squares(board[3, 7], set(['red'])) == set()

def test_get_diagonal_squares_multiple_colors(board):
    colors = set(['black', 'yellow'])
    assert board.get_diagonal_squares(board[0, 1], colors) == set([
        Square(31, 0, 'yellow'),
        Square(1, 0, 'yellow'),
        Square(1, 2, 'black'),
        Square(31, 2, 'yellow'),
    ])

def test_get_diagonal_squares_all_colors(board):
    colors = set(['all'])
    assert board.get_diagonal_squares(board[0, 1], colors) == set([
        Square(31, 0, 'yellow'),
        Square(1, 0, 'yellow'),
        Square(1, 2, 'black'),
        Square(31, 2, 'yellow'),
    ])

def test_get_diagonal_squares_on_arm(board):
    assert board.get_diagonal_squares(board[0, 7], set(['black'])) == set()
    assert board.get_diagonal_squares(board[3, 7], set(['red'])) == set()
    assert board.get_diagonal_squares(board[0, 3], set(['yellow'])) == set([
        Square(31, 2, 'yellow'),
        Square(1, 4, 'yellow'),
    ])
    assert board.get_diagonal_squares(board[3, 3], set(['blue'])) == set([
        Square(2, 4, 'blue'),
        Square(4, 2, 'blue'),
    ])

def test_square_set_from_color():
    assert Color['BLUE'] in SquareSet([Color['BLUE']]).colors

def test_color_set():
    assert Color['BLUE'] in ColorSet([Color['BLUE']])

def test_get_neighbors(board):
    square = board[0, 8]
    neighbors = board.get_neighbors(square)
    assert neighbors == set([
        board[1, 8],
        board[1, 7],
        board[0, 7],
    ])

    square = board[1, 7]
    neighbors = board.get_neighbors(square)
    assert neighbors == set([
        board[2, 7],
        board[2, 8],
        board[1, 8],
        board[0, 8],
        board[0, 7],
        board[0, 6],
        board[1, 6],
        board[2, 6],
    ])

def test_get_neighbors_with_movements_types_line(board):
    square = board[0, 8]
    neighbors = board.get_neighbors(square, movements_types={'line'})
    assert neighbors == set([
        board[1, 8],
        board[0, 7],
    ])

def test_get_neighbors_with_movements_types_diagonal(board):
    square = board[0, 8]
    neighbors = board.get_neighbors(square, movements_types={'diagonal'})
    assert neighbors == set([
        board[1, 7],
    ])

def test_get_neighbors_with_movements_types_all(board):
    square = board[0, 8]
    neighbors = board.get_neighbors(square, movements_types={'diagonal', 'line'})
    assert neighbors == set([
        board[1, 8],
        board[1, 7],
        board[0, 7],
    ])

def test_get_neighbors_x1_circle(board):
    square = board[0, 1]
    neighbors = board.get_neighbors(square, movements_types={'diagonal', 'line'})
    assert neighbors == set([
        board[0, 0],
        board[1, 0],
        board[1, 1],
        board[1, 2],
        board[0, 2],
        board[31, 2],
        board[31, 1],
        board[31, 0],
    ])

def test_get_neighbors_x31_circle(board):
    square = board[31, 1]
    neighbors = board.get_neighbors(square, movements_types={'diagonal', 'line'})
    assert neighbors == set([
        board[0, 0],
        board[0, 1],
        board[0, 2],
        board[30, 2],
        board[30, 1],
        board[30, 0],
        board[31, 0],
        board[31, 2],
    ])
<|endoftext|>