


from abc import ABC, abstractmethod
from typing import List, Optional


class   a__	(						lowerCAmelCase_    ):

       def __init__(   self      :     List[Any]    ):
            # test for the above condition
            self.test()

       def 						UpperCAmelCase(   self      :     Tuple    ):
            a_    :     int										=    0
            a_    :     Tuple										=    False
            while not completed:
                 if counter == 1:
                      self.reset()
                 a_    :     Tuple										=    self.advance()
                 if not self.does_advance(lowerCamelCase_    ):
                      raise Exception(
                          """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."""    )

                 a_			,			a_			,			a_    :     Dict										=    self.update(lowerCamelCase_    )
                 counter += 1

                 if counter > 1_0_0_0_0:
                      raise Exception("""update() does not fulfill the constraint."""    )

            if self.remaining() != 0:
                 raise Exception("""Custom Constraint is not defined correctly."""    )

       @abstractmethod
       def 						UpperCAmelCase(   self      :     Any    ):
            raise NotImplementedError(
                F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )

       @abstractmethod
       def 						UpperCAmelCase(   self      :     Optional[int]      ,							lowerCamelCase_      :     int    ):
            raise NotImplementedError(
                F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )

       @abstractmethod
       def 						UpperCAmelCase(   self      :     str      ,							lowerCamelCase_      :     int    ):
            raise NotImplementedError(
                F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )

       @abstractmethod
       def 						UpperCAmelCase(   self      :     int    ):
            raise NotImplementedError(
                F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )

       @abstractmethod
       def 						UpperCAmelCase(   self      :     Any    ):
            raise NotImplementedError(
                F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )

       @abstractmethod
       def 						UpperCAmelCase(   self      :     List[Any]      ,							lowerCamelCase_      :     Tuple=False    ):
            raise NotImplementedError(
                F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''    )


class   a__	(						lowerCAmelCase_    ):

       def __init__(   self      :     Dict      ,							lowerCamelCase_      :     List[int]    ):
            super(lowerCamelCase_      ,							self    ).__init__()

            if not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ) or len(lowerCamelCase_    ) == 0:
                 raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.'''    )
            if any((not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ) or token_id < 0) for token_id in token_ids    ):
                 raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.'''    )

            a_    :     Optional[Any]										=    token_ids

            a_    :     List[str]										=    len(self.token_ids    )
            a_    :     Optional[int]										=    -1  # the index of the currently fulfilled step
            a_    :     Optional[int]										=    False

       def 						UpperCAmelCase(   self      :     Any    ):
            if self.completed:
                 return None
            return self.token_ids[self.fulfilled_idx + 1]

       def 						UpperCAmelCase(   self      :     Optional[Any]      ,							lowerCamelCase_      :     int    ):
            if not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                 raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(lowerCamelCase_    )}'''    )

            if self.completed:
                 return False

            return token_id == self.token_ids[self.fulfilled_idx + 1]

       def 						UpperCAmelCase(   self      :     Any      ,							lowerCamelCase_      :     int    ):
            if not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                 raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(lowerCamelCase_    )}'''    )

            a_    :     Dict										=    False
            a_    :     List[Any]										=    False
            a_    :     Optional[int]										=    False

            if self.does_advance(lowerCamelCase_    ):
                 self.fulfilled_idx += 1
                 a_    :     int										=    True
                 if self.fulfilled_idx == (self.seqlen - 1):
                      a_    :     List[Any]										=    True
                 a_    :     Optional[Any]										=    completed
            else:
                 # failed to make progress.
                 a_    :     int										=    True
                 self.reset()
            return stepped, completed, reset

       def 						UpperCAmelCase(   self      :     int    ):
            a_    :     str										=    False
            a_    :     Dict										=    0

       def 						UpperCAmelCase(   self      :     str    ):
            return self.seqlen - (self.fulfilled_idx + 1)

       def 						UpperCAmelCase(   self      :     str      ,							lowerCamelCase_      :     str=False    ):
            a_    :     Optional[int]										=    PhrasalConstraint(self.token_ids    )

            if stateful:
                 a_    :     List[str]										=    self.seqlen
                 a_    :     Optional[Any]										=    self.fulfilled_idx
                 a_    :     Optional[Any]										=    self.completed

            return new_constraint


class   a__	:

       def __init__(   self      :     Optional[int]      ,							lowerCamelCase_      :     List[List[int]]      ,							lowerCamelCase_      :     int=True    ):
            a_    :     Optional[Any]										=    max([len(lowerCamelCase_    ) for one in nested_token_ids]    )

            a_    :     int										=    {}
            for token_ids in nested_token_ids:
                 a_    :     Union[str, Any]										=    root
                 for tidx, token_id in enumerate(lowerCamelCase_    ):
                      if token_id not in level:
                           a_    :     Optional[Any]										=    {}

                      a_    :     Dict										=    level[token_id]

            if no_subsets and self.has_subsets(lowerCamelCase_      ,							lowerCamelCase_    ):
                 raise ValueError(
                     """Each list in `nested_token_ids` can't be a complete subset of another list, but is"""
                     F''' {nested_token_ids}.'''    )

            a_    :     Union[str, Any]										=    root

       def 						UpperCAmelCase(   self      :     Optional[int]      ,							lowerCamelCase_      :     Tuple    ):
            a_    :     Union[str, Any]										=    self.trie

            for current_token in current_seq:
                 a_    :     Any										=    start[current_token]

            a_    :     List[str]										=    list(start.keys()    )

            return next_tokens

       def 						UpperCAmelCase(   self      :     Union[str, Any]      ,							lowerCamelCase_      :     List[Any]    ):
            a_    :     Optional[int]										=    self.next_tokens(lowerCamelCase_    )

            return len(lowerCamelCase_    ) == 0

       def 						UpperCAmelCase(   self      :     Optional[Any]      ,							lowerCamelCase_      :     Union[str, Any]    ):
            a_    :     Union[str, Any]										=    list(root.values()    )
            if len(lowerCamelCase_    ) == 0:
                 return 1
            else:
                 return sum([self.count_leaves(lowerCamelCase_    ) for nn in next_nodes]    )

       def 						UpperCAmelCase(   self      :     Optional[int]      ,							lowerCamelCase_      :     int      ,							lowerCamelCase_      :     Optional[Any]    ):
            a_    :     Optional[int]										=    self.count_leaves(lowerCamelCase_    )
            return len(lowerCamelCase_    ) != leaf_count


class   a__	(						lowerCAmelCase_    ):

       def __init__(   self      :     Union[str, Any]      ,							lowerCamelCase_      :     List[List[int]]    ):
            super(lowerCamelCase_      ,							self    ).__init__()

            if not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ) or len(lowerCamelCase_    ) == 0:
                 raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.'''    )
            if any(not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ) for token_ids in nested_token_ids    ):
                 raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.'''    )
            if any(
                any((not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ) or token_id < 0) for token_id in token_ids    )
                for token_ids in nested_token_ids    ):
                 raise ValueError(
                     F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.'''    )

            a_    :     Tuple										=    DisjunctiveTrie(lowerCamelCase_    )
            a_    :     List[str]										=    nested_token_ids

            a_    :     int										=    self.trie.max_height
            a_    :     Union[str, Any]										=    []
            a_    :     List[str]										=    False

       def 						UpperCAmelCase(   self      :     List[Any]    ):
            a_    :     int										=    self.trie.next_tokens(self.current_seq    )

            if len(lowerCamelCase_    ) == 0:
                 return None
            else:
                 return token_list

       def 						UpperCAmelCase(   self      :     Dict      ,							lowerCamelCase_      :     int    ):
            if not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                 raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowerCamelCase_    )}'''    )

            a_    :     Tuple										=    self.trie.next_tokens(self.current_seq    )

            return token_id in next_tokens

       def 						UpperCAmelCase(   self      :     Optional[Any]      ,							lowerCamelCase_      :     int    ):
            if not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                 raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowerCamelCase_    )}'''    )

            a_    :     Union[str, Any]										=    False
            a_    :     Any										=    False
            a_    :     Tuple										=    False

            if self.does_advance(lowerCamelCase_    ):
                 self.current_seq.append(lowerCamelCase_    )
                 a_    :     Optional[int]										=    True
            else:
                 a_    :     str										=    True
                 self.reset()

            a_    :     Optional[Any]										=    self.trie.reached_leaf(self.current_seq    )
            a_    :     Union[str, Any]										=    completed

            return stepped, completed, reset

       def 						UpperCAmelCase(   self      :     Any    ):
            a_    :     Union[str, Any]										=    False
            a_    :     Union[str, Any]										=    []

       def 						UpperCAmelCase(   self      :     List[Any]    ):
            if self.completed:
                 # since this can be completed without reaching max height
                 return 0
            else:
                 return self.seqlen - len(self.current_seq    )

       def 						UpperCAmelCase(   self      :     Union[str, Any]      ,							lowerCamelCase_      :     Optional[Any]=False    ):
            a_    :     Any										=    DisjunctiveConstraint(self.token_ids    )

            if stateful:
                 a_    :     List[str]										=    self.seqlen
                 a_    :     Dict										=    self.current_seq
                 a_    :     List[str]										=    self.completed

            return new_constraint


class   a__	:

       def __init__(   self      :     Optional[int]      ,							lowerCamelCase_      :     List[Constraint]    ):
            a_    :     Optional[int]										=    constraints

            # max # of steps required to fulfill a given constraint
            a_    :     Optional[int]										=    max([c.seqlen for c in constraints]    )
            a_    :     List[str]										=    len(lowerCamelCase_    )
            a_    :     str										=    False

            self.init_state()

       def 						UpperCAmelCase(   self      :     Tuple    ):
            a_    :     List[str]										=    []
            a_    :     List[str]										=    None
            a_    :     Union[str, Any]										=    [constraint.copy(stateful=lowerCamelCase_    ) for constraint in self.constraints]

       def 						UpperCAmelCase(   self      :     List[Any]    ):
            a_    :     Dict										=    0
            if self.inprogress_constraint:
                 # extra points for having a constraint mid-fulfilled
                 add += self.max_seqlen - self.inprogress_constraint.remaining()

            return (len(self.complete_constraints    ) * self.max_seqlen) + add

       def 						UpperCAmelCase(   self      :     Tuple    ):
            a_    :     Tuple										=    []
            if self.inprogress_constraint is None:
                 for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
                      a_    :     Any										=    constraint.advance()
                      if isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                           token_list.append(lowerCamelCase_    )
                      elif isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                           token_list.extend(lowerCamelCase_    )
            else:
                 a_    :     int										=    self.inprogress_constraint.advance()
                 if isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                      token_list.append(lowerCamelCase_    )
                 elif isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                      token_list.extend(lowerCamelCase_    )

            if len(lowerCamelCase_    ) == 0:
                 return None
            else:
                 return token_list

       def 						UpperCAmelCase(   self      :     Optional[Any]      ,							lowerCamelCase_      :     Optional[List[int]]    ):
            self.init_state()

            if token_ids is not None:
                 for token in token_ids:
                      # completes or steps **one** constraint
                      a_			,			a_    :     Optional[int]										=    self.add(lowerCamelCase_    )

                      # the entire list of constraints are fulfilled
                      if self.completed:
                           break

       def 						UpperCAmelCase(   self      :     int      ,							lowerCamelCase_      :     int    ):
            if not isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                 raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.'''    )

            a_			,			a_    :     List[str]										=    False, False

            if self.completed:
                 a_    :     List[Any]										=    True
                 a_    :     Tuple										=    False
                 return complete, stepped

            if self.inprogress_constraint is not None:
                 # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
                 # job, simply update the state

                 a_			,			a_			,			a_    :     Union[str, Any]										=    self.inprogress_constraint.update(lowerCamelCase_    )
                 if reset:
                      # 1. If the next token breaks the progress, then we must restart.
                      #     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

                      #     But that doesn't mean we self.init_state(), since we only reset the state for this particular
                      #     constraint, not the full list of constraints.

                      self.pending_constraints.append(self.inprogress_constraint.copy(stateful=lowerCamelCase_    )    )
                      a_    :     str										=    None

                 if complete:
                      # 2. If the next token completes the constraint, move it to completed list, set
                      #     inprogress to None. If there are no pending constraints either, then this full list of constraints
                      #     is complete.

                      self.complete_constraints.append(self.inprogress_constraint    )
                      a_    :     Union[str, Any]										=    None

                      if len(self.pending_constraints    ) == 0:
                           # we're done!
                           a_    :     Optional[int]										=    True

            else:
                 # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
                 # of constraints?

                 for cidx, pending_constraint in enumerate(self.pending_constraints    ):
                      if pending_constraint.does_advance(lowerCamelCase_    ):
                           a_			,			a_			,			a_    :     Tuple										=    pending_constraint.update(lowerCamelCase_    )

                           if not stepped:
                                raise Exception(
                                    """`constraint.update(token_id)` is not yielding incremental progress, """
                                    """even though `constraint.does_advance(token_id)` is true."""    )

                           if complete:
                                self.complete_constraints.append(lowerCamelCase_    )
                                a_    :     int										=    None

                           if not complete and stepped:
                                a_    :     List[str]										=    pending_constraint

                           if complete or stepped:
                                # If we made any progress at all, then it's at least not a "pending constraint".

                                a_    :     Any										=    (
                                    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
                                )

                                if len(self.pending_constraints    ) == 0 and self.inprogress_constraint is None:
                                     # If there's no longer any pending after this and no inprogress either, then we must be
                                     # complete.

                                     a_    :     Optional[Any]										=    True

                                break  # prevent accidentally stepping through multiple constraints with just one token.

            return complete, stepped

       def 						UpperCAmelCase(   self      :     Optional[int]      ,							lowerCamelCase_      :     Optional[Any]=True    ):
            a_    :     Optional[int]										=    ConstraintListState(self.constraints    )  # we actually never though self.constraints objects
            # throughout this process. So it's at initialization state.

            if stateful:
                 a_    :     Dict										=    [
                     constraint.copy(stateful=lowerCamelCase_    ) for constraint in self.complete_constraints
                 ]
                 if self.inprogress_constraint is not None:
                      a_    :     Any										=    self.inprogress_constraint.copy(stateful=lowerCamelCase_    )
                 a_    :     Dict										=    [constraint.copy() for constraint in self.pending_constraints]

            return new_state







import numpy as np

__lowerCamelCase        =     [
    ['''a''', '''b''', '''c''', '''d''', '''e'''],
    ['''f''', '''g''', '''h''', '''i''', '''k'''],
    ['''l''', '''m''', '''n''', '''o''', '''p'''],
    ['''q''', '''r''', '''s''', '''t''', '''u'''],
    ['''v''', '''w''', '''x''', '''y''', '''z'''],
]


class   a__	:

       def __init__(   self      :     Union[str, Any]    ):
            a_    :     List[Any]										=    np.array(lowerCamelCase_    )

       def 						UpperCAmelCase(   self      :     Union[str, Any]      ,							lowerCamelCase_      :     str    ):
            a_			,			a_    :     Optional[int]										=    np.where(letter == self.SQUARE    )
            a_    :     Union[str, Any]										=    np.concatenate([indexa + 1, indexa + 1]    )
            return indexes

       def 						UpperCAmelCase(   self      :     Tuple      ,							lowerCamelCase_      :     int      ,							lowerCamelCase_      :     int    ):
            a_    :     str										=    self.SQUARE[indexa - 1, indexa - 1]
            return letter

       def 						UpperCAmelCase(   self      :     Optional[Any]      ,							lowerCamelCase_      :     str    ):
            a_    :     List[str]										=    message.lower()
            a_    :     str										=    message.replace(""" """      ,							""""""    )
            a_    :     Union[str, Any]										=    message.replace("""j"""      ,							"""i"""    )

            a_    :     Optional[Any]										=    np.empty((2, len(lowerCamelCase_    ))    )
            for letter_index in range(len(lowerCamelCase_    )    ):
                 a_    :     int										=    self.letter_to_numbers(message[letter_index]    )

                 a_    :     str										=    numbers[0]
                 a_    :     int										=    numbers[1]

            a_    :     int										=    first_step.reshape(2 * len(lowerCamelCase_    )    )
            a_    :     Optional[Any]										=    """"""
            for numbers_index in range(len(lowerCamelCase_    )    ):
                 a_    :     Optional[Any]										=    int(second_step[numbers_index * 2]    )
                 a_    :     Optional[Any]										=    int(second_step[(numbers_index * 2) + 1]    )
                 a_    :     Optional[Any]										=    self.numbers_to_letter(lowerCamelCase_      ,							lowerCamelCase_    )
                 a_    :     List[str]										=    encoded_message + letter

            return encoded_message

       def 						UpperCAmelCase(   self      :     Tuple      ,							lowerCamelCase_      :     str    ):
            a_    :     Optional[Any]										=    message.lower()
            message.replace(""" """      ,							""""""    )
            a_    :     int										=    np.empty(2 * len(lowerCamelCase_    )    )
            for letter_index in range(len(lowerCamelCase_    )    ):
                 a_    :     str										=    self.letter_to_numbers(message[letter_index]    )
                 a_    :     Optional[int]										=    numbers[0]
                 a_    :     Optional[Any]										=    numbers[1]

            a_    :     Tuple										=    first_step.reshape((2, len(lowerCamelCase_    ))    )
            a_    :     Optional[int]										=    """"""
            for numbers_index in range(len(lowerCamelCase_    )    ):
                 a_    :     Dict										=    int(second_step[0, numbers_index]    )
                 a_    :     Tuple										=    int(second_step[1, numbers_index]    )
                 a_    :     Tuple										=    self.numbers_to_letter(lowerCamelCase_      ,							lowerCamelCase_    )
                 a_    :     Union[str, Any]										=    decoded_message + letter

            return decoded_message



