Beispiel #1
0
def test_to_flip():
    r = Records(8, [0, 0], Board(8))
    r.color = "black"
    assert (r.to_flip([1, 1], [3, 4, "white"]) == [])
    assert (r.to_flip([1, 1], [7, 7, "white"]) == [])
    assert (r.to_flip([1, 0], [3, 4, "white"]) == [[3, 4, "white"],
                                                   ["Valid move"]])
Beispiel #2
0
    def test_that_it_trims_records_from_5_to_1_line(self):
        # given
        now = datetime.now()
        content = """var chartData = [
{{  date: new Date("{0}"), aa: 1, bb: 2, cc: 3  }},
{{  date: new Date("{0}"), aa: 4, bb: 5, cc: 6  }},
{{  date: new Date("{0}"), aa: 7, bb: 8, cc: 9  }},
{{  date: new Date("{0}"), aa: 10, bb: 11, cc: 12  }},
{{  date: new Date("{0}"), aa: 13, bb: 14, cc: 15  }},
];""".format(now.strftime('%Y-%m-%dT%H:%M'))

        expected_content = """var chartData = [
{{  date: new Date("{0}"), aa: 13, bb: 14, cc: 15  }},
];""".format(now.strftime('%Y-%m-%dT%H:%M'))

        test_output_file = "/tmp/ultra_garden_test_trim51"
        with open(test_output_file, "w") as f:
            f.write(content)

        # when
        Records.trim_records(test_output_file, 1)

        # then
        with open(test_output_file) as f:
            self.assertEqual(expected_content, f.read())
Beispiel #3
0
class FIFO:
    def __init__(self, queue, trackStartPos):

        self.currentTrack = trackStartPos
        if not isinstance(queue, list):
            raise TypeError("queue must be set to an list")
        self.name = "first in first out"
        print(self.name)
        self.queue = queue.copy()
        self.pos = 0

    def getQueue(self):

        return self.queue

    def accessNextTrack(self):
        self.pos += 1
        return self.queue.pop(0)

    def run(self):
        print("starting run")
        self.records = Records()
        print(len(self.queue))
        for i in range(len(self.queue)):
            self.nextTrack = self.accessNextTrack()
            self.records.addRecord(self.currentTrack, self.nextTrack)

            self.currentTrack = self.nextTrack

        print(self.records)
    def run(self):

        print("starting run")
        self.records = Records()
        # print(len(self.requestList))
        # print(self.requestList)
        self.startIndex = 0

        endPos = cylinders
        direction = 1  # values 1 or -1
        while len(self.requestList) > 0:
            self.activeRequestQueue = []
            for i in range(self.queueSize):
                #print(i)
                if len(self.requestList) > 0:
                    self.activeRequestQueue.append(self.requestList.pop(0))
            while len(self.activeRequestQueue) > 0:
                for track in range(self.headPos, endPos, direction):
                    if track in self.activeRequestQueue:
                        # print(track)
                        self.nextTrack = track
                        self.activeRequestQueue.remove(track)
                        self.records.addRecord(self.headPos, self.nextTrack)
                        self.headPos = self.nextTrack
                    if track == 199:
                        direction *= -1
                        endPos = -1

                    if track == 0:
                        endPos = cylinders
                        direction *= -1
        print(self.records)
Beispiel #5
0
    def test_that_it_writes_multi_line_data_to_file(self):
        # given
        records = Records(
            (SensorFake("aa"), SensorFake("bb"), SensorFake("cc")))

        test_output_file = "/tmp/ultra_garden_test_multi"
        with suppress(FileNotFoundError):
            os.remove(test_output_file)

        now = datetime.now()
        expected_content = """var chartData = [
{{  date: new Date("{0}"), aa: 1, bb: 2, cc: 3  }},
{{  date: new Date("{0}"), aa: 4, bb: 5, cc: 6  }},
{{  date: new Date("{0}"), aa: 7, bb: 8, cc: 9  }},
{{  date: new Date("{0}"), aa: 10, bb: 11, cc: 12  }},
{{  date: new Date("{0}"), aa: 13, bb: 14, cc: 15  }},
];""".format(now.strftime('%Y-%m-%dT%H:%M'))

        # when
        for record in range(5):
            for i, s in enumerate(records.sensors, 1):
                s.value = len(records.sensors) * record + i
            records.write_values(test_output_file)

        # then
        with open(test_output_file) as f:
            self.assertEqual(expected_content, f.read())
Beispiel #6
0
def process(path_to_ini: str):
    """ Program main function """
    input_paths, output_path = load_ini(path_to_ini)
    records = Records()
    load(records, input_paths["csv"], input_paths["json"],
         input_paths["encoding"])
    records.output(output_path["fname"], output_path["encoding"])
Beispiel #7
0
class cscanMode:
    def __init__(self, queue, headpos):
        self.headPos = headpos

        if not isinstance(queue, list):
            raise TypeError("queue must be set to an list")
        self.name = "c-scan algorithm"
        print(self.name)
        self.requestList = queue.copy()

        self.direction = 1  #direction modifier

    def run(self):
        print("starting run")
        self.records = Records()
        print(len(self.requestList))
        print(self.requestList)
        self.startIndex = 0
        self.requestList.sort()
        finished = False
        endPos = cylinders
        direction = 1  # values 1 or -1
        hp = self.headPos
        while len(self.requestList) > 0:
            for track in range(hp, endPos, direction):
                if track in self.requestList:
                    print(track)
                    self.nextTrack = track
                    self.requestList.remove(track)
                    self.records.addRecord(self.headPos, self.nextTrack)
                    self.headPos = self.nextTrack
                if track == 199:
                    hp = 0

        print(self.records)
Beispiel #8
0
    def load(self, records: Records, f):
        self._clear()
        reader = csv.reader(f, delimiter=";")
        for line in reader:
            line_len = len(line)
            if not line_len:
                continue
            if line_len != 10:
                raise Exception("There is not enough or too much columns")

            self.__mid_temp = line[0]
            self.__precipitation = line[1]
            self.__station_id = line[2]
            self.__wind_force = line[3]
            self.__year = line[4]
            self.__month = line[5]
            self.__day = line[6]
            self.__rel_hum = line[7]
            self.__max_temp = line[8]
            self.__min_temp = line[9]
            self._convert_line()
            records.append_record(mid_temp=self.__mid_temp,
                                  precip=self.__precipitation,
                                  station_id=self.__station_id,
                                  wind_force=self.__wind_force,
                                  year=self.__year,
                                  month=self.__month,
                                  day=self.__day,
                                  rel_hum=self.__rel_hum,
                                  max_temp=self.__max_temp,
                                  min_temp=self.__min_temp)
Beispiel #9
0
    def run(self):
        print("starting run")
        self.records = Records()
        print(len(self.requestList))
        print(self.requestList)
        self.startIndex = 0
        self.requestList.sort()
        finished = False
        endPos = cylinders
        direction = 1  # values 1 or -1
        while len(self.requestList) > 0:
            for track in range(self.headPos, endPos, direction):
                if track in self.requestList:
                    print(track)
                    self.nextTrack = track
                    self.requestList.remove(track)
                    self.records.addRecord(self.headPos, self.nextTrack)
                    self.headPos = self.nextTrack
                if track == 199:
                    direction *= -1
                    endPos = -1

                if track == 0:
                    endPos = cylinders
                    direction *= -1
        print(self.records)
Beispiel #10
0
def test_winner_is():
    r = Records(2, [0, 0], Board(2))
    assert (r.winner_is(0, 0) == "Tie! Each player has 0 points.")
    assert (r.winner_is(3, 2) == "Black wins with 3 points, defeating white "
            "with only 2 points!")
    assert (r.winner_is(2, 3) == "White wins with 3 points, defeating black "
            "with only 2 points!")
Beispiel #11
0
    def init_project(self):
        """Common code for initialising project"""
        self.load_project()

        self.records = Records(self.db_file, self.index_file, self.passfile,
                               self.config.options['num_backups'],
                               self.config.options['backup_freq'])
        self.register = Register(self, self.records, self.project_name)
def _records():
    items = [
        dict(id="id-{}".format(n + 1), text='hello world') for n in range(5)
    ]

    records = Records()
    for item in items:
        records.write(**item)

    return records
Beispiel #13
0
 def board_click(self, x, y):
     x = self.correct_coordinate(x)
     y = self.correct_coordinate(y)
     proposed_move = [x, y]
     # If click it outside of the boundaries of the board, do nothing.
     if x == -1 or y == -1:
         pass
     else:
         records = Records(self.size, proposed_move, self)
         records_check = records.record_validation(proposed_move)
         if records_check is False:
             pass
         else:
             self.draw_piece(x, y, self.player_color(self.color))
             for entry in records.will_flip:
                 x_coord = entry[0]
                 y_coord = entry[1]
                 self.draw_piece(x_coord, y_coord, self.color)
             print("End of {}'s turn!".format(self.color))
             # If no more open squares, will announce the winner.
             if records.is_winner() is True:
                 print(records.winner_is(records.score_counter("black"),
                       records.score_counter("white")))
                 self.black_score = records.score_counter("black")
                 self.winner_declared = True
                 turtle.bye()
             else:
                 print("Current score - Black: {}, White: {}".format
                       (records.score_counter("black"),
                        records.score_counter("white")))
                 self.ai_move()
Beispiel #14
0
def load_data(records: Records, path: str, encoding: str):
    print("input-csv ", path, ": ", end="", sep="")
    records.clear()
    try:
        with open(path, "r", encoding=encoding) as f:
            b = Builder()
            b.load(records, f)
    except BaseException as error:
        records.clear()
        raise error
    print("OK")
Beispiel #15
0
    def run(self):
        print("starting run")
        self.records = Records()
        print(len(self.queue))
        for i in range(len(self.queue)):
            self.nextTrack = self.accessNextTrack()
            self.records.addRecord(self.currentTrack, self.nextTrack)

            self.currentTrack = self.nextTrack

        print(self.records)
    def run(self):
        self.queue.reverse()
        print("starting run")
        self.records = Records()
        print("length of request list: " + str(len(self.queue)))
        for i in range(len(self.queue)):
            self.nextTrack = self.accessNextTrack()
            self.records.addRecord(self.currentTrack, self.nextTrack)

            self.currentTrack = self.nextTrack

        print(self.records)
Beispiel #17
0
def _read_log(fname):
    """
    Read a log file 'fname' to produce instance of Config and Records.
    """

    print(f'Reading data from: {fname}')

    cf = Config()
    rs = Records()

    with open(fname, 'r') as f:
        cf.readin(f)
        skip_lines(3, f)
        rs.runs = [int(f.readline().split()[2])]
        rs.seed = [int(f.readline().split()[2])]
        rs.lattice_dims = [int(x) for x in f.readline().split()[2:]]
        skip_lines(4, f)
        while True:
            r = Records.read(f)
            if r == '' or r[0] == '\n':
                break
            rs.add(r)

    print(f'read in: {len(rs.inds)} records')

    return cf, rs
Beispiel #18
0
def test_index_of_best_move():
    r = Records(8, [0, 0], Board(8))
    r.best_move = [0, 0]
    r.legal_moves_avail = [[0, 0], [0, 1]]
    r.turns_avail = False
    assert (r.index_of_best_move() is None)
    r.turns_avail = True
    assert (r.index_of_best_move() == 0)
Beispiel #19
0
def import_log_files(path, runs):

    pat = f'{runs[0]} : {runs[1]}'

    def fn(k):
        return path / f'log_{k}.txt'

    def append_static_recs(rs):
        for v in rs.runs:
            Records.runs_read_in.append(v)

    cf, r = _read_log(fn(runs[0]))
    recs = [r]
    append_static_recs(r)
    for i in range(runs[0] + 1, runs[1] + 1):
        c, r = _read_log(fn(i))
        if c == cf:
            recs.append(r)
            append_static_recs(r)
        else:
            print(f'Error: Runs between {runs[0]} and {runs[1]} do use '
                  f'differing configurations at run {i}. \nExiting!')
            sys.exit(-1)
    ravg = Records.average(recs)

    return ravg, pat
class nstepscan:
    def __init__(self, queue, headpos, queuesize):
        self.headPos = headpos
        self.queueSize = queuesize
        if not isinstance(queue, list):
            raise TypeError("queue must be set to an list")
        self.name = "n-scan step scan algorithm"
        print()
        print(self.name)
        self.requestList = queue.copy()

    def run(self):

        print("starting run")
        self.records = Records()
        # print(len(self.requestList))
        # print(self.requestList)
        self.startIndex = 0

        hp = self.headPos
        endPos = cylinders
        direction = 1  # values 1 or -1
        while len(self.requestList) > 0:
            self.activeRequestQueue = []
            for i in range(self.queueSize):
                #print(i)
                if len(self.requestList) > 0:
                    self.activeRequestQueue.append(self.requestList.pop(0))
            while len(self.activeRequestQueue) > 0:

                for track in range(hp, endPos, direction):
                    if track in self.activeRequestQueue:
                        #print("while " + str(track))
                        self.nextTrack = track
                        self.activeRequestQueue.remove(track)
                        self.records.addRecord(self.headPos, self.nextTrack)
                        self.headPos = self.nextTrack

                    if track == 199:
                        direction = -1
                        endPos = -1
                        hp = cylinders - 1
                    elif track == 0:
                        endPos = cylinders
                        hp = 0
                        direction = 1
        print(self.records)
Beispiel #21
0
def test_ideal_move():
    r = Records(8, [0, 0], Board(8))
    r.turns_avail = False
    assert (r.ideal_move() is None)
    r.turns_avail = True
    r.legal_moves_avail = [[1, 6], [2, 4], [2, 6], [3, 7]]
    r.total_flips_avail = [[[2, 5, 'white'], [3, 4, 'black']],
                           [[3, 4, 'white']], [[3, 5, 'white']],
                           [[3, 6, 'white'], [3, 5, 'black'], [3, 4, 'black']]]
    assert (r.ideal_move() == [3, 7])
Beispiel #22
0
def test_is_winner():
    r = Records(2, [0, 0], Board(2))
    r.plays_used = [[0, 0, "white"]]
    r.total_pieces = 2
    assert (r.is_winner() is False)
    r.plays_used = [[0, 0, "white"], [0, 1, "black"]]
    assert (r.is_winner() is True)
Beispiel #23
0
def test_player_color():
    r = Records(2, [0, 0], Board(2))
    r.plays_used = [[0, 0, "white"], [0, 1, "black"], [1, 1, "white"]]
    r.skipped_turns = 0
    assert (r.player_color() == "white")
    r.skipped_turns = 1
    assert (r.player_color() == "black")
Beispiel #24
0
 def __init__(self):
     self.garden = Garden()
     self.records = Records(sensors=self.garden.sensors)
     self.scheduler = BackgroundScheduler({
         'apscheduler.executors.default': {
             'class': 'apscheduler.executors.pool:ThreadPoolExecutor',
             'max_workers': '1'
         }
     })
Beispiel #25
0
def _context():
    print("getting a new context")

    channel = channels['universe']
    channel.store = Records(salt='hello there')

    class Context:
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)

    return Context(channel=channel)
Beispiel #26
0
    def export_record(self, event):
        """Export the selected record into another project db.
        Matching fields are alone exported while others are ignored"""
        # get project to export to
        project_chooser = ProjectChooser(None, self.config)
        if project_chooser.ShowModal() == wx.ID_OK:
            chosen_project = project_chooser.default_project

        # cancel export otherwise
        else:
            return
         
        # Get the record vals
        selected_record = self.register.record_display.GetFirstSelected()
        if selected_record == -1:
            self.register.SetStatusText('No record selected', 0)
            return

        id = str(self.register.record_display.GetItemData(selected_record))
        record_vals = self.records.retrieve_record(id)
        record_vals['LOCK_STATUS'] = 'unlocked'

        # if same project is selected, clone it
        if chosen_project == self.config.options['default_project']:
            self.records.insert_record(record_vals)
            self.register.refresh_records()

        # if other project selected, open that db and enter compatible vals
        # get values for other project
        other_project_dir = self.config.options['projects'][chosen_project]
   
        # load paths for other project
        #self.fields_file = os.path.join(self.project_dir, 'fields.yaml')
        index_file = os.path.join(other_project_dir, 'index.yaml')
        db_file = os.path.join(other_project_dir, 'records.db')
        passfile = os.path.join(other_project_dir, 'pass.hsh')

        self.recipient_records = Records(db_file, index_file, passfile,
                                         self.config.options['num_backups'],
                                         self.config.options['backup_freq'])
        self.recipient_records.insert_record(record_vals)
Beispiel #27
0
def test_is_occupied():
    r = Records(8, [0, 0], Board(8))
    r.plays_used_coord_only = [[0, 0]]
    r.plays_used = [[0, 0, "white"]]
    assert (r.is_occupied([[0, 1], [1, 1], [1, 0]]) == [])
    assert (r.is_occupied([[0, 1], [0, 0], [1, 1], [2, 1],
                           [2, 0]]) == [[0, 0, "white"]])
Beispiel #28
0
    def test_that_it_writes_single_line_data_to_file(self):
        # given
        records = Records(
            (SensorFake("aa"), SensorFake("bb"), SensorFake("cc")))

        for i, s in enumerate(records.sensors, 1):
            s.value = i

        test_output_file = "/tmp/ultra_garden_test_single"
        with suppress(FileNotFoundError):
            os.remove(test_output_file)

        now = datetime.now()
        expected_content = "var chartData = [\n{{  date: new Date(\"{0}\"), aa: 1, bb: 2, cc: 3  }},\n];" \
            .format(now.strftime('%Y-%m-%dT%H:%M'))

        # when
        records.write_values(test_output_file)

        # then
        with open(test_output_file) as f:
            self.assertEqual(expected_content, f.read())
class LIFO:
    def __init__(self, queue, trackStartPos):

        self.currentTrack = trackStartPos
        if not isinstance(queue, list):
            raise TypeError("queue must be set to an list")
        self.name = "last in first out"
        print()
        print(self.name)
        self.queue = queue.copy()

        self.pos = 0

    def copyList(self, in_List):
        self.out_list = []
        for i in in_List:
            self.out_list.append(i)
        return self.out_list

    def getQueue(self):

        return self.queue

    def accessNextTrack(self):
        self.pos += 1
        return self.queue.pop(0)

    def run(self):
        self.queue.reverse()
        print("starting run")
        self.records = Records()
        print("length of request list: " + str(len(self.queue)))
        for i in range(len(self.queue)):
            self.nextTrack = self.accessNextTrack()
            self.records.addRecord(self.currentTrack, self.nextTrack)

            self.currentTrack = self.nextTrack

        print(self.records)
Beispiel #30
0
class SSTF:
    def __init__(self, queue, trackStartPos):

        self.currentTrack = trackStartPos
        if not isinstance(queue, list):
            raise TypeError("queue must be set to an list")
        self.name = "shortest seek time first"
        print(self.name)
        self.queue = queue.copy()

    def selectClosetTrack(self):
        self.minIndex = 0  #setting to first index and assuming there is atleast one
        self.diff = abs(self.queue[0] -
                        self.currentTrack)  #using first index to start with

        for i in range(len(self.queue)):
            print("index: " + str(i) + ", diff: " +
                  str(abs(self.currentTrack - self.queue[i])) + ", value: " +
                  str(self.queue[i]))
            if abs(self.currentTrack - self.queue[i]) < self.diff:
                self.diff = abs(self.currentTrack - self.queue[i])
                self.minIndex = i

        print("removing: " + str(self.minIndex))
        return self.queue.pop(self.minIndex)

    def run(self):
        print("starting run")
        self.records = Records()

        for i in range(len(self.queue)):

            self.nextTrack = self.selectClosetTrack()
            self.records.addRecord(self.currentTrack, self.nextTrack)

            self.currentTrack = self.nextTrack

        print(self.records)
Beispiel #31
0
    def _iniciarVariaveis(self):
        self.reversiMatrix = [ [ "   " for i in range(self.dimLinhas) ]
                               for j in range(self.dimColunas) ]

        self.reversiMatrix[int(self.dimLinhas/2)][int(self.dimColunas/2)] = ' 0 '
        self.reversiMatrix[int(self.dimLinhas/2)-1][int(self.dimColunas/2)-1] = ' 0 '
        self.reversiMatrix[int(self.dimLinhas/2)-1][int(self.dimColunas/2)] = ' # '
        self.reversiMatrix[int(self.dimLinhas/2)][int(self.dimColunas/2)-1] = ' # '
        ## VARIAVEIS DE SCORE ##
        self.recs = Records("MPDS.rve",self.recNum)
        self.charp = 2
        self.zero = 2
        self.estado = ' # '
        self.nestado = ' 0 '
        self.mensagem = "Inicio do jogo. # é o primeiro jogador. Para ajuda digite H\n"
        self.JogadaTemp = None
        self.last = None
        self.msgText = ""
        self.msg = False
Beispiel #32
0
class Reversi(object):
    '''
    Reversi -> Cria o objecto que implementa o jogo "Reversi". Um jogo de tabuleiro simples
    e representado por caracteres em consola.
    '''

    def _trocaTurno(self):
        estado = ' # ' if self.estado == ' 0 ' else ' 0 '
        self.estado = estado
        self.nestado = ' # ' if estado == ' 0 ' else ' 0 '
        
        
    def _actualizaPossibilidades(self):
        
        def _aplicaIfens(lin,col,i,j):
            if self._verificaArea(lin+(i*2), col+(j*2)) and self.reversiMatrix[lin+i][col+j] == self.nestado:
                if self.reversiMatrix[lin+(i*2)][col+(j*2)] == '   ':
                    self.reversiMatrix[lin+(i*2)][col+(j*2)] = ' - '
                    return
                if self.reversiMatrix[lin+i][col+j] == '   ':
                    return
                if self.reversiMatrix[lin+(i*2)][col+(j*2)] == self.nestado:
                    _aplicaIfens(lin+i, col+j, i, j)
                    return
            return


        for i in range(self.dimLinhas):
            for j in range(self.dimColunas):
                if self.reversiMatrix[i][j] == ' - ':
                    self.reversiMatrix[i][j] = '   '
    
        for lin in range(self.dimLinhas):
            for col in range(self.dimColunas):
                if self.reversiMatrix[lin][col] == self.estado:
                    for i in range(-1,2):
                        for j in range(-1,2):
                            _aplicaIfens(lin, col, i, j)
            
            

    def _verificaArea(self, linha, coluna):
        if linha < self.dimLinhas and linha >= 0 and coluna < self.dimColunas and coluna >= 0:
            return True
        return False
 
    def _aplicaJogada(self, linha, coluna):
        
        def _trocaEstado(lin, col, i, j):
            if self._verificaArea(lin+(i*2), col+(j*2)) and self.reversiMatrix[lin+i][col+j] == self.nestado:
                if self.reversiMatrix[lin+(i*2)][col+(j*2)] == self.estado:
                    self.reversiMatrix[lin+i][col+j] = self.estado
                    return
                if self.reversiMatrix[lin+(i*2)][col+(j*2)] == '   ':
                    return
                if self.reversiMatrix[lin+(i*2)][col+(j*2)] == self.nestado:
                    _trocaEstado(lin+i, col+j, i, j)
                    if self.reversiMatrix[lin+(i*2)][col+(j*2)] == self.estado:
                        self.reversiMatrix[lin+i][col+j] = self.estado
                    return
            return
        
        if self.reversiMatrix[linha][(ord(coluna)-ord('a'))] != ' - ':
            return 'invalido'
        else:
            col = (ord(coluna)-ord('a'))
            lin = linha
            self.reversiMatrix[lin][col] = self.estado
            
            for i in range(-1,2):
                for j in range(-1,2):
                    _trocaEstado(lin, col, i, j)
            
            self.JogadaTemp = [lin,col,self.estado[1]]
            return 'continua'
    
    def _atualizaPontos(self):
        z = 0
        c = 0
        a = 0
        for i in range(self.dimLinhas):
            for j in range(self.dimColunas):
                if self.reversiMatrix[i][j] == ' 0 ':
                    z += 1
                if self.reversiMatrix[i][j] == ' # ':
                    c += 1
                if self.reversiMatrix[i][j] == ' - ':
                    a += 1
        self.zero = z
        self.charp = c
        return a
            
    def _processaComando(self, jogada):
        if jogada == 'N':
            return 'novo'
        elif jogada == 'F':
            return 'sair'
        elif jogada =='U':
            if self.last != None:
                return 'refazer'
            return 'nrefazer'
        elif jogada == 'T':
            self.clear()
            #print(self.recs)
            self.msgText = self.recs.getRecordsTableStr()
            self.msg = True
            print(self)
            self.msg = False
            self._input("\nPrima [enter] para continuar...")
            return
        elif jogada == 'H':
            self.clear()
            self.msg = True
            self.msgText ="""\nN – (Novo jogo) Recomeça uma nova partida considerando derrota do jogador corrente.
F – (Fim) Após confirmação do utilizador, termina o jogo e o programa.
U – (Undo) Desfaz a última jogada, dando hipótese do jogador anterior jogar novamente. Com este comando deve ser possível
desfazer mais do que uma jogada.
T – (Tabela Top 10) Apresenta a tabela dos 10 melhores jogos realizados indicando o número de peças de cada jogador e o nome
do vencedor, sendo o melhor jogo o que teve mais peças do jogador vencedor. Esta tabela poderá ser atualizada no final de
um jogo com mais peças do vencedor que as do último da tabela, sendo necessário perguntar o nome do vencedor.
H – (Help) Apresenta todos os comandos indicando a letra e a descrição sumária de cada um.\n\n""" 
            print(self)
            self.msg = False
            self._input("Prima [enter] para continuar...")
            return
        
        try:
            if len(jogada) == 2 or len(jogada) == 3:
                linha = (int(jogada[0]) - 1) if len(jogada) == 2 else ((int(jogada[0])*10)+int(jogada[1])-1)
                coluna = str(jogada[1]) if len(jogada) == 2 else str(jogada[2])
                if not self._verificaArea(linha,(ord(coluna)-ord('a'))):
                    return 'invalido'
                self._guardaEstadoActual()
                return self._aplicaJogada(linha,coluna)
            else:
                return 'invalido'
        except:
            return 'invalido'
    
    def _iniciarVariaveis(self):
        self.reversiMatrix = [ [ "   " for i in range(self.dimLinhas) ]
                               for j in range(self.dimColunas) ]

        self.reversiMatrix[int(self.dimLinhas/2)][int(self.dimColunas/2)] = ' 0 '
        self.reversiMatrix[int(self.dimLinhas/2)-1][int(self.dimColunas/2)-1] = ' 0 '
        self.reversiMatrix[int(self.dimLinhas/2)-1][int(self.dimColunas/2)] = ' # '
        self.reversiMatrix[int(self.dimLinhas/2)][int(self.dimColunas/2)-1] = ' # '
        ## VARIAVEIS DE SCORE ##
        self.recs = Records("MPDS.rve",self.recNum)
        self.charp = 2
        self.zero = 2
        self.estado = ' # '
        self.nestado = ' 0 '
        self.mensagem = "Inicio do jogo. # é o primeiro jogador. Para ajuda digite H\n"
        self.JogadaTemp = None
        self.last = None
        self.msgText = ""
        self.msg = False
    
    def _refazer(self):
        
        self.reversiMatrix = self.last.reversiMatrix
        self.charp = self.last.charp
        self.zero = self.last.zero
        self.estado = self.last.estado
        self.nestado = self.last.nestado
        self.mensagem = self.last.mensagem
        self.JogadaTemp = self.last.JogadaTemp
        self.last = self.last.last
    
    def _guardaEstadoActual(self):
        self.last = copy.copy(self)
        self.last.reversiMatrix = [ [ "   " for i in range(self.dimLinhas) ]
                               for j in range(self.dimColunas) ]
        for i in range(self.dimLinhas):
            for j in range(self.dimColunas):
                self.last.reversiMatrix[i][j] = str(self.reversiMatrix[i][j])
    
    def __str__(self):
        if self.msg == True:
            return self.msgText
        #os.system('clear')
        self.clear()
        strStruct = self.mensagem + '\n'
        if self.reversiMatrix == None:
            return self
        strStruct += '    '
        for idd in range(self.dimColunas):
            strStruct += " "+chr(idd+(ord('a')))+"  "
        strStruct += "\n"
        strStruct += "    "+(("--- ")*(self.dimColunas))+"\n"
        for i in range(self.dimLinhas):
            strStruct += str(i+1)
            strStruct += "  |" if i+1<10 else " |"
            for j in range(self.dimColunas):
                strStruct += self.reversiMatrix[i][j]+"|"
            strStruct += "\n"
            if i != self.dimLinhas-1:
                strStruct += "   +"+(("---+")*(self.dimColunas))+"\n"
        strStruct += "    "+(("--- ")*(self.dimColunas))+"\n"
        return strStruct
    
    def __init__(self, dimLinhas, dimColunas, recNum):
        '''
        Recebe como parametros as dimensões da matriz que compões o numero de linhas
        e colunas da grelha do jogo.
        '''
        self.dimLinhas = dimLinhas
        self.dimColunas = dimColunas
        self.recNum = recNum
        self._iniciarVariaveis()
        
    def iniciarJogo(self):
        while True:
            varEstado = self._iniciarCiclo()
            if varEstado == 'novo':
                self._iniciarVariaveis()
                continue
            if varEstado == 'sair':
                break
        
    def _porRecords(self):
        self.clear()
        aux = 0
        if not self.zero == self.charp:
            pontos = self.zero if self.zero > self.charp else self.charp 
            if self.recs.isFull() and pontos < self.recs.getLastRecord():
                aux = -1
            vencedor = '0' if self.zero > self.charp else '#'
            self.msg = True
            self.msgText = "O Jogador '"+vencedor+"' ganhou a partida." 
            print(self)
            self.msg = False
            if aux != -1:
                self.recs.putRecord(self._input("Qual o seu nome? "), pontos)

    def _iniciarCiclo(self):
        endedGame = False
        aux = -1
        self._actualizaPossibilidades()
        while True:
            if endedGame:
                break
            if self.JogadaTemp != None: ## Atribui os '()' à jogada temporaria
                self.reversiMatrix[self.JogadaTemp[0]][self.JogadaTemp[1]] = "("+self.JogadaTemp[2]+")"
            print(self)
            if self.JogadaTemp != None: ## Retira os '()' à jogada temporaria apos print()
                self.reversiMatrix[self.JogadaTemp[0]][self.JogadaTemp[1]] = " "+self.JogadaTemp[2]+" "
            if aux == 0:
                self._porRecords()
                self._input("para recomeçar prima [enter]")
                return 'novo'
            jogada = self._input("("+str(self.charp)+","+str(self.zero)+") "+str(self.estado[1])+">")
            estado = self._processaComando(jogada)
            if estado == 'novo' or estado == 'sair':
                self._porRecords()
                strAux = " jogo" if estado == 'novo' else " do jogo"
                self._input("\nPrima [enter] para "+estado+strAux)
                return estado
            if estado == 'invalido':
                self.mensagem = "Jogada inválida, proximo jogador -> "+self.nestado[1]
                self._trocaTurno()
                self._actualizaPossibilidades()
                aux = self._atualizaPontos()
                continue
            if estado == 'continua':
                self._trocaTurno()
                self._actualizaPossibilidades()
                self.mensagem = "Jogada válida, proximo jogador -> "+self.estado[1]
                aux = self._atualizaPontos()
                continue
            if estado == 'refazer':
                self._refazer()
                aux = self._atualizaPontos()
                self.mensagem = "Refazer jogada, proximo jogador -> "+self.estado[1]
                continue
            if estado == 'nrefazer':
                self.mensagem = "Não existem jogadas anteriores. Proximo jogador -> "+self.nestado[1]
                continue

    def _input(self, mensagem):
        return input(mensagem)

    def clear(self):
        return ## Não está implementado
    
        
Beispiel #33
0
class ReportManager():
    """The primary controller.
    Manages one 'project' at a time.
    Coordinates the form for input, records for storage and report for generating output"""
    def __init__(self):
        # if 'new.txt' exists, show it in a dialog
        if os.path.exists('new.txt'):
            msg = open('new.txt').read()
            new_dlg = WhatsNew(self, msg)
            if new_dlg.ShowModal() == wx.ID_CANCEL:
                os.remove('new.txt')
            else:
                pass
                
        
        configfile = self.get_configfile()
        self.config = Config(configfile)
        self.init_project()


    def init_project(self):
        """Common code for initialising project"""
        self.load_project()

        self.records = Records(self.db_file, self.index_file, self.passfile,
                               self.config.options['num_backups'],
                               self.config.options['backup_freq'])
        self.register = Register(self, self.records, self.project_name)
        

    def unload_current_project(self):
        """Close cleanly current loaded project"""
        self.register.Destroy()
        
        
    def get_configfile(self):
        """Get path to config file"""
        platform = sys.platform
        if platform.startswith('linux'):
            return os.path.expanduser('~/.reportmanagerrc')
        elif platform == 'win32':
            return 'reportmanager.conf'
        
        
    def load_project(self, project_dir = None):
        """load project based on options in config file"""
        self.project_dir = self.config.options['projects'][
            int(self.config.options['default_project'])]
   
        # paths
        self.fields_file = os.path.join(self.project_dir, 'fields.yaml')
        self.index_file = os.path.join(self.project_dir, 'index.yaml')
        self.report_files = glob.glob(os.path.join(self.project_dir, '*.rst'))
        self.db_file = os.path.join(self.project_dir, 'records.db')
        self.all_stylefile = os.path.join(self.project_dir, 'all.sty')
        self.passfile = os.path.join(self.project_dir, 'pass.hsh')

        # images (including logo) will all be stored in an image folder.
        self.image_folder = os.path.join(self.project_dir, 'images')
        
        self.tpl_files = glob.glob(os.path.join(self.project_dir, '*.tpl'))
        
        self.project_name = os.path.basename(self.project_dir)
        
        # verify
        VALID_PROJ = True
        missing_files = []

        if not os.path.exists(self.fields_file):
            print 'missing fields', self.fields_file
            VALID_PROJ = False
            missing_files.append('Fields file')

        if not os.path.exists(self.index_file):
            VALID_PROJ = False
            missing_files.append('Index file')

        if len(self.report_files) == 0:
            VALID_PROJ = False
            missing_files.append('Report_Files')

        if not VALID_PROJ:
            print 'Not all files required for project are present. The following files are missing'
            for f in missing_files:
                print f
            print 'exiting ...'
            sys.exit()


    def change_project(self, event):
        """Load a new project"""
        project_chooser = ProjectChooser(None, self.config)
        if project_chooser.ShowModal() == wx.ID_OK:
            chosen_project = project_chooser.default_project
            self.config.options['default_project'] = chosen_project
            project_chooser.Destroy()

        self.unload_current_project()
        self.init_project()

            
    def new_record(self, event):
        """Insert new record.
        Get values by presenting an empty form"""
        # does user want to fill with template ?
        template_name = None
        # show template chooser only if there are some templates
        if len(self.tpl_files) > 0:
            template_chooser = TemplateChooser(None, self.project_dir, self.tpl_files)

            if template_chooser.ShowModal() == wx.ID_CANCEL:
                return

            elif template_chooser.ShowModal() == wx.ID_OK:
                template_name = template_chooser.chosentemplate
                template_chooser.Destroy()


        if template_name == None:
            form = Form(None, self.fields_file, 'Fill in the values')            
        else:
            template_vals = yaml.load(open(template_name))
            form = Form(None, self.fields_file, 'Fill in the values', template_vals)

        if form.ShowModal() == wx.ID_OK:
            form.get_values()

            # Initialise lock as open
            form.vals['LOCK_STATUS'] = 'unlocked'
            self.records.insert_record(form.vals)

            # recreate index
            #self.register.index_summary = self.records.create_index()
            self.register.refresh_records()
                                    
        form.Destroy()


    def new_template(self, event):
        """Create a new template"""
        form = Form(None, self.fields_file, 'Fill in the values for template')
        if form.ShowModal() == wx.ID_OK:
            form.get_values()
            template_vals = form.vals
            form.Destroy()
            
            # get template name
            name_entry = wx.TextEntryDialog(None, 'Enter name for template')
            if name_entry.ShowModal() == wx.ID_OK:
                template_name = name_entry.GetValue()
                if not template_name.endswith('.tpl'):
                    template_name += '.tpl'
                template_name = os.path.join(self.project_dir, template_name)
                
            else:
                return

            # write the template
            yaml.dump(template_vals, open(template_name, 'w'))
        

    def del_template(self, event):
        """Delete an existing template"""
        template_chooser = TemplateChooser(None, self.project_dir)
        if template_chooser.ShowModal() == wx.ID_OK:
            template_name = template_chooser.chosentemplate
            template_chooser.Destroy()
        else:
            template_name = 'Empty'

        if template_name == 'Empty':
            return
        else:
            os.remove(template_name) #TODO: will raise an exception windows if file is in use

            
    def edit_record(self, event):
        """Load the selected record into a form for editing."""
        selected_record = self.register.record_display.GetFirstSelected()

        if selected_record == -1:
            self.register.SetStatusText('No record selected', 0)
            return

        id = str(self.register.record_display.GetItemData(selected_record))

        record_vals = self.records.retrieve_record(id)

        if self.is_locked(selected_record):
            form = ReadOnlyForm(None, self.fields_file,
                        'Locked record. Cannot edit', record_vals)
            if form.ShowModal() == wx.ID_OK:
                form.Destroy
        else:
            form = Form(None, self.fields_file, 'Edit the values', record_vals)

            if form.ShowModal() == wx.ID_OK:
                form.get_values()
                # insert record with same id
                self.records.insert_record(form.vals, id)
                self.register.refresh_records()

            form.Destroy()
        

    def export_record(self, event):
        """Export the selected record into another project db.
        Matching fields are alone exported while others are ignored"""
        # get project to export to
        project_chooser = ProjectChooser(None, self.config)
        if project_chooser.ShowModal() == wx.ID_OK:
            chosen_project = project_chooser.default_project

        # cancel export otherwise
        else:
            return
         
        # Get the record vals
        selected_record = self.register.record_display.GetFirstSelected()
        if selected_record == -1:
            self.register.SetStatusText('No record selected', 0)
            return

        id = str(self.register.record_display.GetItemData(selected_record))
        record_vals = self.records.retrieve_record(id)
        record_vals['LOCK_STATUS'] = 'unlocked'

        # if same project is selected, clone it
        if chosen_project == self.config.options['default_project']:
            self.records.insert_record(record_vals)
            self.register.refresh_records()

        # if other project selected, open that db and enter compatible vals
        # get values for other project
        other_project_dir = self.config.options['projects'][chosen_project]
   
        # load paths for other project
        #self.fields_file = os.path.join(self.project_dir, 'fields.yaml')
        index_file = os.path.join(other_project_dir, 'index.yaml')
        db_file = os.path.join(other_project_dir, 'records.db')
        passfile = os.path.join(other_project_dir, 'pass.hsh')

        self.recipient_records = Records(db_file, index_file, passfile,
                                         self.config.options['num_backups'],
                                         self.config.options['backup_freq'])
        self.recipient_records.insert_record(record_vals)
        # TODO: close the loaded records
        
            
    def is_locked(self, record):
        """Is the record locked. record is index obained from the listctrl"""
        # last entry will always be lock status
        lock_status = self.register.record_display.GetItem(record,
                      len(self.records.index_fields)-1).GetText()

        if lock_status == 'locked':
            return True
        else:
            return False

        
    def toggle_lock(self):
        """Toggle the locked status of the selected record.
        Only priveleges user (admin) should be allowed to use this"""
        selected_record = self.register.record_display.GetFirstSelected()
        
        if selected_record == -1:
            self.register.SetStatusText('No record selected', 0)
            return

        id = str(self.register.record_display.GetItemData(selected_record))
        record_vals = self.records.retrieve_record(id)

        # if there is no lock_status, it is unlocked
        try:
            lock_status = record_vals['LOCK_STATUS']
        except KeyError:
            lock_status = 'unlocked'
        
        if lock_status == 'unlocked':
            record_vals['LOCK_STATUS'] = 'locked'
            self.register.SetStatusText('Locked selected record')
        else:
            record_vals['LOCK_STATUS'] = 'unlocked'
            self.register.SetStatusText('Unlocked selected record')

        self.records.insert_record(record_vals, id)
        self.register.index_summary = self.records.create_index()
        
        self.register.refresh_records()
            

    def flush_report(self, event):
        """Remove the stored raw report for the record if it exists"""
        selected_record = self.register.record_display.GetFirstSelected()

        if selected_record == -1:
            print 'No record selected'
            return

        id = str(self.register.record_display.GetItemData(selected_record))
        
        record_vals = self.records.retrieve_record(id)

        record_vals['raw_report'] = ''

        #self.records.delete_record(id)
        self.records.insert_record(record_vals, id)

        
    def show_n_edit_report(self, event):
        """Display the report for the selected record and allow edits"""
        selected_record = self.register.record_display.GetFirstSelected()

        if selected_record == -1:
            self.register.SetStatusText('No record selected', 0)
            return

        # convert to string coz unicode object does not work
        id = str(self.register.record_display.GetItemData(selected_record))
        
        template_file = self.report_files[event.Id // 2]
        record_vals = self.records.retrieve_record(id)

        # retrieve stored raw report
        try:
            raw_report = record_vals['raw_report']
        except KeyError:
            raw_report = ''

            # create qr code image, pass filename to record_vals
            qrimg_data = [(k, record_vals[k]) for k in self.records.qrcode_fields]
            _, qrimg_filename = tempfile.mkstemp(suffix='.jpg')
            qr = QRImg(qrimg_data, qrimg_filename)
            qr.make_image()
            record_vals['qrimg'] = qrimg_filename
            print record_vals['qrimg']
            
        # style file in the project directory
        # same name as report or all.sty
        local_stylefile = os.path.splitext(template_file)[0] + '.sty'
        global_stylefile = os.path.join(os.path.dirname(template_file), 'all.sty')
        
        if os.path.exists(local_stylefile):
            rep = Report(template_file, record_vals, self.image_folder,
                         id, raw_report, local_stylefile)
        elif os.path.exists(global_stylefile):
            rep = Report(template_file, record_vals, self.image_folder,
                         id, raw_report, global_stylefile)
        else:
            rep = Report(template_file, record_vals, self.image_folder,
                         id, raw_report)

        raw_report =  rep.edit_report()
        
        record_vals['raw_report'] = raw_report
        self.records.insert_record(record_vals, id)
        
        
    def display_pdf(self, pdf_file):
        """Display the pdf using the native viewer"""
        if sys.platform.startswith('linux'):
            time.sleep(2)
            subprocess.Popen(['evince', pdf_file])

        elif sys.platform == 'win32':
            os.startfile(pdf_file)


    def summarize_numerical(self, fieldname, FILTER_SUMMARY):
        """Calculate summary for numerical data with
        field name (key) fieldname"""
        val_id_pairs = self.records.retrieve_column_with_id(fieldname)
        #col = self.records.retrieve_column(fieldname)
        # only restricted ids
        if FILTER_SUMMARY:
            vals = [val for (val, id) in val_id_pairs if id in self.register.restrict_ids]
        else:
            vals = [val for (val, id) in val_id_pairs]
        
        
        
        numerical_cols = [str2float(val) for val in vals if str2float(val) != '']

        # mean = numpy.mean(numerical_cols)
        # stdev = numpy.std(numerical_cols)
        mean, stdev = meanstdv(numerical_cols)
        minimum = min(numerical_cols)
        maximum = max(numerical_cols)
        total_vals = len(vals)
        missing_vals = total_vals - len(numerical_cols)
        
        return mean, stdev, minimum, maximum, total_vals, missing_vals


    def summarize_categorical(self, fieldname, FILTER_SUMMARY):
        """summarize categorical data"""
        val_id_pairs = self.records.retrieve_column_with_id(fieldname)
        uniq = {}

        # only restricted ids
        if FILTER_SUMMARY:
            vals = [val for (val, id) in val_id_pairs if id in self.register.restrict_ids]
        else:
            vals = [val for (val, id) in val_id_pairs]
        
        for val in vals:
            if val in uniq:
                uniq[val] += 1
            else:
                uniq[val] = 1

        result = []
        for key in uniq:
            result.append((key, str(uniq[key])))
              
        return result


    def cat_summary(self, event):
        #TODO: retrive fieldnames in init and dont keep repeating
        catsummary = CatSummary(self, self.get_fieldnames(self.fields_file))
        catsummary.Show()
    
    def num_summary(self, event):
        numsummary = NumSummary(self, self.get_fieldnames(self.fields_file))
        numsummary.Show()

    def get_fieldnames(self, fields_file):
        """retrieve the index names"""
        fieldnames = []
        fields_data = yaml.load_all(open(fields_file))

        for data in fields_data: #collection of dictionaries

            prefix = data.keys()[0]
            
            for i in range(len(data[prefix])):
                suffix = data[prefix][i][0]
                fieldnames.append(prefix + '_' + suffix)

        # for searching all
        fieldnames = ['Anywhere'] + fieldnames
        return fieldnames