




"""simple docstring"""


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






class       lowercase(  __a				):







 '''simple docstring'''





 def __init__(       self:	Dict	):




   '''simple docstring'''



   self.test()


 def 				UpperCamelCase_     (       self:	Optional[Any]	):




   '''simple docstring'''



   _snake_case							:	Tuple			=						0
   _snake_case							:	List[Any]			=						False
   while not completed:
     if counter == 1:
       self.reset()
     _snake_case							:	List[str]			=						self.advance()
     if not self.does_advance(a_	):
       raise Exception(
           """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."""	)

     _snake_case	,      _snake_case	,      _snake_case							:	Union[str, Any]			=						self.update(a_	)
     counter += 1

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

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


 @abstractmethod
 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)


 @abstractmethod
 def 				UpperCamelCase_     (       self:	Optional[int],   a_:	int	):




   '''simple docstring'''



   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)


 @abstractmethod
 def 				UpperCamelCase_     (       self:	Optional[int],   a_:	int	):




   '''simple docstring'''



   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)


 @abstractmethod
 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)


 @abstractmethod
 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)


 @abstractmethod
 def 				UpperCamelCase_     (       self:	List[str],   a_:	Tuple=False	):




   '''simple docstring'''



   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)







class       lowercase(  __a				):







 '''simple docstring'''





 def __init__(       self:	Tuple,   a_:	List[int]	):




   '''simple docstring'''



   super(a_,   self	).__init__()

   if not isinstance(a_,   a_	) or len(a_	) == 0:
     raise ValueError(f"`token_ids` has to be a non-empty list, but is {token_ids}."	)
   if any((not isinstance(a_,   a_	) 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}."	)

   _snake_case							:	Optional[int]			=						token_ids

   _snake_case							:	Dict			=						len(self.token_ids	)
   _snake_case							:	Union[str, Any]			=						-1  # the index of the currently fulfilled step
   _snake_case							:	str			=						False


 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   if self.completed:
     return None
   return self.token_ids[self.fulfilled_idx + 1]


 def 				UpperCamelCase_     (       self:	List[Any],   a_:	int	):




   '''simple docstring'''



   if not isinstance(a_,   a_	):
     raise ValueError(f"`token_id` has to be an `int`, but is {token_id} of type {type(a_	)}"	)

   if self.completed:
     return False

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


 def 				UpperCamelCase_     (       self:	List[str],   a_:	int	):




   '''simple docstring'''



   if not isinstance(a_,   a_	):
     raise ValueError(f"`token_id` has to be an `int`, but is {token_id} of type {type(a_	)}"	)

   _snake_case							:	Optional[int]			=						False
   _snake_case							:	List[str]			=						False
   _snake_case							:	List[Any]			=						False

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


 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



   _snake_case							:	int			=						False
   _snake_case							:	Dict			=						0


 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   return self.seqlen - (self.fulfilled_idx + 1)


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




   '''simple docstring'''



   _snake_case							:	Dict			=						PhrasalConstraint(self.token_ids	)

   if stateful:
     _snake_case							:	List[Any]			=						self.seqlen
     _snake_case							:	str			=						self.fulfilled_idx
     _snake_case							:	Union[str, Any]			=						self.completed

   return new_constraint







class       lowercase:







 '''simple docstring'''





 def __init__(       self:	int,   a_:	List[List[int]],   a_:	int=True	):




   '''simple docstring'''



   _snake_case							:	List[str]			=						max([len(a_	) for one in nested_token_ids]	)

   _snake_case							:	int			=						{}
   for token_ids in nested_token_ids:
     _snake_case							:	List[str]			=						root
     for tidx, token_id in enumerate(a_	):
       if token_id not in level:
         _snake_case							:	int			=						{}

       _snake_case							:	List[Any]			=						level[token_id]

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

   _snake_case							:	int			=						root


 def 				UpperCamelCase_     (       self:	Tuple,   a_:	Tuple	):




   '''simple docstring'''



   _snake_case							:	Union[str, Any]			=						self.trie

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

   _snake_case							:	Any			=						list(start.keys()	)

   return next_tokens


 def 				UpperCamelCase_     (       self:	List[Any],   a_:	Optional[int]	):




   '''simple docstring'''



   _snake_case							:	Any			=						self.next_tokens(a_	)

   return len(a_	) == 0


 def 				UpperCamelCase_     (       self:	Dict,   a_:	List[Any]	):




   '''simple docstring'''



   _snake_case							:	int			=						list(root.values()	)
   if len(a_	) == 0:
     return 1
   else:
     return sum([self.count_leaves(a_	) for nn in next_nodes]	)


 def 				UpperCamelCase_     (       self:	str,   a_:	List[Any],   a_:	int	):




   '''simple docstring'''



   _snake_case							:	str			=						self.count_leaves(a_	)
   return len(a_	) != leaf_count







class       lowercase(  __a				):







 '''simple docstring'''





 def __init__(       self:	Tuple,   a_:	List[List[int]]	):




   '''simple docstring'''



   super(a_,   self	).__init__()

   if not isinstance(a_,   a_	) or len(a_	) == 0:
     raise ValueError(f"`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}."	)
   if any(not isinstance(a_,   a_	) 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(a_,   a_	) 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}."	)

   _snake_case							:	Optional[Any]			=						DisjunctiveTrie(a_	)
   _snake_case							:	Optional[int]			=						nested_token_ids

   _snake_case							:	Tuple			=						self.trie.max_height
   _snake_case							:	List[str]			=						[]
   _snake_case							:	Union[str, Any]			=						False


 def 				UpperCamelCase_     (       self:	Any	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						self.trie.next_tokens(self.current_seq	)

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


 def 				UpperCamelCase_     (       self:	Tuple,   a_:	int	):




   '''simple docstring'''



   if not isinstance(a_,   a_	):
     raise ValueError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(a_	)}"	)

   _snake_case							:	Optional[Any]			=						self.trie.next_tokens(self.current_seq	)

   return token_id in next_tokens


 def 				UpperCamelCase_     (       self:	Any,   a_:	int	):




   '''simple docstring'''



   if not isinstance(a_,   a_	):
     raise ValueError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(a_	)}"	)

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

   if self.does_advance(a_	):
     self.current_seq.append(a_	)
     _snake_case							:	Optional[Any]			=						True
   else:
     _snake_case							:	Tuple			=						True
     self.reset()

   _snake_case							:	Any			=						self.trie.reached_leaf(self.current_seq	)
   _snake_case							:	Tuple			=						completed

   return stepped, completed, reset


 def 				UpperCamelCase_     (       self:	str	):




   '''simple docstring'''



   _snake_case							:	Any			=						False
   _snake_case							:	Tuple			=						[]


 def 				UpperCamelCase_     (       self:	str	):




   '''simple docstring'''



   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:	Dict,   a_:	List[Any]=False	):




   '''simple docstring'''



   _snake_case							:	Union[str, Any]			=						DisjunctiveConstraint(self.token_ids	)

   if stateful:
     _snake_case							:	Tuple			=						self.seqlen
     _snake_case							:	List[str]			=						self.current_seq
     _snake_case							:	List[Any]			=						self.completed

   return new_constraint







class       lowercase:







 '''simple docstring'''





 def __init__(       self:	Any,   a_:	List[Constraint]	):




   '''simple docstring'''



   _snake_case							:	Any			=						constraints

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

   self.init_state()


 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						[]
   _snake_case							:	Union[str, Any]			=						None
   _snake_case							:	Optional[int]			=						[constraint.copy(stateful=a_	) for constraint in self.constraints]


 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



   _snake_case							:	Any			=						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:	Optional[int]	):




   '''simple docstring'''



   _snake_case							:	Union[str, Any]			=						[]
   if self.inprogress_constraint is None:
     for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
       _snake_case							:	str			=						constraint.advance()
       if isinstance(a_,   a_	):
         token_list.append(a_	)
       elif isinstance(a_,   a_	):
         token_list.extend(a_	)
   else:
     _snake_case							:	List[str]			=						self.inprogress_constraint.advance()
     if isinstance(a_,   a_	):
       token_list.append(a_	)
     elif isinstance(a_,   a_	):
       token_list.extend(a_	)

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


 def 				UpperCamelCase_     (       self:	int,   a_:	Optional[List[int]]	):




   '''simple docstring'''



   self.init_state()

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

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


 def 				UpperCamelCase_     (       self:	List[Any],   a_:	int	):




   '''simple docstring'''



   if not isinstance(a_,   a_	):
     raise ValueError(f"`token_id` should be an `int`, but is `{token_id}`."	)

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

   if self.completed:
     _snake_case							:	Dict			=						True
     _snake_case							:	List[Any]			=						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

     _snake_case	,      _snake_case	,      _snake_case							:	Optional[int]			=						self.inprogress_constraint.update(a_	)
     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=a_	)	)
       _snake_case							:	Union[str, Any]			=						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	)
       _snake_case							:	Dict			=						None

       if len(self.pending_constraints	) == 0:
         # we're done!
         _snake_case							:	Union[str, Any]			=						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(a_	):
         _snake_case	,      _snake_case	,      _snake_case							:	Any			=						pending_constraint.update(a_	)

         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(a_	)
           _snake_case							:	Optional[Any]			=						None

         if not complete and stepped:
           _snake_case							:	List[Any]			=						pending_constraint

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

           _snake_case							:	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.

             _snake_case							:	List[str]			=						True

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

   return complete, stepped


 def 				UpperCamelCase_     (       self:	Dict,   a_:	int=True	):




   '''simple docstring'''



   _snake_case							:	Dict			=						ConstraintListState(self.constraints	)  # we actually never though self.constraints objects
   # throughout this process. So it's at initialization state.

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

   return new_state








"""simple docstring"""


def       UpperCAmelCase__ (snake_case__							:      int					):
  """simple docstring"""

  if not isinstance(snake_case__	,     snake_case__					) or number < 0:
    raise ValueError("""Input must be a non-negative integer"""					)

  _snake_case							:	Dict			=						0
  while number:
    # This way we arrive at next set bit (next 1) instead of looping
    # through each bit and checking for 1s hence the
    # loop won't run 32 times it will only run the number of `1` times
    number &= number - 1
    count += 1
  return count


if __name__ == "__main__":
     import doctest

     doctest.testmod()


