
"""simple docstring"""







import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


lowerCamelCase__        =		datasets.utils.logging.get_logger(__name__)




@dataclass
class 			A__	(     datasets.BuilderConfig):
		A_						:	Optional[datasets.Features]           =     None
		A_						:	str           =     "utf-8"
		A_						:	Optional[str]           =     None
		A_						:	Optional[str]           =     None
		A_						:	bool           =     True  # deprecated
		A_						:	Optional[int]           =     None  # deprecated
		A_						:	int           =     1_0 << 2_0  # 10MB
		A_						:	Optional[bool]           =     None




class 			A__	(     datasets.ArrowBasedBuilder):
		A_						:	int           =     JsonConfig

		def 							__lowerCamelCase							(				self			):
			if self.config.block_size is not None:
				logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'			)
				__lowerCAmelCase      :						List[str]						      =				self.config.block_size
			if self.config.use_threads is not True:
				logger.warning(
				    'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.'			)
			if self.config.newlines_in_values is not None:
				raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported'			)
			return datasets.DatasetInfo(features=self.config.features			)

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE			):
			if not self.config.data_files:
				raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}"			)
			__lowerCAmelCase      :						Union[str, Any]						      =				dl_manager.download_and_extract(self.config.data_files			)
			if isinstance(lowerCAmelCase__	,		(str, list, tuple)			):
				__lowerCAmelCase      :						Dict						      =				data_files
				if isinstance(lowerCAmelCase__	,		lowerCAmelCase__			):
					__lowerCAmelCase      :						Dict						      =				[files]
				__lowerCAmelCase      :						List[str]						      =				[dl_manager.iter_files(lowerCAmelCase__			) for file in files]
				return [datasets.SplitGenerator(name=datasets.Split.TRAIN	,		gen_kwargs={'files': files}			)]
			__lowerCAmelCase      :						Any						      =				[]
			for split_name, files in data_files.items():
				if isinstance(lowerCAmelCase__	,		lowerCAmelCase__			):
					__lowerCAmelCase      :						Optional[Any]						      =				[files]
				__lowerCAmelCase      :						Optional[int]						      =				[dl_manager.iter_files(lowerCAmelCase__			) for file in files]
				splits.append(datasets.SplitGenerator(name=lowerCAmelCase__	,		gen_kwargs={'files': files}			)			)
			return splits

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE			):
			if self.config.features is not None:
				# adding missing columns
				for column_name in set(self.config.features			) - set(pa_table.column_names			):
					__lowerCAmelCase      :						List[str]						      =				self.config.features.arrow_schema.field(lowerCAmelCase__			).type
					__lowerCAmelCase      :						List[Any]						      =				pa_table.append_column(lowerCAmelCase__	,		pa.array([None] * len(lowerCAmelCase__			)	,		type=lowerCAmelCase__			)			)
				# more expensive cast to support nested structures with keys in a different order
				# allows str <-> int/float or str to Audio for example
				__lowerCAmelCase      :						str						      =				table_cast(lowerCAmelCase__	,		self.config.features.arrow_schema			)
			return pa_table







		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE			):
			for file_idx, file in enumerate(itertools.chain.from_iterable(lowerCAmelCase__			)			):
				# If the file is one json object and if we need to look at the list of items in one specific field
				if self.config.field is not None:
					with open(lowerCAmelCase__	,		encoding=self.config.encoding	,		errors=self.config.encoding_errors			) as f:
						__lowerCAmelCase      :						int						      =				json.load(lowerCAmelCase__			)

					# We keep only the field we are interested in
					__lowerCAmelCase      :						int						      =				dataset[self.config.field]

					# We accept two format: a list of dicts or a dict of lists
					if isinstance(lowerCAmelCase__	,		(list, tuple)			):
						__lowerCAmelCase      :						List[Any]						      =				set().union(*[row.keys() for row in dataset]			)
						__lowerCAmelCase      :						Optional[Any]						      =				{col: [row.get(lowerCAmelCase__			) for row in dataset] for col in keys}
					else:
						__lowerCAmelCase      :						Union[str, Any]						      =				dataset
					__lowerCAmelCase      :						List[Any]						      =				pa.Table.from_pydict(lowerCAmelCase__			)
					yield file_idx, self._cast_table(lowerCAmelCase__			)

				# If the file has one json object per line
				else:
					with open(lowerCAmelCase__	,		'rb'			) as f:
						__lowerCAmelCase      :						Optional[Any]						      =				0
						# Use block_size equal to the chunk size divided by 32 to leverage multithreading
						# Set a default minimum value of 16kB if the chunk size is really small
						__lowerCAmelCase      :						Optional[int]						      =				max(self.config.chunksize // 32	,		16 << 10			)
						__lowerCAmelCase      :						Optional[Any]						      =				(
						    self.config.encoding_errors if self.config.encoding_errors is not None else 'strict'
						)
						while True:
							__lowerCAmelCase      :						int						      =				f.read(self.config.chunksize			)
							if not batch:
								break
							# Finish current line
							try:
								batch += f.readline()
							except (AttributeError, io.UnsupportedOperation):
								batch += readline(lowerCAmelCase__			)
							# PyArrow only accepts utf-8 encoded bytes
							if self.config.encoding != "utf-8":
								__lowerCAmelCase      :						int						      =				batch.decode(self.config.encoding	,		errors=lowerCAmelCase__			).encode('utf-8'			)
							try:
								while True:
									try:
										__lowerCAmelCase      :						Optional[int]						      =				paj.read_json(
										    io.BytesIO(lowerCAmelCase__			)	,		read_options=paj.ReadOptions(block_size=lowerCAmelCase__			)			)
										break
									except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
										if (
										    isinstance(lowerCAmelCase__	,		pa.ArrowInvalid			)
										    and "straddling" not in str(lowerCAmelCase__			)
										    or block_size > len(lowerCAmelCase__			)
										):
											raise
										else:
											# Increase the block size in case it was too small.
											# The block size will be reset for the next file.
											logger.debug(
											    f"Batch of {len(lowerCAmelCase__			)} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}."			)
											block_size *= 2
							except pa.ArrowInvalid as e:
								try:
									with open(
									    lowerCAmelCase__	,		encoding=self.config.encoding	,		errors=self.config.encoding_errors			) as f:
										__lowerCAmelCase      :						str						      =				json.load(lowerCAmelCase__			)
								except json.JSONDecodeError:
									logger.error(f"Failed to read file \'{file}\' with error {type(lowerCAmelCase__			)}: {e}"			)
									raise e
								# If possible, parse the file as a list of json objects and exit the loop
								if isinstance(lowerCAmelCase__	,		lowerCAmelCase__			):  # list is the only sequence type supported in JSON
									try:
										__lowerCAmelCase      :						Optional[Any]						      =				set().union(*[row.keys() for row in dataset]			)
										__lowerCAmelCase      :						Dict						      =				{col: [row.get(lowerCAmelCase__			) for row in dataset] for col in keys}
										__lowerCAmelCase      :						Dict						      =				pa.Table.from_pydict(lowerCAmelCase__			)
									except (pa.ArrowInvalid, AttributeError) as e:
										logger.error(f"Failed to read file \'{file}\' with error {type(lowerCAmelCase__			)}: {e}"			)
										raise ValueError(f"Not able to read records in the JSON file at {file}."			) from None
									yield file_idx, self._cast_table(lowerCAmelCase__			)
									break
								else:
									logger.error(f"Failed to read file \'{file}\' with error {type(lowerCAmelCase__			)}: {e}"			)
									raise ValueError(
									    f"Not able to read records in the JSON file at {file}. "
									    f"You should probably indicate the field of the JSON file containing your records. "
									    f"This JSON file contain the following fields: {str(list(dataset.keys()			)			)}. "
									    f"Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. "			) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
							yield (file_idx, batch_idx), self._cast_table(lowerCAmelCase__			)
							batch_idx += 1

"""simple docstring"""







import argparse
import datetime
def    __lowerCAmelCase    (_UpperCamelCase		):
	__lowerCAmelCase      :						Optional[Any]						      =				{
	    '0': 'Sunday',
	    '1': 'Monday',
	    '2': 'Tuesday',
	    '3': 'Wednesday',
	    '4': 'Thursday',
	    '5': 'Friday',
	    '6': 'Saturday',
	}

	__lowerCAmelCase      :						Optional[Any]						      =				{0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0}

	# Validate
	if not 0 < len(_UpperCamelCase		) < 11:
		raise ValueError('Must be 10 characters long'		)

	# Get month
	__lowerCAmelCase      :						int						      =				int(date_input[0] + date_input[1]		)
	# Validate
	if not 0 < m < 13:
		raise ValueError('Month must be between 1 - 12'		)

	__lowerCAmelCase      :						str						      =				date_input[2]
	# Validate
	if sep_a not in ["-", "/"]:
		raise ValueError('Date separator must be \'-\' or \'/\''		)

	# Get day
	__lowerCAmelCase      :						int						      =				int(date_input[3] + date_input[4]		)
	# Validate
	if not 0 < d < 32:
		raise ValueError('Date must be between 1 - 31'		)

	# Get second separator
	__lowerCAmelCase      :						str						      =				date_input[5]
	# Validate
	if sep_a not in ["-", "/"]:
		raise ValueError('Date separator must be \'-\' or \'/\''		)

	# Get year
	__lowerCAmelCase      :						int						      =				int(date_input[6] + date_input[7] + date_input[8] + date_input[9]		)
	# Arbitrary year range
	if not 45 < y < 8500:
		raise ValueError(
		    'Year out of range. There has to be some sort of limit...right?'		)

	# Get datetime obj for validation
	__lowerCAmelCase      :						Tuple						      =				datetime.date(int(_UpperCamelCase		)	,  int(_UpperCamelCase		)	,  int(_UpperCamelCase		)		)

	# Start math
	if m <= 2:
		__lowerCAmelCase      :						int						      =				y - 1
		__lowerCAmelCase      :						Tuple						      =				m + 12
	# maths var
	__lowerCAmelCase      :						int						      =				int(str(_UpperCamelCase		)[:2]		)
	__lowerCAmelCase      :						int						      =				int(str(_UpperCamelCase		)[2:]		)
	__lowerCAmelCase      :						int						      =				int(2.6 * m - 5.39		)
	__lowerCAmelCase      :						int						      =				int(c / 4		)
	__lowerCAmelCase      :						int						      =				int(k / 4		)
	__lowerCAmelCase      :						int						      =				int(d + k		)
	__lowerCAmelCase      :						int						      =				int(t + u + v + x		)
	__lowerCAmelCase      :						int						      =				int(z - (2 * c)		)
	__lowerCAmelCase      :						int						      =				round(w % 7		)
	# End math

	# Validate math
	if f != convert_datetime_days[dt_ck.weekday()]:
		raise AssertionError('The date was evaluated incorrectly. Contact developer.'		)

	# Response
	__lowerCAmelCase      :						str						      =				F"Your date {date_input}, is a {days[str(_UpperCamelCase		)]}!"
	return response


if __name__ == "__main__":
							import doctest

							doctest.testmod()
							lowerCamelCase__        =		argparse.ArgumentParser(
							    description=(
							        """Find out what day of the week nearly any date is or was. Enter """
							        """date as a string in the mm-dd-yyyy or mm/dd/yyyy format"""
							    )
							)
							parser.add_argument(
							    """date_input""", type=str, help="""Date as a string (mm-dd-yyyy or mm/dd/yyyy)"""
							)
							lowerCamelCase__        =		parser.parse_args()
							zeller(args.date_input)