


import io
import json

import fsspec
import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.json import JsonDatasetReader, JsonDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases


def        _UpperCamelCase							(      lowercase__    ,       lowercase__      ):
						assert isinstance(lowercase__    ,       lowercase__      )
						assert dataset.num_rows == 4
						assert dataset.num_columns == 3
						assert dataset.column_names == ["col_1", "col_2", "col_3"]
						for feature, expected_dtype in expected_features.items():
												assert dataset.features[feature].dtype == expected_dtype


@pytest.mark.parametrize('''keep_in_memory'''    ,       [False, True]      )
def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     Dict					=		tmp_path / '''cache'''
						__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
												__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		JsonDatasetReader(lowercase__    ,       cache_dir=lowercase__    ,       keep_in_memory=lowercase__      ).read()
						_check_json_dataset(lowercase__    ,       lowercase__      )


@pytest.mark.parametrize(
    '''features'''    ,       [
        None,
        {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
        {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
        {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
        {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
    ]    ,       )
def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     List[Any]					=		tmp_path / '''cache'''
						__SCREAMING_SNAKE_CASE						:     str					=		{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		features.copy() if features else default_expected_features
						__SCREAMING_SNAKE_CASE						:     Any					=		(
						    Features({feature: Value(lowercase__      ) for feature, dtype in features.items()}      ) if features is not None else None
						)
						__SCREAMING_SNAKE_CASE						:     str					=		JsonDatasetReader(lowercase__    ,       features=lowercase__    ,       cache_dir=lowercase__      ).read()
						_check_json_dataset(lowercase__    ,       lowercase__      )


@pytest.mark.parametrize(
    '''features'''    ,       [
        None,
        {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''},
    ]    ,       )
def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     List[Any]					=		tmp_path / '''cache'''
						__SCREAMING_SNAKE_CASE						:     Dict					=		{'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}
						__SCREAMING_SNAKE_CASE						:     Tuple					=		features.copy() if features else default_expected_features
						__SCREAMING_SNAKE_CASE						:     Dict					=		(
						    Features({feature: Value(lowercase__      ) for feature, dtype in features.items()}      ) if features is not None else None
						)
						__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		JsonDatasetReader(lowercase__    ,       features=lowercase__    ,       cache_dir=lowercase__      ).read()
						assert isinstance(lowercase__    ,       lowercase__      )
						assert dataset.num_rows == 2
						assert dataset.num_columns == 3
						assert dataset.column_names == ["col_3", "col_1", "col_2"]
						for feature, expected_dtype in expected_features.items():
												assert dataset.features[feature].dtype == expected_dtype


def        _UpperCamelCase							(      lowercase__    ,       lowercase__      ):
						# jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"}
						__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		{'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''}
						__SCREAMING_SNAKE_CASE						:     List[Any]					=		features.copy()
						__SCREAMING_SNAKE_CASE						:     List[Any]					=		(
						    Features({feature: Value(lowercase__      ) for feature, dtype in features.items()}      ) if features is not None else None
						)
						__SCREAMING_SNAKE_CASE						:     Dict					=		tmp_path / '''cache'''
						__SCREAMING_SNAKE_CASE						:     Dict					=		JsonDatasetReader(lowercase__    ,       features=lowercase__    ,       cache_dir=lowercase__      ).read()
						assert isinstance(lowercase__    ,       lowercase__      )
						assert dataset.num_rows == 2
						assert dataset.num_columns == 3
						assert dataset.column_names == ["col_2", "col_3", "col_1"]
						for feature, expected_dtype in expected_features.items():
												assert dataset.features[feature].dtype == expected_dtype


@pytest.mark.parametrize('''split'''    ,       [None, NamedSplit('''train'''      ), '''train''', '''test''']      )
def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     Dict					=		tmp_path / '''cache'''
						__SCREAMING_SNAKE_CASE						:     Dict					=		{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						__SCREAMING_SNAKE_CASE						:     List[str]					=		JsonDatasetReader(lowercase__    ,       cache_dir=lowercase__    ,       split=lowercase__      ).read()
						_check_json_dataset(lowercase__    ,       lowercase__      )
						assert dataset.split == split if split else "train"


@pytest.mark.parametrize('''path_type'''    ,       [str, list]      )
def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__      ):
						if issubclass(lowercase__    ,       lowercase__      ):
												__SCREAMING_SNAKE_CASE						:     Dict					=		jsonl_path
						elif issubclass(lowercase__    ,       lowercase__      ):
												__SCREAMING_SNAKE_CASE						:     int					=		[jsonl_path]
						__SCREAMING_SNAKE_CASE						:     int					=		tmp_path / '''cache'''
						__SCREAMING_SNAKE_CASE						:     Any					=		{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						__SCREAMING_SNAKE_CASE						:     List[Any]					=		JsonDatasetReader(lowercase__    ,       cache_dir=lowercase__      ).read()
						_check_json_dataset(lowercase__    ,       lowercase__      )


def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__=("train",)      ):
						assert isinstance(lowercase__    ,       lowercase__      )
						for split in splits:
												__SCREAMING_SNAKE_CASE						:     Optional[int]					=		dataset_dict[split]
												assert dataset.num_rows == 4
												assert dataset.num_columns == 3
												assert dataset.column_names == ["col_1", "col_2", "col_3"]
												for feature, expected_dtype in expected_features.items():
																		assert dataset.features[feature].dtype == expected_dtype


@pytest.mark.parametrize('''keep_in_memory'''    ,       [False, True]      )
def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     Dict					=		tmp_path / '''cache'''
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
												__SCREAMING_SNAKE_CASE						:     Dict					=		JsonDatasetReader({'''train''': jsonl_path}    ,       cache_dir=lowercase__    ,       keep_in_memory=lowercase__      ).read()
						_check_json_datasetdict(lowercase__    ,       lowercase__      )


@pytest.mark.parametrize(
    '''features'''    ,       [
        None,
        {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
        {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
        {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
        {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
    ]    ,       )
def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		tmp_path / '''cache'''
						__SCREAMING_SNAKE_CASE						:     List[Any]					=		{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		features.copy() if features else default_expected_features
						__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		(
						    Features({feature: Value(lowercase__      ) for feature, dtype in features.items()}      ) if features is not None else None
						)
						__SCREAMING_SNAKE_CASE						:     List[Any]					=		JsonDatasetReader({'''train''': jsonl_path}    ,       features=lowercase__    ,       cache_dir=lowercase__      ).read()
						_check_json_datasetdict(lowercase__    ,       lowercase__      )


@pytest.mark.parametrize('''split'''    ,       [None, NamedSplit('''train'''      ), '''train''', '''test''']      )
def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__      ):
						if split:
												__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		{split: jsonl_path}
						else:
												__SCREAMING_SNAKE_CASE						:     str					=		'''train'''
												__SCREAMING_SNAKE_CASE						:     List[str]					=		{'''train''': jsonl_path, '''test''': jsonl_path}
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		tmp_path / '''cache'''
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						__SCREAMING_SNAKE_CASE						:     Dict					=		JsonDatasetReader(lowercase__    ,       cache_dir=lowercase__      ).read()
						_check_json_datasetdict(lowercase__    ,       lowercase__    ,       splits=list(path.keys()      )      )
						assert all(dataset[split].split == split for split in path.keys()      )


def        _UpperCamelCase							(      lowercase__      ):
						return json.load(lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						return [json.loads(lowercase__      ) for line in buffer]
class        _lowercase      :






				'''simple docstring'''



				@pytest.mark.parametrize('''lines, load_json_function'''			,			[(True, load_json_lines), (False, load_json)]	)
				def 		__magic_name__(       self			:str			,			lowerCAmelCase__			:Dict			,			lowerCAmelCase__			:List[Any]			,			lowerCAmelCase__			:Any	)		->			Optional[Any]:
										with io.BytesIO() as buffer:
																JsonDatasetWriter(lowerCAmelCase__			,			lowerCAmelCase__			,			lines=lowerCAmelCase__	).write()
																buffer.seek(0	)
																__SCREAMING_SNAKE_CASE						:     Tuple					=		load_json_function(lowerCAmelCase__	)
										assert isinstance(lowerCAmelCase__			,			lowerCAmelCase__	)
										assert isinstance(exported_content[0]			,			lowerCAmelCase__	)
										assert len(lowerCAmelCase__	) == 10


				@pytest.mark.parametrize(
				    '''orient, container, keys, len_at'''			,			[
				        ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None),
				        ('''split''', dict, {'''columns''', '''data'''}, '''data'''),
				        ('''index''', dict, set('''0123456789'''	), None),
				        ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''),
				        ('''values''', list, None, None),
				        ('''table''', dict, {'''schema''', '''data'''}, '''data'''),
				    ]			,			)
				def 		__magic_name__(       self			:Optional[int]			,			lowerCAmelCase__			:List[Any]			,			lowerCAmelCase__			:Union[str, Any]			,			lowerCAmelCase__			:Tuple			,			lowerCAmelCase__			:Union[str, Any]			,			lowerCAmelCase__			:List[Any]	)		->			Optional[Any]:
										with io.BytesIO() as buffer:
																JsonDatasetWriter(lowerCAmelCase__			,			lowerCAmelCase__			,			lines=lowerCAmelCase__			,			orient=lowerCAmelCase__	).write()
																buffer.seek(0	)
																__SCREAMING_SNAKE_CASE						:     List[Any]					=		load_json(lowerCAmelCase__	)
										assert isinstance(lowerCAmelCase__			,			lowerCAmelCase__	)
										if keys:
																if container is dict:
																						assert exported_content.keys() == keys
																else:
																						assert exported_content[0].keys() == keys
										else:
																assert not hasattr(lowerCAmelCase__			,			'''keys'''	) and not hasattr(exported_content[0]			,			'''keys'''	)
										if len_at:
																assert len(exported_content[len_at]	) == 10
										else:
																assert len(lowerCAmelCase__	) == 10


				@pytest.mark.parametrize('''lines, load_json_function'''			,			[(True, load_json_lines), (False, load_json)]	)
				def 		__magic_name__(       self			:Optional[Any]			,			lowerCAmelCase__			:str			,			lowerCAmelCase__			:Any			,			lowerCAmelCase__			:Union[str, Any]	)		->			Dict:
										with io.BytesIO() as buffer:
																JsonDatasetWriter(lowerCAmelCase__			,			lowerCAmelCase__			,			lines=lowerCAmelCase__			,			num_proc=2	).write()
																buffer.seek(0	)
																__SCREAMING_SNAKE_CASE						:     Tuple					=		load_json_function(lowerCAmelCase__	)
										assert isinstance(lowerCAmelCase__			,			lowerCAmelCase__	)
										assert isinstance(exported_content[0]			,			lowerCAmelCase__	)
										assert len(lowerCAmelCase__	) == 10


				@pytest.mark.parametrize(
				    '''orient, container, keys, len_at'''			,			[
				        ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None),
				        ('''split''', dict, {'''columns''', '''data'''}, '''data'''),
				        ('''index''', dict, set('''0123456789'''	), None),
				        ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''),
				        ('''values''', list, None, None),
				        ('''table''', dict, {'''schema''', '''data'''}, '''data'''),
				    ]			,			)
				def 		__magic_name__(       self			:Any			,			lowerCAmelCase__			:List[Any]			,			lowerCAmelCase__			:Union[str, Any]			,			lowerCAmelCase__			:Tuple			,			lowerCAmelCase__			:Optional[Any]			,			lowerCAmelCase__			:Optional[Any]	)		->			Optional[Any]:
										with io.BytesIO() as buffer:
																JsonDatasetWriter(lowerCAmelCase__			,			lowerCAmelCase__			,			lines=lowerCAmelCase__			,			orient=lowerCAmelCase__			,			num_proc=2	).write()
																buffer.seek(0	)
																__SCREAMING_SNAKE_CASE						:     Tuple					=		load_json(lowerCAmelCase__	)
										assert isinstance(lowerCAmelCase__			,			lowerCAmelCase__	)
										if keys:
																if container is dict:
																						assert exported_content.keys() == keys
																else:
																						assert exported_content[0].keys() == keys
										else:
																assert not hasattr(lowerCAmelCase__			,			'''keys'''	) and not hasattr(exported_content[0]			,			'''keys'''	)
										if len_at:
																assert len(exported_content[len_at]	) == 10
										else:
																assert len(lowerCAmelCase__	) == 10


				def 		__magic_name__(       self			:Dict			,			lowerCAmelCase__			:Optional[Any]	)		->			int:
										with pytest.raises(lowerCAmelCase__	):
																with io.BytesIO() as buffer:
																						JsonDatasetWriter(lowerCAmelCase__			,			lowerCAmelCase__			,			num_proc=0	)



				@pytest.mark.parametrize('''compression, extension'''			,			[('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')]	)
				def 		__magic_name__(       self			:Any			,			lowerCAmelCase__			:Dict			,			lowerCAmelCase__			:int			,			lowerCAmelCase__			:List[str]			,			lowerCAmelCase__			:int			,			lowerCAmelCase__			:Optional[Any]	)		->			int:
										__SCREAMING_SNAKE_CASE						:     Tuple					=		tmp_path_factory.mktemp('''data'''	) / f'''test.json.{extension}'''
										__SCREAMING_SNAKE_CASE						:     Dict					=		str(shared_datadir / f'''test_file.json.{extension}'''	)
										JsonDatasetWriter(lowerCAmelCase__			,			lowerCAmelCase__			,			compression=lowerCAmelCase__	).write()

										with fsspec.open(lowerCAmelCase__			,			'''rb'''			,			compression='''infer'''	) as f:
																__SCREAMING_SNAKE_CASE						:     Dict					=		f.read()
										with fsspec.open(lowerCAmelCase__			,			'''rb'''			,			compression='''infer'''	) as f:
																__SCREAMING_SNAKE_CASE						:     str					=		f.read()
										assert exported_content == original_content


import string

# frequency taken from https://en.wikipedia.org/wiki/Letter_frequency
__lowerCAmelCase			:     Optional[int]           =   {
    'E': 12.70,
    'T': 9.06,
    'A': 8.17,
    'O': 7.51,
    'I': 6.97,
    'N': 6.75,
    'S': 6.33,
    'H': 6.09,
    'R': 5.99,
    'D': 4.25,
    'L': 4.03,
    'C': 2.78,
    'U': 2.76,
    'M': 2.41,
    'W': 2.36,
    'F': 2.23,
    'G': 2.02,
    'Y': 1.97,
    'P': 1.93,
    'B': 1.29,
    'V': 0.98,
    'K': 0.77,
    'J': 0.15,
    'X': 0.15,
    'Q': 0.10,
    'Z': 0.07,
}
__lowerCAmelCase			:     Optional[Any]           =   'ETAOINSHRDLCUMWFGYPBVKJXQZ'
__lowerCAmelCase			:     Optional[Any]           =   'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def a__    (       A_					):






  '''simple docstring'''





  __magic_name__				     =       {letter: 0 for letter in string.ascii_uppercase}
  for letter in message.upper():
    if letter in LETTERS:
      letter_count[letter] += 1

  return letter_count

def a__    (       A_					):






  '''simple docstring'''





  return x[0]

def a__    (       A_					):






  '''simple docstring'''





  __magic_name__				     =       get_letter_count(A_					)
  __magic_name__				     =       {
      freq: [] for letter, freq in letter_to_freq.items()
  }
  for letter in LETTERS:
    freq_to_letter[letter_to_freq[letter]].append(A_					)

  __magic_name__				     =       {}

  for freq in freq_to_letter:
    freq_to_letter[freq].sort(key=ETAOIN.find,     reverse=A_					)
    __magic_name__				     =       """""".join(freq_to_letter[freq]					)

  __magic_name__				     =       list(freq_to_letter_str.items()					)
  freq_pairs.sort(key=A_,     reverse=A_					)

  __magic_name__				     =       [freq_pair[1] for freq_pair in freq_pairs]

  return "".join(A_					)

def a__    (       A_					):






  '''simple docstring'''





  __magic_name__				     =       get_frequency_order(A_					)
  __magic_name__				     =       0
  for common_letter in ETAOIN[:6]:
    if common_letter in freq_order[:6]:
      match_score += 1

  for uncommon_letter in ETAOIN[-6:]:
    if uncommon_letter in freq_order[-6:]:
      match_score += 1

  return match_score


if __name__ == "__main__":
    import doctest

    doctest.testmod()

