



'''simple docstring'''



import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
		from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import ViTImageProcessor





class _UpperCamelCase		:





				'''simple docstring'''





				def __init__(							self  :  str  ,       _lowerCAmelCase  :  int  ,       _lowerCAmelCase  :  Optional[Any]=1_3  ,       _lowerCAmelCase  :  str=3_0  ,       _lowerCAmelCase  :  Optional[Any]=2  ,       _lowerCAmelCase  :  List[str]=3  ,       _lowerCAmelCase  :  Dict=True  ,       _lowerCAmelCase  :  Any=True  ,       _lowerCAmelCase  :  Dict=3_2  ,       _lowerCAmelCase  :  Tuple=5  ,       _lowerCAmelCase  :  Optional[Any]=4  ,       _lowerCAmelCase  :  Optional[Any]=3_7  ,       _lowerCAmelCase  :  Optional[Any]="gelu"  ,       _lowerCAmelCase  :  List[Any]=0.1  ,       _lowerCAmelCase  :  str=0.1  ,       _lowerCAmelCase  :  str=1_0  ,       _lowerCAmelCase  :  str=0.02  ,       _lowerCAmelCase  :  Optional[int]=None  ,       _lowerCAmelCase  :  List[str]=2  ,       ):







											'''simple docstring'''

											__lowercase       	=parent
											__lowercase       	=batch_size
											__lowercase       	=image_size
											__lowercase       	=patch_size
											__lowercase       	=num_channels
											__lowercase       	=is_training
											__lowercase       	=use_labels
											__lowercase       	=hidden_size
											__lowercase       	=num_hidden_layers
											__lowercase       	=num_attention_heads
											__lowercase       	=intermediate_size
											__lowercase       	=hidden_act
											__lowercase       	=hidden_dropout_prob
											__lowercase       	=attention_probs_dropout_prob
											__lowercase       	=type_sequence_label_size
											__lowercase       	=initializer_range
											__lowercase       	=scope
											__lowercase       	=encoder_stride

											# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
											__lowercase       	=(image_size // patch_size) ** 2
											__lowercase       	=num_patches + 1

				def 				__lowerCamelCase     (							self  :  str):







											'''simple docstring'''

											__lowercase       	=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

											__lowercase       	=None
											if self.use_labels:
																		__lowercase       	=ids_tensor([self.batch_size]  ,       self.type_sequence_label_size)

											__lowercase       	=self.get_config()

											return config, pixel_values, labels

				def 				__lowerCamelCase     (							self  :  Dict):







											'''simple docstring'''

											return ViTConfig(
											    image_size=self.image_size  ,       patch_size=self.patch_size  ,       num_channels=self.num_channels  ,       hidden_size=self.hidden_size  ,       num_hidden_layers=self.num_hidden_layers  ,       num_attention_heads=self.num_attention_heads  ,       intermediate_size=self.intermediate_size  ,       hidden_act=self.hidden_act  ,       hidden_dropout_prob=self.hidden_dropout_prob  ,       attention_probs_dropout_prob=self.attention_probs_dropout_prob  ,       is_decoder=_lowerCAmelCase  ,       initializer_range=self.initializer_range  ,       encoder_stride=self.encoder_stride  ,       )

				def 				__lowerCamelCase     (							self  :  int  ,       _lowerCAmelCase  :  List[str]  ,       _lowerCAmelCase  :  List[str]  ,       _lowerCAmelCase  :  Optional[int]):







											'''simple docstring'''

											__lowercase       	=ViTModel(config=_lowerCAmelCase)
											model.to(_lowerCAmelCase)
											model.eval()
											__lowercase       	=model(_lowerCAmelCase)
											self.parent.assertEqual(result.last_hidden_state.shape  ,       (self.batch_size, self.seq_length, self.hidden_size))

				def 				__lowerCamelCase     (							self  :  List[Any]  ,       _lowerCAmelCase  :  Tuple  ,       _lowerCAmelCase  :  List[Any]  ,       _lowerCAmelCase  :  str):







											'''simple docstring'''

											__lowercase       	=ViTForMaskedImageModeling(config=_lowerCAmelCase)
											model.to(_lowerCAmelCase)
											model.eval()
											__lowercase       	=model(_lowerCAmelCase)
											self.parent.assertEqual(
											    result.reconstruction.shape  ,       (self.batch_size, self.num_channels, self.image_size, self.image_size))

											# test greyscale images
											__lowercase       	=1
											__lowercase       	=ViTForMaskedImageModeling(_lowerCAmelCase)
											model.to(_lowerCAmelCase)
											model.eval()

											__lowercase       	=floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
											__lowercase       	=model(_lowerCAmelCase)
											self.parent.assertEqual(result.reconstruction.shape  ,       (self.batch_size, 1, self.image_size, self.image_size))

				def 				__lowerCamelCase     (							self  :  List[str]  ,       _lowerCAmelCase  :  Any  ,       _lowerCAmelCase  :  str  ,       _lowerCAmelCase  :  str):







											'''simple docstring'''

											__lowercase       	=self.type_sequence_label_size
											__lowercase       	=ViTForImageClassification(_lowerCAmelCase)
											model.to(_lowerCAmelCase)
											model.eval()
											__lowercase       	=model(_lowerCAmelCase  ,       labels=_lowerCAmelCase)
											self.parent.assertEqual(result.logits.shape  ,       (self.batch_size, self.type_sequence_label_size))

											# test greyscale images
											__lowercase       	=1
											__lowercase       	=ViTForImageClassification(_lowerCAmelCase)
											model.to(_lowerCAmelCase)
											model.eval()

											__lowercase       	=floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
											__lowercase       	=model(_lowerCAmelCase)
											self.parent.assertEqual(result.logits.shape  ,       (self.batch_size, self.type_sequence_label_size))

				def 				__lowerCamelCase     (							self  :  Any):







											'''simple docstring'''

											__lowercase       	=self.prepare_config_and_inputs()
											(
											    (
											    __lowercase
											)	,				(
											    __lowercase
											)	,				(
											    __lowercase
											)	,				
											)       	=config_and_inputs
											__lowercase       	={'pixel_values': pixel_values}
											return config, inputs_dict





@require_torch
class _UpperCamelCase		(     A      ,       A      ,       unittest.TestCase		):





				'''simple docstring'''





				lowerCAmelCase__					    =    (
				    (
				        ViTModel,
				        ViTForImageClassification,
				        ViTForMaskedImageModeling,
				    )
				    if is_torch_available()
				    else ()
				)
				lowerCAmelCase__					    =    (
				    {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification}
				    if is_torch_available()
				    else {}
				)
				lowerCAmelCase__					    =    True

				lowerCAmelCase__					    =    False
				lowerCAmelCase__					    =    False
				lowerCAmelCase__					    =    False

				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											__lowercase       	=ViTModelTester(self)
											__lowercase       	=ConfigTester(self  ,       config_class=_lowerCAmelCase  ,       has_text_modality=_lowerCAmelCase  ,       hidden_size=3_7)

				def 				__lowerCamelCase     (							self  :  int):







											'''simple docstring'''

											self.config_tester.run_common_tests()

				@unittest.skip(reason='ViT does not use inputs_embeds')
				def 				__lowerCamelCase     (							self  :  Optional[Any]):







											'''simple docstring'''

											pass

				def 				__lowerCamelCase     (							self  :  str):







											'''simple docstring'''

											__lowercase	,				__lowercase       	=self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		__lowercase       	=model_class(_lowerCAmelCase)
																		self.assertIsInstance(model.get_input_embeddings()  ,       (nn.Module))
																		__lowercase       	=model.get_output_embeddings()
																		self.assertTrue(x is None or isinstance(_lowerCAmelCase  ,       nn.Linear))

				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											__lowercase	,				__lowercase       	=self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		__lowercase       	=model_class(_lowerCAmelCase)
																		__lowercase       	=inspect.signature(model.forward)
																		# signature.parameters is an OrderedDict => so arg_names order is deterministic
																		__lowercase       	=[*signature.parameters.keys()]

																		__lowercase       	=['pixel_values']
																		self.assertListEqual(arg_names[:1]  ,       _lowerCAmelCase)

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







											'''simple docstring'''

											__lowercase       	=self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowerCAmelCase)

				def 				__lowerCamelCase     (							self  :  int):







											'''simple docstring'''

											__lowercase       	=self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCAmelCase)

				def 				__lowerCamelCase     (							self  :  Tuple):







											'''simple docstring'''

											__lowercase       	=self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase)

				@slow
				def 				__lowerCamelCase     (							self  :  List[str]):







											'''simple docstring'''

											for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		__lowercase       	=ViTModel.from_pretrained(_lowerCAmelCase)
																		self.assertIsNotNone(_lowerCAmelCase)



def   _A       (   ):



							"""simple docstring"""



							__lowercase       	=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
							return image





@require_torch
@require_vision
class _UpperCamelCase		(     unittest.TestCase		):





				'''simple docstring'''





				@cached_property
				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224') if is_vision_available() else None

				@slow
				def 				__lowerCamelCase     (							self  :  int):







											'''simple docstring'''

											__lowercase       	=ViTForImageClassification.from_pretrained('google/vit-base-patch16-224').to(_lowerCAmelCase)

											__lowercase       	=self.default_image_processor
											__lowercase       	=prepare_img()
											__lowercase       	=image_processor(images=_lowerCAmelCase  ,       return_tensors='pt').to(_lowerCAmelCase)

											# forward pass
											with torch.no_grad():
																		__lowercase       	=model(**_lowerCAmelCase)

											# verify the logits
											__lowercase       	=torch.Size((1, 1_0_0_0))
											self.assertEqual(outputs.logits.shape  ,       _lowerCAmelCase)

											__lowercase       	=torch.tensor([-0.2744, 0.8215, -0.0836]).to(_lowerCAmelCase)

											self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,       _lowerCAmelCase  ,       atol=1e-4))

				@slow
				def 				__lowerCamelCase     (							self  :  Union[str, Any]):







											'''simple docstring'''

											__lowercase       	=ViTModel.from_pretrained('facebook/dino-vits8').to(_lowerCAmelCase)

											__lowercase       	=ViTImageProcessor.from_pretrained('facebook/dino-vits8'  ,       size=4_8_0)
											__lowercase       	=prepare_img()
											__lowercase       	=image_processor(images=_lowerCAmelCase  ,       return_tensors='pt')
											__lowercase       	=inputs.pixel_values.to(_lowerCAmelCase)

											# forward pass
											with torch.no_grad():
																		__lowercase       	=model(_lowerCAmelCase  ,       interpolate_pos_encoding=_lowerCAmelCase)

											# verify the logits
											__lowercase       	=torch.Size((1, 3_6_0_1, 3_8_4))
											self.assertEqual(outputs.last_hidden_state.shape  ,       _lowerCAmelCase)

											__lowercase       	=torch.tensor(
											    [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]).to(_lowerCAmelCase)

											self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]  ,       _lowerCAmelCase  ,       atol=1e-4))

				@slow
				@require_accelerate
				@require_torch_gpu
				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											__lowercase       	=ViTModel.from_pretrained('facebook/dino-vits8'  ,       torch_dtype=torch.floataa  ,       device_map='auto')
											__lowercase       	=self.default_image_processor

											__lowercase       	=prepare_img()
											__lowercase       	=image_processor(images=_lowerCAmelCase  ,       return_tensors='pt')
											__lowercase       	=inputs.pixel_values.to(_lowerCAmelCase)

											# forward pass to make sure inference works in fp16
											with torch.no_grad():
																		__lowercase       	=model(_lowerCAmelCase)








'''simple docstring'''



def   _A       (   _lowerCAmelCase  ,   _lowerCAmelCase  ,   _lowerCAmelCase					):



							"""simple docstring"""



							if len(_lowerCAmelCase					) != len(_lowerCAmelCase					):
														raise ValueError('The length of profit and weight must be same.'					)
							if max_weight <= 0:
														raise ValueError('max_weight must greater than zero.'					)
							if any(p < 0 for p in profit					):
														raise ValueError('Profit can not be negative.'					)
							if any(w < 0 for w in weight					):
														raise ValueError('Weight can not be negative.'					)

							# List created to store profit gained for the 1kg in case of each weight
							# respectively.  Calculate and append profit/weight for each element.
							__lowercase       	=[p / w for p, w in zip(_lowerCAmelCase  ,   _lowerCAmelCase					)]

							# Creating a copy of the list and sorting profit/weight in ascending order
							__lowercase       	=sorted(_lowerCAmelCase					)

							# declaring useful variables
							__lowercase       	=len(_lowerCAmelCase					)
							__lowercase       	=0
							__lowercase       	=0
							__lowercase       	=0

							# loop till the total weight do not reach max limit e.g. 15 kg and till i<length
							while limit <= max_weight and i < length:
														# flag value for encountered greatest element in sorted_profit_by_weight
														__lowercase       	=sorted_profit_by_weight[length - i - 1]
														__lowercase       	=profit_by_weight.index(_lowerCAmelCase					)
														__lowercase       	=-1

														# check if the weight encountered is less than the total weight
														# encountered before.
														if max_weight - limit >= weight[index]:
																					limit += weight[index]
																					# Adding profit gained for the given weight 1 ===
																					# weight[index]/weight[index]
																					gain += 1 * profit[index]
														else:
																					# Since the weight encountered is greater than limit, therefore take the
																					# required number of remaining kgs and calculate profit for it.
																					# weight remaining / weight[index]
																					gain += (max_weight - limit) / weight[index] * profit[index]
																					break
														i += 1
							return gain


if __name__ == "__main__":
		print(
		    """Input profits, weights, and then max_weight (all positive ints) separated by """
		    """spaces."""
		)

		lowerCamelCase	 =       [int(x) for x in input("""Input profits separated by spaces: """).split()]
		lowerCamelCase	 =       [int(x) for x in input("""Input weights separated by spaces: """).split()]
		lowerCamelCase	 =       int(input("""Max weight allowed: """))

		# Function Call
		calc_profit(profit, weight, max_weight)



