

'''simple docstring'''






import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


if TYPE_CHECKING:
      import sqlitea

      import sqlalchemy


snake_case_					  =	datasets.utils.logging.get_logger(__name__)
@dataclass
class      SCREAMING_SNAKE_CASE__      (    datasets.BuilderConfig				):
    _A         =							None
    _A         =							None
    _A         =							None
    _A         =							True
    _A         =							None
    _A         =							None
    _A         =							None
    _A         =							10_000
    _A         =							None




    def   __lowerCamelCase				( self      ):






          """simple docstring"""






          if self.sql is None:
                raise ValueError("sql must be specified"      )
          if self.con is None:
                raise ValueError("con must be specified"      )




    def   __lowerCamelCase				( self    ,					lowercase__    ,					lowercase__ = None    ,					):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_				:      Optional[int]					=	config_kwargs.copy()
          # We need to stringify the Selectable object to make its hash deterministic

          # The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
          SCREAMING_SNAKE_CASE_				:      Any					=	config_kwargs["sql"]
          if not isinstance(lowercase__    ,					lowercase__      ):
                if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                      import sqlalchemy

                      if isinstance(lowercase__    ,					sqlalchemy.sql.Selectable      ):
                            SCREAMING_SNAKE_CASE_				:      Any					=	sqlalchemy.create_engine(config_kwargs["con"].split("://"      )[0] + "://"      )
                            SCREAMING_SNAKE_CASE_				:      Optional[Any]					=	str(sql.compile(dialect=engine.dialect      )      )
                            SCREAMING_SNAKE_CASE_				:      Tuple					=	sql_str
                      else:
                            raise TypeError(
                                F"Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(lowercase__      )}: {sql}"      )
                else:
                      raise TypeError(
                          F"Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(lowercase__      )}: {sql}"      )
          SCREAMING_SNAKE_CASE_				:      List[str]					=	config_kwargs["con"]
          if not isinstance(lowercase__    ,					lowercase__      ):
                SCREAMING_SNAKE_CASE_				:      List[str]					=	id(lowercase__      )
                logger.info(
                    F"SQL connection 'con' of type {type(lowercase__      )} couldn't be hashed properly. To enable hashing, specify 'con' as URI string instead."      )

          return super().create_config_id(lowercase__    ,					custom_features=lowercase__      )







    @property
    def   __lowerCamelCase				( self      ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_				:      str					=	{
              "index_col": self.index_col,
              "columns": self.columns,
              "params": self.params,
              "coerce_float": self.coerce_float,
              "parse_dates": self.parse_dates,
          }
          return pd_read_sql_kwargs






class      SCREAMING_SNAKE_CASE__      (    datasets.ArrowBasedBuilder				):
    _A         =							SqlConfig




    def   __lowerCamelCase				( self      ):






          """simple docstring"""






          return datasets.DatasetInfo(features=self.config.features      )




    def   __lowerCamelCase				( self    ,					lowercase__      ):






          """simple docstring"""






          return [datasets.SplitGenerator(name=datasets.Split.TRAIN    ,					gen_kwargs={}      )]




    def   __lowerCamelCase				( self    ,					lowercase__      ):






          """simple docstring"""






          if self.config.features is not None:
                SCREAMING_SNAKE_CASE_				:      Tuple					=	self.config.features.arrow_schema
                if all(not require_storage_cast(lowercase__      ) for feature in self.config.features.values()      ):
                      # cheaper cast
                      SCREAMING_SNAKE_CASE_				:      Optional[int]					=	pa.Table.from_arrays([pa_table[field.name] for field in schema]    ,					schema=lowercase__      )
                else:
                      # more expensive cast; allows str <-> int/float or str to Audio for example
                      SCREAMING_SNAKE_CASE_				:      Tuple					=	table_cast(lowercase__    ,					lowercase__      )
          return pa_table







    def   __lowerCamelCase				( self      ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_				:      Optional[Any]					=	self.config.chunksize
          SCREAMING_SNAKE_CASE_				:      Dict					=	pd.read_sql(
              self.config.sql    ,					self.config.con    ,					chunksize=lowercase__    ,					**self.config.pd_read_sql_kwargs      )
          SCREAMING_SNAKE_CASE_				:      List[str]					=	[sql_reader] if chunksize is None else sql_reader
          for chunk_idx, df in enumerate(lowercase__      ):
                SCREAMING_SNAKE_CASE_				:      Tuple					=	pa.Table.from_pandas(lowercase__      )
                yield chunk_idx, self._cast_table(lowercase__      )




'''simple docstring'''






from __future__ import annotations

from PIL import Image

# Define the first generation of cells
# fmt: off
snake_case_					  =	[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]


def  __lowerCamelCase      (				SCREAMING_SNAKE_CASE_					:     int   )							->       list[int]:
      """simple docstring"""

      return [int(SCREAMING_SNAKE_CASE_   ) for c in F"{ruleset:08}"[:8]]


def  __lowerCamelCase      (				SCREAMING_SNAKE_CASE_					:     list[list[int]]  ,  SCREAMING_SNAKE_CASE_					:     list[int]  ,  SCREAMING_SNAKE_CASE_					:     int   )							->       list[int]:
      """simple docstring"""

      SCREAMING_SNAKE_CASE_				:      Optional[Any]					=	len(cells[0]   )  # 31
      SCREAMING_SNAKE_CASE_				:      Dict					=	[]
      for i in range(SCREAMING_SNAKE_CASE_   ):
            # Get the neighbors of each cell
            # Handle neighbours outside bounds by using 0 as their value
            SCREAMING_SNAKE_CASE_				:      Any					=	0 if i == 0 else cells[time][i - 1]
            SCREAMING_SNAKE_CASE_				:      Dict					=	0 if i == population - 1 else cells[time][i + 1]
            # Define a new cell and add it to the new generation
            SCREAMING_SNAKE_CASE_				:      List[Any]					=	7 - int(F"{left_neighbor}{cells[time][i]}{right_neighbor}"  ,  2   )
            next_generation.append(rule[situation]   )
      return next_generation


def  __lowerCamelCase      (				SCREAMING_SNAKE_CASE_					:     list[list[int]]   )							->       Image.Image:
      """simple docstring"""

      SCREAMING_SNAKE_CASE_				:      Tuple					=	Image.new("RGB"  ,  (len(cells[0]   ), len(SCREAMING_SNAKE_CASE_   ))   )
      SCREAMING_SNAKE_CASE_				:      Optional[int]					=	img.load()
      # Generates image
      for w in range(img.width   ):
            for h in range(img.height   ):
                  SCREAMING_SNAKE_CASE_				:      List[Any]					=	2_5_5 - int(2_5_5 * cells[h][w]   )
                  SCREAMING_SNAKE_CASE_				:      Optional[int]					=	(color, color, color)
      return img


if __name__ == "__main__":
      snake_case_					  =	bin(int(input('Rule:\n').strip()))[2:]
      snake_case_					  =	format_ruleset(int(rule_num))
      for time in range(1_6):
            CELLS.append(new_generation(CELLS, rule, time))
      snake_case_					  =	generate_image(CELLS)
      # Uncomment to save the image
      # img.save(f"rule_{rule_num}.png")
      img.show()

