



"""simple docstring"""






import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil






class 	__snake_case	(     _lowercase):




  def 						SCREAMING_SNAKE_CASE    (			self					:						Dict		):






         """simple docstring"""






         _lowerCamelCase						:    Dict         =			pa.array(TypedSequence([1, 2, 3]		)		)
         self.assertEqual(arr.type						, pa.intaa()		)




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






         """simple docstring"""






         with self.assertRaises(__lowerCAmelCase		):
                _lowerCamelCase						:    Tuple         =			pa.array(TypedSequence([1, 2, 3]		)						, type=pa.intaa()		)




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






         """simple docstring"""






         with self.assertRaises(__lowerCAmelCase		):
                _lowerCamelCase						:    List[str]         =			pa.array(TypedSequence([1, 2, 3]						, try_type=Value('''bool'''		)						, type=Value('''int64'''		)		)		)




  def 						SCREAMING_SNAKE_CASE    (			self					:						str		):






         """simple docstring"""






         _lowerCamelCase						:    Optional[Any]         =			pa.array(TypedSequence([1, 2, 3]						, type=Value('''int32'''		)		)		)
         self.assertEqual(arr.type						, pa.intaa()		)




  def 						SCREAMING_SNAKE_CASE    (			self					:						str		):






         """simple docstring"""






         with self.assertRaises((TypeError, pa.lib.ArrowInvalid)		):
                _lowerCamelCase						:    List[str]         =			pa.array(TypedSequence(['''foo''', '''bar''']						, type=Value('''int64'''		)		)		)




  def 						SCREAMING_SNAKE_CASE    (			self					:						Optional[int]		):






         """simple docstring"""






         _lowerCamelCase						:    str         =			pa.array(TypedSequence([1, 2, 3]						, try_type=Value('''int32'''		)		)		)
         self.assertEqual(arr.type						, pa.intaa()		)




  def 						SCREAMING_SNAKE_CASE    (			self					:						List[str]		):






         """simple docstring"""






         _lowerCamelCase						:    str         =			pa.array(TypedSequence(['''foo''', '''bar''']						, try_type=Value('''int64'''		)		)		)
         self.assertEqual(arr.type						, pa.string()		)




  def 						SCREAMING_SNAKE_CASE    (			self					:						int		):






         """simple docstring"""






         _lowerCamelCase						:    str         =			pa.array(TypedSequence([[[1, 2, 3]]]						, type=ArrayaD((1, 3)						, '''int64'''		)		)		)
         self.assertEqual(arr.type						, ArrayaDExtensionType((1, 3)						, '''int64'''		)		)




  def 						SCREAMING_SNAKE_CASE    (			self					:						Any		):






         """simple docstring"""






         with self.assertRaises((TypeError, pa.lib.ArrowInvalid)		):
                _lowerCamelCase						:    Dict         =			pa.array(TypedSequence(['''foo''', '''bar''']						, type=ArrayaD((1, 3)						, '''int64'''		)		)		)




  def 						SCREAMING_SNAKE_CASE    (			self					:						Dict		):






         """simple docstring"""






         _lowerCamelCase						:    Tuple         =			pa.array(TypedSequence([[[1, 2, 3]]]						, try_type=ArrayaD((1, 3)						, '''int64'''		)		)		)
         self.assertEqual(arr.type						, ArrayaDExtensionType((1, 3)						, '''int64'''		)		)




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






         """simple docstring"""






         _lowerCamelCase						:    Optional[Any]         =			pa.array(TypedSequence(['''foo''', '''bar''']						, try_type=ArrayaD((1, 3)						, '''int64'''		)		)		)
         self.assertEqual(arr.type						, pa.string()		)




  @require_pil
  def 						SCREAMING_SNAKE_CASE    (			self					:						Optional[int]		):






         """simple docstring"""






         import PIL.Image

         _lowerCamelCase						:    Tuple         =			PIL.Image.fromarray(np.arange(1_0						, dtype=np.uinta		).reshape(2						, 5		)		)
         with patch(
             '''datasets.arrow_writer.cast_to_python_objects'''						, side_effect=__lowerCAmelCase		) as mock_cast_to_python_objects:
                _lowerCamelCase						:    Union[str, Any]         =			pa.array(TypedSequence([{'''path''': None, '''bytes''': B'''image_bytes'''}, pil_image]						, type=Image()		)		)
                _lowerCamelCase						:    int         =			mock_cast_to_python_objects.call_args_list[-1]
                self.assertIn('''optimize_list_casting'''						, __lowerCAmelCase		)
                self.assertFalse(kwargs['''optimize_list_casting''']		)






def 	snake_case_  (				A_ :		Tuple,    A_ :		int						):


       '''simple docstring'''





       _lowerCamelCase						:    List[Any]         =			pa.BufferReader(A_						) if isinstance(A_,    pa.Buffer						) else pa.memory_map(A_						)
       _lowerCamelCase						:    Union[str, Any]         =			pa.ipc.open_stream(A_						)
       _lowerCamelCase						:    pa.Table         =			f.read_all()
       assert len(pa_table.to_batches()						) == expected_num_chunks
       assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
       del pa_table






@pytest.mark.parametrize('''writer_batch_size''',    [None, 1, 10]						)
@pytest.mark.parametrize(
    '''fields''',    [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]						)
def 	snake_case_  (				A_ :		Any,    A_ :		Dict						):


       '''simple docstring'''





       _lowerCamelCase						:    List[Any]         =			pa.BufferOutputStream()
       _lowerCamelCase						:    Union[str, Any]         =			pa.schema(A_						) if fields else None
       with ArrowWriter(stream=A_,    schema=A_,    writer_batch_size=A_						) as writer:
              writer.write({'''col_1''': '''foo''', '''col_2''': 1}						)
              writer.write({'''col_1''': '''bar''', '''col_2''': 2}						)
              _lowerCamelCase						:    List[str]         =			writer.finalize()
       assert num_examples == 2
       assert num_bytes > 0
       if not fields:
              _lowerCamelCase						:    int         =			{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
       assert writer._schema == pa.schema(A_,    metadata=writer._schema.metadata						)
       _check_output(output.getvalue(),    expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)






def 	snake_case_  (				):


       '''simple docstring'''





       _lowerCamelCase						:    Any         =			pa.BufferOutputStream()
       _lowerCamelCase						:    List[str]         =			Features({'''labels''': ClassLabel(names=['''neg''', '''pos''']						)}						)
       with ArrowWriter(stream=A_,    features=A_						) as writer:
              writer.write({'''labels''': 0}						)
              writer.write({'''labels''': 1}						)
              _lowerCamelCase						:    Dict         =			writer.finalize()
       assert num_examples == 2
       assert num_bytes > 0
       assert writer._schema == features.arrow_schema
       assert writer._schema.metadata == features.arrow_schema.metadata
       _lowerCamelCase						:    Optional[int]         =			pa.BufferReader(output.getvalue()						)
       _lowerCamelCase						:    Optional[int]         =			pa.ipc.open_stream(A_						)
       _lowerCamelCase						:    pa.Table         =			f.read_all()
       _lowerCamelCase						:    Optional[Any]         =			pa_table.schema
       assert pa_table.num_rows == 2
       assert schema == features.arrow_schema
       assert schema.metadata == features.arrow_schema.metadata
       assert features == Features.from_arrow_schema(A_						)






@pytest.mark.parametrize('''writer_batch_size''',    [None, 1, 10]						)
def 	snake_case_  (				A_ :		List[Any]						):


       '''simple docstring'''





       _lowerCamelCase						:    int         =			pa.BufferOutputStream()
       with ArrowWriter(
           stream=A_,    writer_batch_size=A_,    hash_salt='''split_name''',    check_duplicates=A_,    ) as writer:
              with pytest.raises(A_						):
                     writer.write({'''col_1''': '''foo''', '''col_2''': 1},    key=[1, 2]						)
                     _lowerCamelCase						:    int         =			writer.finalize()






@pytest.mark.parametrize('''writer_batch_size''',    [None, 2, 10]						)
def 	snake_case_  (				A_ :		Optional[int]						):


       '''simple docstring'''





       _lowerCamelCase						:    int         =			pa.BufferOutputStream()
       with ArrowWriter(
           stream=A_,    writer_batch_size=A_,    hash_salt='''split_name''',    check_duplicates=A_,    ) as writer:
              with pytest.raises(A_						):
                     writer.write({'''col_1''': '''foo''', '''col_2''': 1},    key=10						)
                     writer.write({'''col_1''': '''bar''', '''col_2''': 2},    key=10						)
                     _lowerCamelCase						:    Dict         =			writer.finalize()






@pytest.mark.parametrize('''writer_batch_size''',    [None, 2, 10]						)
def 	snake_case_  (				A_ :		List[Any]						):


       '''simple docstring'''





       _lowerCamelCase						:    List[str]         =			pa.BufferOutputStream()
       with ArrowWriter(
           stream=A_,    writer_batch_size=A_,    hash_salt='''split_name''',    check_duplicates=A_,    ) as writer:
              writer.write({'''col_1''': '''foo''', '''col_2''': 1},    key=1						)
              writer.write({'''col_1''': '''bar''', '''col_2''': 2},    key=2						)
              _lowerCamelCase						:    List[Any]         =			writer.finalize()
       assert num_examples == 2
       assert num_bytes > 0
       _check_output(output.getvalue(),    expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)






@pytest.mark.parametrize('''writer_batch_size''',    [None, 1, 10]						)
@pytest.mark.parametrize(
    '''fields''',    [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]						)
def 	snake_case_  (				A_ :		List[str],    A_ :		Optional[int]						):


       '''simple docstring'''





       _lowerCamelCase						:    Optional[int]         =			pa.BufferOutputStream()
       _lowerCamelCase						:    Dict         =			pa.schema(A_						) if fields else None
       with ArrowWriter(stream=A_,    schema=A_,    writer_batch_size=A_						) as writer:
              writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}						)
              writer.write_batch({'''col_1''': [], '''col_2''': []}						)
              _lowerCamelCase						:    List[str]         =			writer.finalize()
       assert num_examples == 2
       assert num_bytes > 0
       if not fields:
              _lowerCamelCase						:    Optional[int]         =			{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
       assert writer._schema == pa.schema(A_,    metadata=writer._schema.metadata						)
       _check_output(output.getvalue(),    expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)






@pytest.mark.parametrize('''writer_batch_size''',    [None, 1, 10]						)
@pytest.mark.parametrize(
    '''fields''',    [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]						)
def 	snake_case_  (				A_ :		Optional[int],    A_ :		List[str]						):


       '''simple docstring'''





       _lowerCamelCase						:    Optional[Any]         =			pa.BufferOutputStream()
       _lowerCamelCase						:    Any         =			pa.schema(A_						) if fields else None
       with ArrowWriter(stream=A_,    schema=A_,    writer_batch_size=A_						) as writer:
              writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}						)						)
              _lowerCamelCase						:    Optional[int]         =			writer.finalize()
       assert num_examples == 2
       assert num_bytes > 0
       if not fields:
              _lowerCamelCase						:    str         =			{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
       assert writer._schema == pa.schema(A_,    metadata=writer._schema.metadata						)
       _check_output(output.getvalue(),    expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)






@pytest.mark.parametrize('''writer_batch_size''',    [None, 1, 10]						)
@pytest.mark.parametrize(
    '''fields''',    [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]						)
def 	snake_case_  (				A_ :		List[str],    A_ :		Optional[int]						):


       '''simple docstring'''





       _lowerCamelCase						:    Union[str, Any]         =			pa.BufferOutputStream()
       _lowerCamelCase						:    Any         =			pa.schema(A_						) if fields else None
       with ArrowWriter(stream=A_,    schema=A_,    writer_batch_size=A_						) as writer:
              writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]}						)						)
              writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]}						)						)
              _lowerCamelCase						:    Union[str, Any]         =			writer.finalize()
       assert num_examples == 2
       assert num_bytes > 0
       if not fields:
              _lowerCamelCase						:    List[str]         =			{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
       assert writer._schema == pa.schema(A_,    metadata=writer._schema.metadata						)
       _check_output(output.getvalue(),    expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)






def 	snake_case_  (				):


       '''simple docstring'''





       with tempfile.TemporaryDirectory() as tmp_dir:
              _lowerCamelCase						:    Optional[Any]         =			{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
              _lowerCamelCase						:    Optional[int]         =			os.path.join(A_,    '''test.arrow'''						)
              with ArrowWriter(path=A_,    schema=pa.schema(A_						)						) as writer:
                     writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}						)
                     _lowerCamelCase						:    int         =			writer.finalize()
              assert num_examples == 2
              assert num_bytes > 0
              assert writer._schema == pa.schema(A_,    metadata=writer._schema.metadata						)
              _check_output(A_,    1						)






def 	snake_case_  (				A_ :		List[Any]						):


       '''simple docstring'''





       if pa.types.is_list(A_						):
              return get_base_dtype(arr_type.value_type						)
       else:
              return arr_type






def 	snake_case_  (				A_ :		Optional[Any],    A_ :		List[Any]						):


       '''simple docstring'''





       if isinstance(lst[0],    A_						):
              change_first_primitive_element_in_list(lst[0],    A_						)
       else:
              _lowerCamelCase						:    Any         =			value






@pytest.mark.parametrize('''optimized_int_type, expected_dtype''',    [(None, pa.intaa()), (Value('''int32'''						), pa.intaa())]						)
@pytest.mark.parametrize('''sequence''',    [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]						)
def 	snake_case_  (				A_ :		str,    A_ :		str,    A_ :		int						):


       '''simple docstring'''





       _lowerCamelCase						:    List[Any]         =			pa.array(TypedSequence(A_,    optimized_int_type=A_						)						)
       assert get_base_dtype(arr.type						) == expected_dtype






@pytest.mark.parametrize(
    '''col, expected_dtype''',    [
        ('''attention_mask''', pa.inta()),
        ('''special_tokens_mask''', pa.inta()),
        ('''token_type_ids''', pa.inta()),
        ('''input_ids''', pa.intaa()),
        ('''other''', pa.intaa()),
    ],    )
@pytest.mark.parametrize('''sequence''',    [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]						)
def 	snake_case_  (				A_ :		Any,    A_ :		str,    A_ :		Tuple						):


       '''simple docstring'''





       _lowerCamelCase						:    Dict         =			pa.array(OptimizedTypedSequence(A_,    col=A_						)						)
       assert get_base_dtype(arr.type						) == expected_dtype

       # not in range
       if col != "other":
              # avoids errors due to in-place modifications
              _lowerCamelCase						:    Optional[Any]         =			copy.deepcopy(A_						)
              _lowerCamelCase						:    Dict         =			np.iinfo(expected_dtype.to_pandas_dtype()						).max + 1
              change_first_primitive_element_in_list(A_,    A_						)
              _lowerCamelCase						:    Optional[Any]         =			pa.array(OptimizedTypedSequence(A_,    col=A_						)						)
              assert get_base_dtype(arr.type						) == pa.intaa()






@pytest.mark.parametrize('''raise_exception''',    [False, True]						)
def 	snake_case_  (				A_ :		Any,    A_ :		str						):


       '''simple docstring'''





       _lowerCamelCase						:    Union[str, Any]         =			str(tmp_path / '''dataset-train.arrow'''						)
       try:
              with ArrowWriter(path=A_						) as writer:
                     if raise_exception:
                            raise pa.lib.ArrowInvalid()
                     else:
                            writer.stream.close()
       except pa.lib.ArrowInvalid:
              pass
       finally:
              assert writer.stream.closed






def 	snake_case_  (				A_ :		int						):


       '''simple docstring'''





       _lowerCamelCase						:    Tuple         =			'''mock://dataset-train.arrow'''
       with ArrowWriter(path=A_,    storage_options=mockfs.storage_options						) as writer:
              assert isinstance(writer._fs,    type(A_						)						)
              assert writer._fs.storage_options == mockfs.storage_options
              writer.write({'''col_1''': '''foo''', '''col_2''': 1}						)
              writer.write({'''col_1''': '''bar''', '''col_2''': 2}						)
              _lowerCamelCase						:    Tuple         =			writer.finalize()
       assert num_examples == 2
       assert num_bytes > 0
       assert mockfs.exists(A_						)






def 	snake_case_  (				):


       '''simple docstring'''





       _lowerCamelCase						:    Dict         =			pa.BufferOutputStream()
       with ParquetWriter(stream=A_						) as writer:
              writer.write({'''col_1''': '''foo''', '''col_2''': 1}						)
              writer.write({'''col_1''': '''bar''', '''col_2''': 2}						)
              _lowerCamelCase						:    Optional[Any]         =			writer.finalize()
       assert num_examples == 2
       assert num_bytes > 0
       _lowerCamelCase						:    Any         =			pa.BufferReader(output.getvalue()						)
       _lowerCamelCase						:    pa.Table         =			pq.read_table(A_						)
       assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}






@require_pil
@pytest.mark.parametrize('''embed_local_files''',    [False, True]						)
def 	snake_case_  (				A_ :		Optional[int],    A_ :		Optional[int]						):


       '''simple docstring'''





       import PIL.Image

       _lowerCamelCase						:    Optional[Any]         =			str(tmp_path / '''test_image_rgb.jpg'''						)
       PIL.Image.fromarray(np.zeros((5, 5),    dtype=np.uinta						)						).save(A_,    format='''png'''						)
       _lowerCamelCase						:    Optional[int]         =			pa.BufferOutputStream()
       with ParquetWriter(
           stream=A_,    features=Features({'''image''': Image()}						),    embed_local_files=A_						) as writer:
              writer.write({'''image''': image_path}						)
              writer.finalize()
       _lowerCamelCase						:    Optional[Any]         =			pa.BufferReader(output.getvalue()						)
       _lowerCamelCase						:    pa.Table         =			pq.read_table(A_						)
       _lowerCamelCase						:    str         =			pa_table.to_pydict()
       if embed_local_files:
              assert isinstance(out['''image'''][0]['''path'''],    A_						)
              with open(A_,    '''rb'''						) as f:
                     assert out["image"][0]["bytes"] == f.read()
       else:
              assert out["image"][0]["path"] == image_path
              assert out["image"][0]["bytes"] is None







def 	snake_case_  (				):


       '''simple docstring'''





       _lowerCamelCase						:    int         =			pa.schema([pa.field('''col_1''',    pa.string(),    nullable=A_						)]						)
       _lowerCamelCase						:    Optional[int]         =			pa.BufferOutputStream()
       with ArrowWriter(stream=A_						) as writer:
              writer._build_writer(inferred_schema=A_						)
              assert writer._schema == pa.schema([pa.field('''col_1''',    pa.string()						)]						)







"""simple docstring"""






def 	snake_case_  (				A_ :		list						):


       '''simple docstring'''





       _lowerCamelCase						:    Union[str, Any]         =			len(A_						)
       for i in range(1,    A_						):
              _lowerCamelCase						:    Tuple         =			collection[i]
              _lowerCamelCase						:    Dict         =			0
              _lowerCamelCase						:    Any         =			i - 1

              while low <= high:
                     _lowerCamelCase						:    Optional[int]         =			(low + high) // 2
                     if val < collection[mid]:
                            _lowerCamelCase						:    List[str]         =			mid - 1
                     else:
                            _lowerCamelCase						:    Dict         =			mid + 1
              for j in range(A_,    A_,    -1						):
                     _lowerCamelCase						:    Optional[int]         =			collection[j - 1]
              _lowerCamelCase						:    Tuple         =			val
       return collection


if __name__ == "__main__":
   lowerCAmelCase__      =    input('''Enter numbers separated by a comma:\n''').strip()
   lowerCAmelCase__      =    [int(item) for item in user_input.split(''',''')]
   print(binary_insertion_sort(unsorted))


