






'''simple docstring'''





#
# Sort large text files in a minimum amount of memory
#
import argparse
import os





class 		SCREAMING_SNAKE_CASE__   :
		_UpperCAmelCase         ='''block_{0}.dat'''



		def __init__(    self:    List[Any]				,   a:    Tuple)  ->Optional[Any]:






								'''simple docstring'''


								a_				     =   filename
								a_				     =   []



		def _lowerCAmelCase     (    self:    str				,   a:    Optional[int]				,   a:    int)  ->List[str]:






								'''simple docstring'''


								a_				     =   self.BLOCK_FILENAME_FORMAT.format(a)
								with open(a				,   "w") as file:
														file.write(a)
								self.block_filenames.append(a)



		def _lowerCAmelCase     (    self:    str)  ->List[Any]:






								'''simple docstring'''


								return self.block_filenames



		def _lowerCAmelCase     (    self:    Optional[Any]				,   a:    Optional[int]				,   a:    int=None)  ->Tuple:






								'''simple docstring'''


								a_				     =   0
								with open(self.filename) as file:
														while True:
																				a_				     =   file.readlines(a)

																				if lines == []:
																										break

																				if sort_key is None:
																										lines.sort()
																				else:
																										lines.sort(key=a)

																				self.write_block("".join(a)				,   a)
																				i += 1




		def _lowerCAmelCase     (    self:    int)  ->int:






								'''simple docstring'''


								map(os.remove				,   self.block_filenames)





class 		SCREAMING_SNAKE_CASE__   :



		def _lowerCAmelCase     (    self:    str				,   a:    Union[str, Any])  ->Dict:






								'''simple docstring'''


								a_				     =   -1
								a_				     =   None

								for i in range(len(a)):
														if min_str is None or choices[i] < min_str:
																				a_				     =   i

								return min_index





class 		SCREAMING_SNAKE_CASE__   :



		def __init__(    self:    List[str]				,   a:    int)  ->int:






								'''simple docstring'''


								a_				     =   files
								a_				     =   set()
								a_				     =   len(a)
								a_				     =   {i: None for i in range(self.num_buffers)}



		def _lowerCAmelCase     (    self:    Optional[Any])  ->Tuple:






								'''simple docstring'''


								return {
								    i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty
								}



		def _lowerCAmelCase     (    self:    Tuple)  ->int:






								'''simple docstring'''


								for i in range(self.num_buffers):
														if self.buffers[i] is None and i not in self.empty:
																				a_				     =   self.files[i].readline()

																				if self.buffers[i] == "":
																										self.empty.add(a)
																										self.files[i].close()

								if len(self.empty) == self.num_buffers:
														return False

								return True




		def _lowerCAmelCase     (    self:    Tuple				,   a:    Tuple)  ->Optional[int]:






								'''simple docstring'''


								a_				     =   self.buffers[index]
								a_				     =   None

								return value





class 		SCREAMING_SNAKE_CASE__   :



		def __init__(    self:    Union[str, Any]				,   a:    List[Any])  ->Tuple:






								'''simple docstring'''


								a_				     =   merge_strategy



		def _lowerCAmelCase     (    self:    str				,   a:    str				,   a:    Optional[int]				,   a:    Dict)  ->List[str]:






								'''simple docstring'''


								a_				     =   FilesArray(self.get_file_handles(a				,   a))
								with open(a				,   "w"				,   a) as outfile:
														while buffers.refresh():
																				a_				     =   self.merge_strategy.select(buffers.get_dict())
																				outfile.write(buffers.unshift(a))




		def _lowerCAmelCase     (    self:    Optional[Any]				,   a:    str				,   a:    str)  ->List[Any]:






								'''simple docstring'''


								a_				     =   {}

								for i in range(len(a)):
														a_				     =   open(filenames[i]				,   "r"				,   a)  # noqa: UP015

								return files





class 		SCREAMING_SNAKE_CASE__   :



		def __init__(    self:    List[str]				,   a:    Tuple)  ->Union[str, Any]:






								'''simple docstring'''


								a_				     =   block_size



		def _lowerCAmelCase     (    self:    int				,   a:    List[str]				,   a:    Optional[Any]=None)  ->str:






								'''simple docstring'''


								a_				     =   self.get_number_blocks(a				,   self.block_size)
								a_				     =   FileSplitter(a)
								splitter.split(self.block_size				,   a)

								a_				     =   FileMerger(NWayMerge())
								a_				     =   self.block_size / (num_blocks + 1)
								merger.merge(splitter.get_block_filenames()				,   filename + ".out"				,   a)

								splitter.cleanup()




		def _lowerCAmelCase     (    self:    Any				,   a:    Optional[int]				,   a:    Tuple)  ->str:






								'''simple docstring'''


								return (os.stat(a).st_size / block_size) + 1





def 			__UpperCAmelCase				(lowercase__				)		->				Optional[int]:

						'''simple docstring'''


						if string[-1].lower() == "k":
												return int(string[:-1]				) * 1024
						elif string[-1].lower() == "m":
												return int(string[:-1]				) * 1024 * 1024
						elif string[-1].lower() == "g":
												return int(string[:-1]				) * 1024 * 1024 * 1024
						else:
												return int(lowercase__				)



def 			__UpperCAmelCase				()		->				List[Any]:

						'''simple docstring'''


						a_				     =   argparse.ArgumentParser()
						parser.add_argument(
						    "-m"	,"--mem"	,help="amount of memory to use for sorting"	,default="100M"				)
						parser.add_argument(
						    "filename"	,metavar="<filename>"	,nargs=1	,help="name of file to sort"				)
						a_				     =   parser.parse_args()

						a_				     =   ExternalSort(parse_memory(args.mem				)				)
						sorter.sort(args.filename[0]				)


if __name__ == "__main__":
							main()











'''simple docstring'''





from typing import List, Optional, Tuple, Union

from . import logging
from .import_utils import is_torch_available, is_torch_version


if is_torch_available():
							import torch

a_      = logging.get_logger(__name__)  # pylint: disable=invalid-name

try:
							from torch._dynamo import allow_in_graph as maybe_allow_in_graph
except (ImportError, ModuleNotFoundError):



							def 			__UpperCAmelCase				(cls				)		->				Optional[Any]:

													'''simple docstring'''


													return cls



def 			__UpperCAmelCase				(lowercase__	,lowercase__ = None	,lowercase__ = None	,lowercase__ = None	,lowercase__ = None	,)		->				Union[str, Any]:

						'''simple docstring'''


						a_				     =   device
						a_				     =   shape[0]

						a_				     =   layout or torch.strided
						a_				     =   device or torch.device("cpu"				)

						if generator is not None:
												a_				     =   generator.device.type if not isinstance(lowercase__	,lowercase__				) else generator[0].device.type
												if gen_device_type != device.type and gen_device_type == "cpu":
																		a_				     =   "cpu"
																		if device != "mps":
																								logger.info(
																								    F"""The passed generator was created on 'cpu' even though a tensor on {device} was expected."""
																								    F""" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably"""
																								    F""" slighly speed up this function by passing a generator that was created on the {device} device."""				)
												elif gen_device_type != device.type and gen_device_type == "cuda":
																		raise ValueError(F"""Cannot generate a {device} tensor from a generator of type {gen_device_type}."""				)

						if isinstance(lowercase__	,lowercase__				):
												a_				     =   (1,) + shape[1:]
												a_				     =   [
												    torch.randn(lowercase__	,generator=generator[i]	,device=lowercase__	,dtype=lowercase__	,layout=lowercase__				)
												    for i in range(lowercase__				)
												]
												a_				     =   torch.cat(lowercase__	,dim=0				).to(lowercase__				)
						else:
												a_				     =   torch.randn(lowercase__	,generator=lowercase__	,device=lowercase__	,dtype=lowercase__	,layout=lowercase__				).to(lowercase__				)

						return latents



def 			__UpperCAmelCase				(lowercase__				)		->				Tuple:

						'''simple docstring'''


						if is_torch_version("<"	,"2.0.0"				) or not hasattr(lowercase__	,"_dynamo"				):
												return False
						return isinstance(lowercase__	,torch._dynamo.eval_frame.OptimizedModule				)



