prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>contents.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)<|fim▁hole|>
class Contents:
@logtool.log_call
def __init__ (self, canvas, objects):
self.canvas = canvas
self.objects = objects
@logtool.log_call
def render (self):
with Page (self.canvas) as pg:
for obj in self.objects:
coords = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_type, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render ()<|fim▁end|> | |
<|file_name|>contents.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)
class Contents:
<|fim_middle|>
<|fim▁end|> | @logtool.log_call
def __init__ (self, canvas, objects):
self.canvas = canvas
self.objects = objects
@logtool.log_call
def render (self):
with Page (self.canvas) as pg:
for obj in self.objects:
coords = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_type, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render () |
<|file_name|>contents.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)
class Contents:
@logtool.log_call
def __init__ (self, canvas, objects):
<|fim_middle|>
@logtool.log_call
def render (self):
with Page (self.canvas) as pg:
for obj in self.objects:
coords = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_type, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render ()
<|fim▁end|> | self.canvas = canvas
self.objects = objects |
<|file_name|>contents.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)
class Contents:
@logtool.log_call
def __init__ (self, canvas, objects):
self.canvas = canvas
self.objects = objects
@logtool.log_call
def render (self):
<|fim_middle|>
<|fim▁end|> | with Page (self.canvas) as pg:
for obj in self.objects:
coords = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_type, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render () |
<|file_name|>contents.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)
class Contents:
@logtool.log_call
def <|fim_middle|> (self, canvas, objects):
self.canvas = canvas
self.objects = objects
@logtool.log_call
def render (self):
with Page (self.canvas) as pg:
for obj in self.objects:
coords = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_type, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render ()
<|fim▁end|> | __init__ |
<|file_name|>contents.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)
class Contents:
@logtool.log_call
def __init__ (self, canvas, objects):
self.canvas = canvas
self.objects = objects
@logtool.log_call
def <|fim_middle|> (self):
with Page (self.canvas) as pg:
for obj in self.objects:
coords = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_type, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render ()
<|fim▁end|> | render |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:<|fim▁hole|>
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])<|fim▁end|> | currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
<|fim_middle|>
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
<|fim_middle|>
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
<|fim_middle|>
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop() |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
<|fim_middle|>
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | return True |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
<|fim_middle|>
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | return False |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
<|fim_middle|>
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | return False |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
<|fim_middle|>
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | continue |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
<|fim_middle|>
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
<|fim_middle|>
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop() |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
<|fim_middle|>
<|fim▁end|> | N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1]) |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def <|fim_middle|>(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | solutionWorks |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def <|fim_middle|>(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def moveDiscs(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | stepLegitimate |
<|file_name|>pegs.py<|end_file_name|><|fim▁begin|># n peg hanoi tower problem, use bfs instead of dfs, and don't have a full
# analytical solution
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return True
else:
return False
def stepLegitimate(stacksAfterSolution, i, j):
if len(stacksAfterSolution[i]) == 0 or \
(len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]):
return False
return True
# DFS cannot work, need to use BFS
def <|fim_middle|>(initialStacks, finalStacks, results):
import collections
solutions = collections.deque()
solutions.append([])
K = len(initialStacks) - 1
while len(solutions) > 0:
currentSolution = copy.deepcopy(solutions.popleft())
if len(currentSolution) > 7:
continue
stacksAfterSolution = copy.deepcopy(initialStacks)
if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
results.append(list(currentSolution[x]))
return
# add other solutions in queue
for i in range(1, K + 1):
for j in range(1, K + 1):
if j != i and stepLegitimate(stacksAfterSolution, i, j):
currentSolution.append([i, j])
solutions.append(copy.deepcopy(currentSolution))
currentSolution.pop()
if __name__ == '__main__':
# N, K = [int(x) for x in sys.stdin.readline().split()]
N, K = 6, 4
initialStacks = [[] for x in range(K + 1)]
finalStacks = [[] for x in range(K + 1)]
# initial = [int(x) for x in sys.stdin.readline().split()]
# final = [int(x) for x in sys.stdin.readline().split()]
initial = [4, 2, 4, 3, 1, 1]
final = [1, 1, 1, 1, 1, 1]
for i in range(N - 1, -1, -1):
initialStacks[initial[i]].append(i + 1)
for i in range(N - 1, -1, -1):
finalStacks[final[i]].append(i + 1)
print(initialStacks)
print(finalStacks)
results = []
moveDiscs(initialStacks, finalStacks, results)
print(len(results))
for i in range(len(results)):
print(results[i][0], results[i][1])
<|fim▁end|> | moveDiscs |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
<|fim▁hole|> exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()<|fim▁end|> | def __set_layout(self):
|
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
<|fim_middle|>
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | """
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
<|fim_middle|>
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | """
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor)) |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
<|fim_middle|>
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | """
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
<|fim_middle|>
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | """
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
<|fim_middle|>
<|fim▁end|> | """
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
<|fim_middle|>
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | """
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
<|fim_middle|>
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
<|fim_middle|>
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | """
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
<|fim_middle|>
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | """
Show map window
"""
self.map_window.construct_scene() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
<|fim_middle|>
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | """
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display) |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
<|fim_middle|>
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | """
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
<|fim_middle|>
<|fim▁end|> | """
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
<|fim_middle|>
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window() |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def <|fim_middle|>(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | __init__ |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def <|fim_middle|>(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | show_splash_screen |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def <|fim_middle|>(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | show_main_window |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def <|fim_middle|>(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | __init__ |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def <|fim_middle|>(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | __set_layout |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def <|fim_middle|>(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | show_new_game |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def <|fim_middle|>(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | __show_map_window |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def <|fim_middle|>(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | __show_message_window |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def <|fim_middle|>(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def __show_end_screen(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | __show_menu |
<|file_name|>mainwindow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Module for main window related functionality
"""
import PyQt4.QtGui
from herculeum.ui.controllers import EndScreenController, StartGameController
from herculeum.ui.gui.endscreen import EndScreen
from herculeum.ui.gui.eventdisplay import EventMessageDockWidget
from herculeum.ui.gui.map import PlayMapWindow
from herculeum.ui.gui.menu import MenuDialog
from herculeum.ui.gui.startgame import StartGameWidget
from PyQt4.QtCore import QFile, Qt
from PyQt4.QtGui import (QAction, QApplication, QCursor, QDialog, QIcon,
QMainWindow, QPixmap, QSplashScreen)
class QtUserInterface():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# self.qt_app.setOverrideCursor(QCursor(Qt.BlankCursor))
def show_splash_screen(self):
"""
Show splash screen
"""
file = QFile(':herculeum.qss')
file.open(QFile.ReadOnly)
styleSheet = str(file.readAll().data(), 'ascii')
self.qt_app.setStyleSheet(styleSheet)
pixmap = QPixmap(':splash.png')
self.splash_screen = QSplashScreen(pixmap)
self.splash_screen.show()
def show_main_window(self):
"""
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
StartGameController(self.application.level_generator_factory,
self.application.creature_generator,
self.application.item_generator,
self.application.config.start_level))
self.splash_screen.finish(main_window)
main_window.show_new_game()
self.qt_app.exec_()
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
self.application = application
self.surface_manager = surface_manager
self.qt_app = qt_app
self.controller = controller
self.__set_layout()
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
inventory_action = QAction(QIcon(':inventory.png'),
'Inventory',
self)
inventory_action.setShortcut('Ctrl+I')
inventory_action.setStatusTip('Show inventory')
inventory_action.triggered.connect(self.__show_menu)
character_action = QAction(QIcon(':character.png'),
'Character',
self)
character_action.setShortcut('Ctrl+C')
character_action.setStatusTip('Show character')
self.map_window = PlayMapWindow(parent=None,
model=self.application.world,
surface_manager=self.surface_manager,
action_factory=self.application.action_factory,
rng=self.application.rng,
rules_engine=self.application.rules_engine,
configuration=self.application.config)
self.setCentralWidget(self.map_window)
self.map_window.MenuRequested.connect(self.__show_menu)
self.map_window.EndScreenRequested.connect(self.__show_end_screen)
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle('Herculeum')
self.setWindowIcon(QIcon(':rune-stone.png'))
self.showMaximized()
def show_new_game(self):
"""
Show new game dialog
"""
app = self.application
start_dialog = StartGameWidget(generator=app.player_generator,
config=self.application.config.controls,
parent=self,
application=self.application,
surface_manager=self.surface_manager,
flags=Qt.Dialog | Qt.CustomizeWindowHint)
result = start_dialog.exec_()
if result == QDialog.Accepted:
player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(player)
self.map_window.hit_points_widget.show_spirit_points(player)
self.map_window.message_widget.text_edit.setText(intro_text)
self.__show_map_window()
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"""
messages_display = EventMessageDockWidget(self, character)
self.addDockWidget(Qt.BottomDockWidgetArea,
messages_display)
def __show_menu(self):
"""
Show menu
"""
menu_dialog = MenuDialog(self.surface_manager,
self.application.world.player,
self.application.action_factory,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint)
menu_dialog.exec_()
def <|fim_middle|>(self):
"""
Show end screen
.. versionadded:: 0.8
"""
end_screen = EndScreen(self.application.world,
self.application.config.controls,
self,
Qt.Dialog | Qt.CustomizeWindowHint,
controller=EndScreenController())
end_screen.exec_()
self.qt_app.quit()
<|fim▁end|> | __show_end_screen |
<|file_name|>infinity.py<|end_file_name|><|fim▁begin|>my_inf = float('Inf')
print 99999999 > my_inf
# False
<|fim▁hole|># True<|fim▁end|> | my_neg_inf = float('-Inf')
print my_neg_inf < -99999999 |
<|file_name|>version.py<|end_file_name|><|fim▁begin|># ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: version.py [] [email protected] $
<|fim▁hole|>"""
##########################################################################
## Versioning
##########################################################################
__version_info__ = {
'major': 0,
'minor': 1,
'micro': 0,
'releaselevel': 'final',
'serial': 0,
}
def get_version(short=False):
"""
Returns the version from the version info.
"""
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0],
__version_info__['serial']))
return ''.join(vers)<|fim▁end|> | """
Helper module for ORMBad version information. |
<|file_name|>version.py<|end_file_name|><|fim▁begin|># ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: version.py [] [email protected] $
"""
Helper module for ORMBad version information.
"""
##########################################################################
## Versioning
##########################################################################
__version_info__ = {
'major': 0,
'minor': 1,
'micro': 0,
'releaselevel': 'final',
'serial': 0,
}
def get_version(short=False):
<|fim_middle|>
<|fim▁end|> | """
Returns the version from the version info.
"""
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0],
__version_info__['serial']))
return ''.join(vers) |
<|file_name|>version.py<|end_file_name|><|fim▁begin|># ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: version.py [] [email protected] $
"""
Helper module for ORMBad version information.
"""
##########################################################################
## Versioning
##########################################################################
__version_info__ = {
'major': 0,
'minor': 1,
'micro': 0,
'releaselevel': 'final',
'serial': 0,
}
def get_version(short=False):
"""
Returns the version from the version info.
"""
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
<|fim_middle|>
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0],
__version_info__['serial']))
return ''.join(vers)
<|fim▁end|> | vers.append(".%(micro)i" % __version_info__) |
<|file_name|>version.py<|end_file_name|><|fim▁begin|># ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: version.py [] [email protected] $
"""
Helper module for ORMBad version information.
"""
##########################################################################
## Versioning
##########################################################################
__version_info__ = {
'major': 0,
'minor': 1,
'micro': 0,
'releaselevel': 'final',
'serial': 0,
}
def get_version(short=False):
"""
Returns the version from the version info.
"""
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
<|fim_middle|>
return ''.join(vers)
<|fim▁end|> | vers.append('%s%i' % (__version_info__['releaselevel'][0],
__version_info__['serial'])) |
<|file_name|>version.py<|end_file_name|><|fim▁begin|># ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: version.py [] [email protected] $
"""
Helper module for ORMBad version information.
"""
##########################################################################
## Versioning
##########################################################################
__version_info__ = {
'major': 0,
'minor': 1,
'micro': 0,
'releaselevel': 'final',
'serial': 0,
}
def <|fim_middle|>(short=False):
"""
Returns the version from the version info.
"""
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0],
__version_info__['serial']))
return ''.join(vers)
<|fim▁end|> | get_version |
<|file_name|>task_2_8.py<|end_file_name|><|fim▁begin|># Задача 2. Вариант 8.
#Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Лао-Цзы. Не забудьте о том, что автор должен быть упомянут на отдельной строке.<|fim▁hole|>
print("Нельзя обожествлять бесов.\n\t\t\t\t\t\t\t\tЛао-цзы")
input("Нажмите ENTER для выхода.")<|fim▁end|> |
# Ionova A. K.
#30.04.2016 |
<|file_name|>adapt_fit.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# Import the relevant PTS classes and modules
from pts.modeling.core.environment import load_modeling_environment_cwd
from pts.modeling.config.component import definition<|fim▁hole|>
# -----------------------------------------------------------------
# Load environment and model suite
environment = load_modeling_environment_cwd()
runs = environment.fitting_runs
# -----------------------------------------------------------------
properties = ["representation", "filters", "ranges", "genetic", "grid", "units", "types"]
# -----------------------------------------------------------------
definition = definition.copy()
# -----------------------------------------------------------------
# The fitting run for which to adapt the configuration
if runs.empty: raise RuntimeError("No fitting runs are present")
elif runs.has_single: definition.add_fixed("name", "name of the fitting run", runs.single_name)
else: definition.add_required("name", "string", "name of the fitting run", choices=runs.names)
# -----------------------------------------------------------------
# Dust or stellar
definition.add_positional_optional("properties", "string_list", "properties to adapt", default=properties, choices=properties)
# -----------------------------------------------------------------
# Select certain properties
definition.add_optional("contains", "string", "only adapt properties containing this string in their name")
definition.add_optional("not_contains", "string", "don't adapt properties containing this string in their name")
definition.add_optional("exact_name", "string", "only adapt properties with this exact string as their name")
definition.add_optional("exact_not_name", "string", "don't adapt properties with this exact string as their name")
definition.add_optional("startswith", "string", "only adapt properties whose name starts with this string")
definition.add_optional("endswith", "string", "only adapt properties whose name starts with this string")
# -----------------------------------------------------------------
# Save
definition.add_flag("save", "save adapted properties", True)
# -----------------------------------------------------------------<|fim▁end|> | |
<|file_name|>adapt_fit.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# Import the relevant PTS classes and modules
from pts.modeling.core.environment import load_modeling_environment_cwd
from pts.modeling.config.component import definition
# -----------------------------------------------------------------
# Load environment and model suite
environment = load_modeling_environment_cwd()
runs = environment.fitting_runs
# -----------------------------------------------------------------
properties = ["representation", "filters", "ranges", "genetic", "grid", "units", "types"]
# -----------------------------------------------------------------
definition = definition.copy()
# -----------------------------------------------------------------
# The fitting run for which to adapt the configuration
if runs.empty: r <|fim_middle|>
elif runs.has_single: definition.add_fixed("name", "name of the fitting run", runs.single_name)
else: definition.add_required("name", "string", "name of the fitting run", choices=runs.names)
# -----------------------------------------------------------------
# Dust or stellar
definition.add_positional_optional("properties", "string_list", "properties to adapt", default=properties, choices=properties)
# -----------------------------------------------------------------
# Select certain properties
definition.add_optional("contains", "string", "only adapt properties containing this string in their name")
definition.add_optional("not_contains", "string", "don't adapt properties containing this string in their name")
definition.add_optional("exact_name", "string", "only adapt properties with this exact string as their name")
definition.add_optional("exact_not_name", "string", "don't adapt properties with this exact string as their name")
definition.add_optional("startswith", "string", "only adapt properties whose name starts with this string")
definition.add_optional("endswith", "string", "only adapt properties whose name starts with this string")
# -----------------------------------------------------------------
# Save
definition.add_flag("save", "save adapted properties", True)
# -----------------------------------------------------------------
<|fim▁end|> | aise RuntimeError("No fitting runs are present")
|
<|file_name|>adapt_fit.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# Import the relevant PTS classes and modules
from pts.modeling.core.environment import load_modeling_environment_cwd
from pts.modeling.config.component import definition
# -----------------------------------------------------------------
# Load environment and model suite
environment = load_modeling_environment_cwd()
runs = environment.fitting_runs
# -----------------------------------------------------------------
properties = ["representation", "filters", "ranges", "genetic", "grid", "units", "types"]
# -----------------------------------------------------------------
definition = definition.copy()
# -----------------------------------------------------------------
# The fitting run for which to adapt the configuration
if runs.empty: raise RuntimeError("No fitting runs are present")
elif runs.has_single: d <|fim_middle|>
else: definition.add_required("name", "string", "name of the fitting run", choices=runs.names)
# -----------------------------------------------------------------
# Dust or stellar
definition.add_positional_optional("properties", "string_list", "properties to adapt", default=properties, choices=properties)
# -----------------------------------------------------------------
# Select certain properties
definition.add_optional("contains", "string", "only adapt properties containing this string in their name")
definition.add_optional("not_contains", "string", "don't adapt properties containing this string in their name")
definition.add_optional("exact_name", "string", "only adapt properties with this exact string as their name")
definition.add_optional("exact_not_name", "string", "don't adapt properties with this exact string as their name")
definition.add_optional("startswith", "string", "only adapt properties whose name starts with this string")
definition.add_optional("endswith", "string", "only adapt properties whose name starts with this string")
# -----------------------------------------------------------------
# Save
definition.add_flag("save", "save adapted properties", True)
# -----------------------------------------------------------------
<|fim▁end|> | efinition.add_fixed("name", "name of the fitting run", runs.single_name)
|
<|file_name|>adapt_fit.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# Import the relevant PTS classes and modules
from pts.modeling.core.environment import load_modeling_environment_cwd
from pts.modeling.config.component import definition
# -----------------------------------------------------------------
# Load environment and model suite
environment = load_modeling_environment_cwd()
runs = environment.fitting_runs
# -----------------------------------------------------------------
properties = ["representation", "filters", "ranges", "genetic", "grid", "units", "types"]
# -----------------------------------------------------------------
definition = definition.copy()
# -----------------------------------------------------------------
# The fitting run for which to adapt the configuration
if runs.empty: raise RuntimeError("No fitting runs are present")
elif runs.has_single: definition.add_fixed("name", "name of the fitting run", runs.single_name)
else: d <|fim_middle|>
# -----------------------------------------------------------------
# Dust or stellar
definition.add_positional_optional("properties", "string_list", "properties to adapt", default=properties, choices=properties)
# -----------------------------------------------------------------
# Select certain properties
definition.add_optional("contains", "string", "only adapt properties containing this string in their name")
definition.add_optional("not_contains", "string", "don't adapt properties containing this string in their name")
definition.add_optional("exact_name", "string", "only adapt properties with this exact string as their name")
definition.add_optional("exact_not_name", "string", "don't adapt properties with this exact string as their name")
definition.add_optional("startswith", "string", "only adapt properties whose name starts with this string")
definition.add_optional("endswith", "string", "only adapt properties whose name starts with this string")
# -----------------------------------------------------------------
# Save
definition.add_flag("save", "save adapted properties", True)
# -----------------------------------------------------------------
<|fim▁end|> | efinition.add_required("name", "string", "name of the fitting run", choices=runs.names)
|
<|file_name|>test_reboot_unprovisioned.py<|end_file_name|><|fim▁begin|># Copyright 2015 Rackspace, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from onmetal_scripts.lib import states
from onmetal_scripts import reboot_unprovisioned
from onmetal_scripts.tests import base
import mock
class TestRebootUnprovisioned(base.BaseTest):
def setUp(self):
self.script = reboot_unprovisioned.RebootUnprovisioned()
self.script.get_argument = mock.Mock()
self.script.get_argument.return_value = 0
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run(self, ironic_mock):
active_node = self._get_test_node(
provision_state=states.ACTIVE,
instance_uuid='118ad976-084a-443f-9ec5-77d477f2bfcc')<|fim▁hole|>
ironic_mock.list_nodes.return_value = [active_node, inactive_node]
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run_fail(self, ironic_mock):
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [inactive_node]
ironic_mock.set_target_power_state.side_effect = ValueError
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)<|fim▁end|> | inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False) |
<|file_name|>test_reboot_unprovisioned.py<|end_file_name|><|fim▁begin|># Copyright 2015 Rackspace, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from onmetal_scripts.lib import states
from onmetal_scripts import reboot_unprovisioned
from onmetal_scripts.tests import base
import mock
class TestRebootUnprovisioned(base.BaseTest):
<|fim_middle|>
<|fim▁end|> | def setUp(self):
self.script = reboot_unprovisioned.RebootUnprovisioned()
self.script.get_argument = mock.Mock()
self.script.get_argument.return_value = 0
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run(self, ironic_mock):
active_node = self._get_test_node(
provision_state=states.ACTIVE,
instance_uuid='118ad976-084a-443f-9ec5-77d477f2bfcc')
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [active_node, inactive_node]
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run_fail(self, ironic_mock):
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [inactive_node]
ironic_mock.set_target_power_state.side_effect = ValueError
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT) |
<|file_name|>test_reboot_unprovisioned.py<|end_file_name|><|fim▁begin|># Copyright 2015 Rackspace, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from onmetal_scripts.lib import states
from onmetal_scripts import reboot_unprovisioned
from onmetal_scripts.tests import base
import mock
class TestRebootUnprovisioned(base.BaseTest):
def setUp(self):
<|fim_middle|>
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run(self, ironic_mock):
active_node = self._get_test_node(
provision_state=states.ACTIVE,
instance_uuid='118ad976-084a-443f-9ec5-77d477f2bfcc')
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [active_node, inactive_node]
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run_fail(self, ironic_mock):
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [inactive_node]
ironic_mock.set_target_power_state.side_effect = ValueError
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
<|fim▁end|> | self.script = reboot_unprovisioned.RebootUnprovisioned()
self.script.get_argument = mock.Mock()
self.script.get_argument.return_value = 0 |
<|file_name|>test_reboot_unprovisioned.py<|end_file_name|><|fim▁begin|># Copyright 2015 Rackspace, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from onmetal_scripts.lib import states
from onmetal_scripts import reboot_unprovisioned
from onmetal_scripts.tests import base
import mock
class TestRebootUnprovisioned(base.BaseTest):
def setUp(self):
self.script = reboot_unprovisioned.RebootUnprovisioned()
self.script.get_argument = mock.Mock()
self.script.get_argument.return_value = 0
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run(self, ironic_mock):
<|fim_middle|>
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run_fail(self, ironic_mock):
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [inactive_node]
ironic_mock.set_target_power_state.side_effect = ValueError
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
<|fim▁end|> | active_node = self._get_test_node(
provision_state=states.ACTIVE,
instance_uuid='118ad976-084a-443f-9ec5-77d477f2bfcc')
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [active_node, inactive_node]
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT) |
<|file_name|>test_reboot_unprovisioned.py<|end_file_name|><|fim▁begin|># Copyright 2015 Rackspace, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from onmetal_scripts.lib import states
from onmetal_scripts import reboot_unprovisioned
from onmetal_scripts.tests import base
import mock
class TestRebootUnprovisioned(base.BaseTest):
def setUp(self):
self.script = reboot_unprovisioned.RebootUnprovisioned()
self.script.get_argument = mock.Mock()
self.script.get_argument.return_value = 0
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run(self, ironic_mock):
active_node = self._get_test_node(
provision_state=states.ACTIVE,
instance_uuid='118ad976-084a-443f-9ec5-77d477f2bfcc')
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [active_node, inactive_node]
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run_fail(self, ironic_mock):
<|fim_middle|>
<|fim▁end|> | inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [inactive_node]
ironic_mock.set_target_power_state.side_effect = ValueError
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT) |
<|file_name|>test_reboot_unprovisioned.py<|end_file_name|><|fim▁begin|># Copyright 2015 Rackspace, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from onmetal_scripts.lib import states
from onmetal_scripts import reboot_unprovisioned
from onmetal_scripts.tests import base
import mock
class TestRebootUnprovisioned(base.BaseTest):
def <|fim_middle|>(self):
self.script = reboot_unprovisioned.RebootUnprovisioned()
self.script.get_argument = mock.Mock()
self.script.get_argument.return_value = 0
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run(self, ironic_mock):
active_node = self._get_test_node(
provision_state=states.ACTIVE,
instance_uuid='118ad976-084a-443f-9ec5-77d477f2bfcc')
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [active_node, inactive_node]
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run_fail(self, ironic_mock):
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [inactive_node]
ironic_mock.set_target_power_state.side_effect = ValueError
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
<|fim▁end|> | setUp |
<|file_name|>test_reboot_unprovisioned.py<|end_file_name|><|fim▁begin|># Copyright 2015 Rackspace, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from onmetal_scripts.lib import states
from onmetal_scripts import reboot_unprovisioned
from onmetal_scripts.tests import base
import mock
class TestRebootUnprovisioned(base.BaseTest):
def setUp(self):
self.script = reboot_unprovisioned.RebootUnprovisioned()
self.script.get_argument = mock.Mock()
self.script.get_argument.return_value = 0
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def <|fim_middle|>(self, ironic_mock):
active_node = self._get_test_node(
provision_state=states.ACTIVE,
instance_uuid='118ad976-084a-443f-9ec5-77d477f2bfcc')
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [active_node, inactive_node]
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run_fail(self, ironic_mock):
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [inactive_node]
ironic_mock.set_target_power_state.side_effect = ValueError
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
<|fim▁end|> | test_run |
<|file_name|>test_reboot_unprovisioned.py<|end_file_name|><|fim▁begin|># Copyright 2015 Rackspace, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from onmetal_scripts.lib import states
from onmetal_scripts import reboot_unprovisioned
from onmetal_scripts.tests import base
import mock
class TestRebootUnprovisioned(base.BaseTest):
def setUp(self):
self.script = reboot_unprovisioned.RebootUnprovisioned()
self.script.get_argument = mock.Mock()
self.script.get_argument.return_value = 0
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def test_run(self, ironic_mock):
active_node = self._get_test_node(
provision_state=states.ACTIVE,
instance_uuid='118ad976-084a-443f-9ec5-77d477f2bfcc')
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [active_node, inactive_node]
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
@mock.patch('onmetal_scripts.reboot_unprovisioned.RebootUnprovisioned.'
'ironic_client')
def <|fim_middle|>(self, ironic_mock):
inactive_node = self._get_test_node(
provision_state=states.AVAILABLE,
instance_uuid=None,
maintenance=False)
ironic_mock.list_nodes.return_value = [inactive_node]
ironic_mock.set_target_power_state.side_effect = ValueError
self.script.run()
ironic_mock.set_target_power_state.assert_called_once_with(
inactive_node, states.REBOOT)
<|fim▁end|> | test_run_fail |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
<|fim▁hole|> for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)<|fim▁end|> | formatted = ''.join(char if i != self.head_position else '[%s]' % char |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
<|fim_middle|>
<|fim▁end|> | def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape) |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
<|fim_middle|>
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
<|fim_middle|>
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
<|fim_middle|>
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
<|fim_middle|>
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted) |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
<|fim_middle|>
<|fim▁end|> | self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape) |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
<|fim_middle|>
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | print "# %s " % self.state |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
<|fim_middle|>
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
) |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
<|fim_middle|>
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | self.head_position = max(0, self.head_position - 1) |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
<|fim_middle|>
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1 |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
<|fim_middle|>
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | self.tape.append('#') |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
<|fim_middle|>
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | self.print_tape_contents() |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def <|fim_middle|>(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | __init__ |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def <|fim_middle|>(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | initialize |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def <|fim_middle|>(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | simulate_one_step |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def <|fim_middle|>(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | print_tape_contents |
<|file_name|>turing.py<|end_file_name|><|fim▁begin|>required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
def initialize(self, input_string):
for char in input_string:
assert char in self.sigma
self.tape = list(input_string)
self.state = 'init'
self.head_position = 0
return
def simulate_one_step(self, verbose=False):
if self.state in ['accept', 'reject']:
print "# %s " % self.state
cur_symbol = self.tape[self.head_position]
transition = self.delta[(self.state, cur_symbol)]
if verbose:
self.print_tape_contents()
template = "delta({q_old}, {s_old}) = ({q}, {s}, {arr})"
print(template.format(q_old=self.state,
s_old=cur_symbol,
q=transition[0],
s=transition[1],
arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2] == 'right')
if self.head_position == len(self.tape) - 1:
self.tape.append('#')
self.head_position +=1
if verbose:
self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def <|fim_middle|>(self, input_string, verbose=False):
self.initialize(input_string)
while self.state not in ['reject', 'accept']:
self.simulate_one_step(verbose)
return str(self.tape)
<|fim▁end|> | run |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>'''
from .version import *<|fim▁end|> | '''WARCAT: Web ARChive (WARC) Archiving Tool
Tool and library for handling Web ARChive (WARC) files. |
<|file_name|>media_object.py<|end_file_name|><|fim▁begin|>""" TODO: Add docstring """
import re<|fim▁hole|>import pexpect
class MediaObject(object):
"""Represents an encodable object"""
def __init__(self, input_filename, output_filename):
self.input_filename = input_filename
self.output_filename = output_filename
self.media_duration = self.get_media_duration()
# INFO: All other media information could potentially be put here too
def get_media_duration(self):
"""
Spawns an avprobe process to get the media duration.
Spawns an avprobe process and saves the output to a list, then uses
regex to find the duration of the media and return it as an integer.
"""
info_process = pexpect.spawn("/usr/bin/avprobe " + self.input_filename)
subprocess_output = info_process.readlines()
info_process.close
# Non-greedy match on characters 'Duration: ' followed by
# number in form 00:00:00:00
regex_group = re.compile(".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)",
re.IGNORECASE | re.DOTALL)
# Exits as soon as duration is found
# PERF: Perform some tests to find the min number of lines
# certain not to contain the duration, then operate on a slice
# not containing those lines
for line in subprocess_output:
regex_match = regex_group.search(line)
if regex_match:
# Return the total duration in seconds
return ((int(regex_match.group(1)) * 3600) + # Hours
(int(regex_match.group(2)) * 60) + # Minutes
int(regex_match.group(3)) + # Seconds
# Round milliseconds to nearest second
1 if int(regex_match.group(3)) > 50 else 0)
# Not found so it's possible the process terminated early or an update
# broke the regex. Unlikely but we must return something just in case.
return -1<|fim▁end|> | |
<|file_name|>media_object.py<|end_file_name|><|fim▁begin|>""" TODO: Add docstring """
import re
import pexpect
class MediaObject(object):
<|fim_middle|>
<|fim▁end|> | """Represents an encodable object"""
def __init__(self, input_filename, output_filename):
self.input_filename = input_filename
self.output_filename = output_filename
self.media_duration = self.get_media_duration()
# INFO: All other media information could potentially be put here too
def get_media_duration(self):
"""
Spawns an avprobe process to get the media duration.
Spawns an avprobe process and saves the output to a list, then uses
regex to find the duration of the media and return it as an integer.
"""
info_process = pexpect.spawn("/usr/bin/avprobe " + self.input_filename)
subprocess_output = info_process.readlines()
info_process.close
# Non-greedy match on characters 'Duration: ' followed by
# number in form 00:00:00:00
regex_group = re.compile(".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)",
re.IGNORECASE | re.DOTALL)
# Exits as soon as duration is found
# PERF: Perform some tests to find the min number of lines
# certain not to contain the duration, then operate on a slice
# not containing those lines
for line in subprocess_output:
regex_match = regex_group.search(line)
if regex_match:
# Return the total duration in seconds
return ((int(regex_match.group(1)) * 3600) + # Hours
(int(regex_match.group(2)) * 60) + # Minutes
int(regex_match.group(3)) + # Seconds
# Round milliseconds to nearest second
1 if int(regex_match.group(3)) > 50 else 0)
# Not found so it's possible the process terminated early or an update
# broke the regex. Unlikely but we must return something just in case.
return -1 |
<|file_name|>media_object.py<|end_file_name|><|fim▁begin|>""" TODO: Add docstring """
import re
import pexpect
class MediaObject(object):
"""Represents an encodable object"""
def __init__(self, input_filename, output_filename):
<|fim_middle|>
def get_media_duration(self):
"""
Spawns an avprobe process to get the media duration.
Spawns an avprobe process and saves the output to a list, then uses
regex to find the duration of the media and return it as an integer.
"""
info_process = pexpect.spawn("/usr/bin/avprobe " + self.input_filename)
subprocess_output = info_process.readlines()
info_process.close
# Non-greedy match on characters 'Duration: ' followed by
# number in form 00:00:00:00
regex_group = re.compile(".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)",
re.IGNORECASE | re.DOTALL)
# Exits as soon as duration is found
# PERF: Perform some tests to find the min number of lines
# certain not to contain the duration, then operate on a slice
# not containing those lines
for line in subprocess_output:
regex_match = regex_group.search(line)
if regex_match:
# Return the total duration in seconds
return ((int(regex_match.group(1)) * 3600) + # Hours
(int(regex_match.group(2)) * 60) + # Minutes
int(regex_match.group(3)) + # Seconds
# Round milliseconds to nearest second
1 if int(regex_match.group(3)) > 50 else 0)
# Not found so it's possible the process terminated early or an update
# broke the regex. Unlikely but we must return something just in case.
return -1
<|fim▁end|> | self.input_filename = input_filename
self.output_filename = output_filename
self.media_duration = self.get_media_duration()
# INFO: All other media information could potentially be put here too |
<|file_name|>media_object.py<|end_file_name|><|fim▁begin|>""" TODO: Add docstring """
import re
import pexpect
class MediaObject(object):
"""Represents an encodable object"""
def __init__(self, input_filename, output_filename):
self.input_filename = input_filename
self.output_filename = output_filename
self.media_duration = self.get_media_duration()
# INFO: All other media information could potentially be put here too
def get_media_duration(self):
<|fim_middle|>
<|fim▁end|> | """
Spawns an avprobe process to get the media duration.
Spawns an avprobe process and saves the output to a list, then uses
regex to find the duration of the media and return it as an integer.
"""
info_process = pexpect.spawn("/usr/bin/avprobe " + self.input_filename)
subprocess_output = info_process.readlines()
info_process.close
# Non-greedy match on characters 'Duration: ' followed by
# number in form 00:00:00:00
regex_group = re.compile(".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)",
re.IGNORECASE | re.DOTALL)
# Exits as soon as duration is found
# PERF: Perform some tests to find the min number of lines
# certain not to contain the duration, then operate on a slice
# not containing those lines
for line in subprocess_output:
regex_match = regex_group.search(line)
if regex_match:
# Return the total duration in seconds
return ((int(regex_match.group(1)) * 3600) + # Hours
(int(regex_match.group(2)) * 60) + # Minutes
int(regex_match.group(3)) + # Seconds
# Round milliseconds to nearest second
1 if int(regex_match.group(3)) > 50 else 0)
# Not found so it's possible the process terminated early or an update
# broke the regex. Unlikely but we must return something just in case.
return -1 |
<|file_name|>media_object.py<|end_file_name|><|fim▁begin|>""" TODO: Add docstring """
import re
import pexpect
class MediaObject(object):
"""Represents an encodable object"""
def __init__(self, input_filename, output_filename):
self.input_filename = input_filename
self.output_filename = output_filename
self.media_duration = self.get_media_duration()
# INFO: All other media information could potentially be put here too
def get_media_duration(self):
"""
Spawns an avprobe process to get the media duration.
Spawns an avprobe process and saves the output to a list, then uses
regex to find the duration of the media and return it as an integer.
"""
info_process = pexpect.spawn("/usr/bin/avprobe " + self.input_filename)
subprocess_output = info_process.readlines()
info_process.close
# Non-greedy match on characters 'Duration: ' followed by
# number in form 00:00:00:00
regex_group = re.compile(".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)",
re.IGNORECASE | re.DOTALL)
# Exits as soon as duration is found
# PERF: Perform some tests to find the min number of lines
# certain not to contain the duration, then operate on a slice
# not containing those lines
for line in subprocess_output:
regex_match = regex_group.search(line)
if regex_match:
# Return the total duration in seconds
<|fim_middle|>
# Not found so it's possible the process terminated early or an update
# broke the regex. Unlikely but we must return something just in case.
return -1
<|fim▁end|> | return ((int(regex_match.group(1)) * 3600) + # Hours
(int(regex_match.group(2)) * 60) + # Minutes
int(regex_match.group(3)) + # Seconds
# Round milliseconds to nearest second
1 if int(regex_match.group(3)) > 50 else 0) |
<|file_name|>media_object.py<|end_file_name|><|fim▁begin|>""" TODO: Add docstring """
import re
import pexpect
class MediaObject(object):
"""Represents an encodable object"""
def <|fim_middle|>(self, input_filename, output_filename):
self.input_filename = input_filename
self.output_filename = output_filename
self.media_duration = self.get_media_duration()
# INFO: All other media information could potentially be put here too
def get_media_duration(self):
"""
Spawns an avprobe process to get the media duration.
Spawns an avprobe process and saves the output to a list, then uses
regex to find the duration of the media and return it as an integer.
"""
info_process = pexpect.spawn("/usr/bin/avprobe " + self.input_filename)
subprocess_output = info_process.readlines()
info_process.close
# Non-greedy match on characters 'Duration: ' followed by
# number in form 00:00:00:00
regex_group = re.compile(".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)",
re.IGNORECASE | re.DOTALL)
# Exits as soon as duration is found
# PERF: Perform some tests to find the min number of lines
# certain not to contain the duration, then operate on a slice
# not containing those lines
for line in subprocess_output:
regex_match = regex_group.search(line)
if regex_match:
# Return the total duration in seconds
return ((int(regex_match.group(1)) * 3600) + # Hours
(int(regex_match.group(2)) * 60) + # Minutes
int(regex_match.group(3)) + # Seconds
# Round milliseconds to nearest second
1 if int(regex_match.group(3)) > 50 else 0)
# Not found so it's possible the process terminated early or an update
# broke the regex. Unlikely but we must return something just in case.
return -1
<|fim▁end|> | __init__ |
<|file_name|>media_object.py<|end_file_name|><|fim▁begin|>""" TODO: Add docstring """
import re
import pexpect
class MediaObject(object):
"""Represents an encodable object"""
def __init__(self, input_filename, output_filename):
self.input_filename = input_filename
self.output_filename = output_filename
self.media_duration = self.get_media_duration()
# INFO: All other media information could potentially be put here too
def <|fim_middle|>(self):
"""
Spawns an avprobe process to get the media duration.
Spawns an avprobe process and saves the output to a list, then uses
regex to find the duration of the media and return it as an integer.
"""
info_process = pexpect.spawn("/usr/bin/avprobe " + self.input_filename)
subprocess_output = info_process.readlines()
info_process.close
# Non-greedy match on characters 'Duration: ' followed by
# number in form 00:00:00:00
regex_group = re.compile(".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)",
re.IGNORECASE | re.DOTALL)
# Exits as soon as duration is found
# PERF: Perform some tests to find the min number of lines
# certain not to contain the duration, then operate on a slice
# not containing those lines
for line in subprocess_output:
regex_match = regex_group.search(line)
if regex_match:
# Return the total duration in seconds
return ((int(regex_match.group(1)) * 3600) + # Hours
(int(regex_match.group(2)) * 60) + # Minutes
int(regex_match.group(3)) + # Seconds
# Round milliseconds to nearest second
1 if int(regex_match.group(3)) > 50 else 0)
# Not found so it's possible the process terminated early or an update
# broke the regex. Unlikely but we must return something just in case.
return -1
<|fim▁end|> | get_media_duration |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0]
def post_setup(self):
if self.named_args is not None:
if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(filename)<|fim▁hole|>if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())<|fim▁end|> | |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
<|fim_middle|>
if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())
<|fim▁end|> | """
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0]
def post_setup(self):
if self.named_args is not None:
if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(filename) |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
<|fim_middle|>
def post_setup(self):
if self.named_args is not None:
if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(filename)
if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())
<|fim▁end|> | self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0] |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0]
def post_setup(self):
<|fim_middle|>
if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())
<|fim▁end|> | if self.named_args is not None:
if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(filename) |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
<|fim_middle|>
def post_setup(self):
if self.named_args is not None:
if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(filename)
if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())
<|fim▁end|> | self.dfr_dir = self.extra_args[0] |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0]
def post_setup(self):
if self.named_args is not None:
<|fim_middle|>
if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())
<|fim▁end|> | if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(filename) |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0]
def post_setup(self):
if self.named_args is not None:
if 'tags' in self.named_args:
<|fim_middle|>
if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())
<|fim▁end|> | self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(filename) |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0]
def post_setup(self):
if self.named_args is not None:
if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
<|fim_middle|>
else:
del self.metadata[filename]
self.files.remove(filename)
if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())
<|fim▁end|> | self.metadata[filename]['label'] = my_tags[0] |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0]
def post_setup(self):
if self.named_args is not None:
if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
<|fim_middle|>
if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())
<|fim▁end|> | del self.metadata[filename]
self.files.remove(filename) |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0]
def post_setup(self):
if self.named_args is not None:
if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(filename)
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc()) |
<|file_name|>mallet_lda_tags.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def <|fim_middle|>(self):
self.name = 'mallet_lda_tags'
self.categorical = False
self.template_name = 'mallet_lda'
self.dry_run = False
self.topics = 50
self.dfr = len(self.extra_args) > 0
if self.dfr:
self.dfr_dir = self.extra_args[0]
def post_setup(self):
if self.named_args is not None:
if 'tags' in self.named_args:
self.tags = self.named_args['tags']
for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(filename)
if __name__ == '__main__':
try:
processor = MalletTagTopics(track_progress=False)
processor.process()
except:
logging.error(traceback.format_exc())
<|fim▁end|> | _basic_params |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.