n getValue(): int {\n return $this->value;\n }\n\n public function add(NumberObjectInterface $number): NumberObjectInterface {\n return new Number($this->value + $number->getValue());\n }\n\n public function multiply(NumberObjectInterface $number): NumberObjectInterface {\n return new Number($this->value * $number->getValue());\n }\n\n public static function fromPrimitive(int $value): NumberObjectInterface {\n return new Number($value);\n }\n}\n\nclass FactorialCalculator {\n public function factorial(int $n): NumberObjectInterface {\n \/\/ Your implementation here\n }\n}\n```","solution":"```php\nclass FactorialCalculator {\n public function factorial(int $n): NumberObjectInterface {\n if ($n < 0) {\n throw new InvalidArgumentException(\"Factorial is not defined for negative numbers\");\n }\n\n $result = 1;\n for ($i = 2; $i <= $n; $i++) {\n $result *= $i;\n }\n\n return Number::fromPrimitive($result);\n }\n}\n```\n\nThe `factorial` method in the `FactorialCalculator` class calculates the factorial of a non-negative integer using a simple iterative approach. It first checks if the input is non-negative and then calculates the factorial using a loop. The result is then returned as a NumberObjectInterface instance using the `fromPrimitive` method of the Number class. If the input is negative, an InvalidArgumentException is thrown."} {"lang":"shell","raw_index":15180,"index":322,"seed":"# keep track of the last executed command\ntrap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG\n# echo an error message before exiting\ntrap 'echo \"\\\"${last_command}\\\" command finished with exit code $?.\"' EXIT\n\n#npm install\n#ionic cordova prepare\n\nbranch=$(git branch | grep \\* | cut -d ' ' -f2)\necho Current git branch: $branch\nif [ \"$branch\" == \"master\" ]\n then\n\n. .\/env-prod.sh\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a script to automate the deployment process for a web application. The script should perform the following tasks:\n\n1. Set up a trap to keep track of the last executed command and echo an error message before exiting.\n2. Check the current git branch and execute specific commands based on the branch name.\n3. If the current git branch is \"master,\" source an environment configuration file named \"env-prod.sh.\"\n\nYour task is to write a Bash script that accomplishes the above requirements and ensures the correct execution of commands based on the git branch.","solution":"```bash\n#!\/bin\/bash\n\n# Set up trap to keep track of the last executed command and echo an error message before exiting\ntrap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG\ntrap 'echo \"\\\"${last_command}\\\" command finished with exit code $?.\"' EXIT\n\n# Check the current git branch\nbranch=$(git branch | grep \\* | cut -d ' ' -f2)\necho \"Current git branch: $branch\"\n\n# Execute commands based on the git branch\nif [ \"$branch\" == \"master\" ]; then\n # Source environment configuration file for production\n . .\/env-prod.sh\n # Additional deployment commands for the master branch\n # Example: npm install, ionic cordova prepare, etc.\nfi\n\n# Add more conditional blocks for other branches if needed\n# Example:\n# if [ \"$branch\" == \"development\" ]; then\n# . .\/env-dev.sh\n# # Additional deployment commands for the development branch\n# fi\n\n# Add more conditional blocks for other branches as per the deployment requirements\n```\n\nIn the solution, a Bash script is provided that sets up traps to keep track of the last executed command and echo an error message before exiting. It then checks the current git branch and sources the environment configuration file \"env-prod.sh\" if the branch is \"master.\" Additional conditional blocks can be added for other branches to execute specific deployment commands based on the branch name."} {"lang":"python","raw_index":55020,"index":39070,"seed":" if (is_divisible):\n break\n\nprint(n)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a positive integer `n`. Your task is to find the smallest positive integer `m` such that the product of all the digits of `m` is divisible by `n`. If no such `m` exists, return -1.\n\nWrite a function `smallest_divisible_number(n)` that takes in a positive integer `n` and returns the smallest positive integer `m` that satisfies the given condition.\n\nFor example, given `n = 12`, the function should return `26` because the product of the digits of `26` is `2*6=12`, which is divisible by `12`.","solution":"```python\ndef smallest_divisible_number(n):\n if n == 1:\n return 1\n\n def product_of_digits(num):\n product = 1\n while num > 0:\n product *= num % 10\n num \/\/= 10\n return product\n\n for m in range(1, 10**6):\n if product_of_digits(m) % n == 0:\n return m\n return -1\n```"} {"lang":"python","raw_index":129630,"index":17183,"seed":"\r\n colon = _get_colon(s)\r\n\r\n if colon not in s:\r\n return colon + s\r\n\r\n comps = s.split(colon)\r\n i = 1\r\n while i < len(comps)-1:\r\n if not comps[i] and comps[i-1]:\r\n if i > 1:\r\n del comps[i-1:i+1]\r\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a string `s` containing a series of components separated by a colon (`:`). Your task is to write a function that removes adjacent empty components in the string and returns the modified string.\n\nWrite a function `remove_adjacent_empty_components(s: str) -> str` that takes in a string `s` and returns the modified string after removing adjacent empty components.\n\nFor example, given the input string `\"a::b:c::d\"`, the function should return `\"a:b:c:d\"` as the output.","solution":"```python\ndef remove_adjacent_empty_components(s: str) -> str:\n def _get_colon(s: str) -> str:\n for i, char in enumerate(s):\n if char == \":\":\n return \":\"\n return \"\"\n\n colon = _get_colon(s)\n\n if colon not in s:\n return colon + s\n\n comps = s.split(colon)\n i = 1\n while i < len(comps)-1:\n if not comps[i] and comps[i-1]:\n if i > 1:\n del comps[i-1:i+1]\n\n return colon.join(comps)\n```\nThe `remove_adjacent_empty_components` function first identifies the colon used for splitting the components. It then splits the input string into components and iterates through them to remove adjacent empty components. Finally, it joins the modified components using the identified colon and returns the resulting string."} {"lang":"python","raw_index":53860,"index":16850,"seed":" # fallback, don't know how to get tabs from ibmcloud registry\n return _get_last_version_from_local_docker(c, registry, image)\n\n url = 'https:\/\/{}\/v2\/{}\/tags\/list'.format(registry, image)\n r = requests.get(url, **_auth_headers(c, registry))\n r.raise_for_status()\n tags = r.json()['tags']\n if len(tags) == 100:\n raise RuntimeError(\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that retrieves the latest version of a Docker image from a given registry. The function should handle the scenario where the number of tags for the image exceeds 100.\n\nYou are provided with a code snippet that partially implements this functionality. The snippet makes use of the `requests` library to send a GET request to the registry's API endpoint and retrieve the list of tags for a specific image. If the number of tags is exactly 100, a `RuntimeError` is raised. If the number of tags is less than 100, the function should return the latest version of the image.\n\nYour task is to complete the implementation of the function to handle the case where the number of tags is exactly 100. If the number of tags is 100, the function should return the latest version of the image by sorting the tags and selecting the last one.\n\nComplete the function `get_latest_image_version` with the following signature:\n```python\ndef get_latest_image_version(registry: str, image: str) -> str:\n # Your implementation here\n```\n\nExample:\n```python\nprint(get_latest_image_version('example.com', 'myimage'))\n# Output: 'v1.2.3'\n```","solution":"```python\nimport requests\n\ndef _auth_headers(c, registry):\n # Implementation of _auth_headers function is not provided in the given code snippet\n\ndef _get_last_version_from_local_docker(c, registry, image):\n # Implementation of _get_last_version_from_local_docker function is not provided in the given code snippet\n\ndef get_latest_image_version(registry: str, image: str) -> str:\n url = 'https:\/\/{}\/v2\/{}\/tags\/list'.format(registry, image)\n r = requests.get(url, **_auth_headers(c, registry))\n r.raise_for_status()\n tags = r.json()['tags']\n if len(tags) == 100:\n tags.sort() # Sort the tags\n return tags[-1] # Return the last (latest) tag\n else:\n return tags[-1] # Return the latest tag\n\n# Test the function\nprint(get_latest_image_version('example.com', 'myimage'))\n```\n\nIn the solution, the `get_latest_image_version` function is completed to handle the case where the number of tags is exactly 100. If the number of tags is 100, the function sorts the tags and returns the last (latest) tag. If the number of tags is less than 100, the function directly returns the latest tag."} {"lang":"shell","raw_index":62872,"index":3904,"seed":" cardano-cli node key-gen-VRF \\\n --verification-key-file node$i-vrf.vkey \\\n --signing-key-file node$i-vrf.skey\ndone\ncd ..\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a script to automate the generation of Cardano node VRF (Verifiable Random Function) key pairs. The Cardano blockchain platform uses VRF for various cryptographic operations, and you need to streamline the process of generating these key pairs for multiple nodes.\n\nYour script should take an input parameter `n` representing the number of nodes for which key pairs need to be generated. For each node, the script should execute the command `cardano-cli node key-gen-VRF` to create a verification key file (`node-vrf.vkey`) and a signing key file (`node-vrf.skey`), where `` represents the node number.\n\nWrite a bash script that takes the input parameter `n` and generates the necessary key pairs for the specified number of nodes.\n\nExample:\nInput:\n```\nn = 3\n```\nOutput:\n```\nGenerated VRF key pairs for 3 nodes\n```\nFiles created:\n```\nnode1-vrf.vkey, node1-vrf.skey\nnode2-vrf.vkey, node2-vrf.skey\nnode3-vrf.vkey, node3-vrf.skey\n```","solution":"```bash\n#!\/bin\/bash\n\n# Check if input parameter is provided\nif [ -z \"$1\" ]; then\n echo \"Please provide the number of nodes as an input parameter\"\n exit 1\nfi\n\n# Extract the number of nodes from input parameter\nn=$1\n\n# Loop through the range of nodes and generate key pairs\nfor ((i=1; i<=$n; i++)); do\n cardano-cli node key-gen-VRF \\\n --verification-key-file node$i-vrf.vkey \\\n --signing-key-file node$i-vrf.skey\ndone\n\necho \"Generated VRF key pairs for $n nodes\"\n```\n\nThis bash script takes the input parameter `n` and uses a loop to generate VRF key pairs for the specified number of nodes. It checks if the input parameter is provided and then iterates through the range of nodes, executing the `cardano-cli node key-gen-VRF` command to create the necessary key pairs. Finally, it outputs a message confirming the successful generation of key pairs."} {"lang":"python","raw_index":69960,"index":27419,"seed":"print(command_manager.all_command_help(max_length=6, page=3, pages=\"[%d\/%d]\"))\nprint(\"\\n\")\nprint(command_manager.broadcast(\"cmd.\u5317\u4eac\u5929\u6c14\"))\nprint(command_manager.require(\"\/pip\"))\nprint(command_manager.command_help(\"\/pip\"))","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a command manager for a chatbot application. The command manager is responsible for handling various commands, including providing help for all commands, broadcasting messages, and managing required commands.\n\nYour task is to implement a Python class `CommandManager` with the following functionalities:\n\n1. `all_command_help(max_length, page, pages)`: This method should return a formatted string containing help information for all commands. The `max_length` parameter specifies the maximum length of each command's help text. The `page` parameter specifies the page number to display, and the `pages` parameter specifies the format for displaying the total number of pages.\n\n2. `broadcast(message)`: This method should broadcast the given `message` to all users.\n\n3. `require(command)`: This method should mark a command as required, ensuring that it is available for use.\n\n4. `command_help(command)`: This method should return the help information for the specified `command`.\n\nYou are provided with a code snippet that demonstrates the usage of these methods. Your task is to implement the `CommandManager` class with the specified functionalities.","solution":"```python\nclass CommandManager:\n def __init__(self):\n self.commands = {}\n self.required_commands = set()\n\n def all_command_help(self, max_length, page, pages):\n all_help = \"\"\n commands_list = list(self.commands.keys())\n total_pages = (len(commands_list) + max_length - 1) \/\/ max_length\n start_index = (page - 1) * max_length\n end_index = min(start_index + max_length, len(commands_list))\n for i in range(start_index, end_index):\n command = commands_list[i]\n help_text = self.commands[command]\n all_help += f\"{command}: {help_text}\\n\"\n return f\"{all_help}\\n{pages % (page, total_pages)}\"\n\n def broadcast(self, message):\n # Code for broadcasting the message to all users\n print(f\"Broadcasting message: {message}\")\n\n def require(self, command):\n self.required_commands.add(command)\n\n def command_help(self, command):\n if command in self.commands:\n return f\"{command}: {self.commands[command]}\"\n else:\n return f\"Command '{command}' not found\"\n\n# Usage\ncommand_manager = CommandManager()\ncommand_manager.commands = {\n \"\/pip\": \"Manage Python packages\",\n \"\/weather\": \"Get weather information\",\n \"\/help\": \"Display help information\"\n}\n\nprint(command_manager.all_command_help(max_length=6, page=3, pages=\"[%d\/%d]\"))\nprint(\"\\n\")\nprint(command_manager.broadcast(\"cmd.\u5317\u4eac\u5929\u6c14\"))\nprint(command_manager.require(\"\/pip\"))\nprint(command_manager.command_help(\"\/pip\"))\n```\n\nIn the solution, the `CommandManager` class is implemented with the specified functionalities. The `all_command_help` method generates formatted help information for all commands, considering the specified page and max length. The `broadcast` method simulates broadcasting a message. The `require` method marks a command as required, and the `command_help` method retrieves help information for a specific command. The provided code snippet demonstrates the usage of these methods."} {"lang":"python","raw_index":43946,"index":18973,"seed":"Paul11100\/LeetCode\nclass Solution:\n # Codes (Accepted), O(n) time and space\n def replaceDigits(self, s: str) -> str:\n li, n = [], len(s)\n for i in range(0, n, 2):\n if i+1 < n:\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a string `s` consisting of lowercase English letters and digits. The digits are represented by a pair of a letter and a digit. The letter represents the position of the digit in the string, and the digit represents the number of positions to shift the letter. The task is to replace every digit with the letter located at the shifted position.\n\nWrite a function `replaceDigits(s: str) -> str` to return the resulting string after replacing every digit with the letter located at the shifted position.\n\nFunction signature: `def replaceDigits(s: str) -> str`\n\n**Input**\n- The input parameter is a string `s` (1 <= |s| <= 100), where |s| denotes the length of the string. The string consists of lowercase English letters and digits.\n\n**Output**\n- Return the resulting string after replacing every digit with the letter located at the shifted position.\n\n**Example**\n```\nInput: s = \"a1c1e1\"\nOutput: \"abcdef\"\nExplanation: The digits are replaced as follows:\n- 1st digit: 'a' + 1 = 'b'\n- 2nd digit: 'c' + 1 = 'd'\n- 3rd digit: 'e' + 1 = 'f'\nHence, the resulting string is \"abcdef\".\n```","solution":"```python\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n result = []\n for i in range(len(s)):\n if i % 2 == 0:\n result.append(s[i])\n else:\n result.append(chr(ord(s[i-1]) + int(s[i])))\n return ''.join(result)\n```\nThe `replaceDigits` function iterates through the input string `s` and replaces every digit with the letter located at the shifted position. It uses the ASCII value of the previous letter and adds the digit to it to get the new letter. Finally, it returns the resulting string after the replacements."} {"lang":"python","raw_index":28680,"index":6367,"seed":"\n self.dataset = self.available_datasets[dataset_name]\n\n if dataset_name == \"visda19\":\n data = self.dataset.load(split=split, domain=domain, img_width=img_width, img_height=img_height)\n else:\n data = self.dataset.load(split=split, img_width=img_width, img_height=img_height)\n return data\n else:\n print(\"Dataset not implemented\")\n print(\"Please choose from the following:\")\n print(self.get_supported_datasets())","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class method for loading data from different datasets. The class has a dictionary `available_datasets` containing various dataset objects, and the method is responsible for loading data from a specified dataset. The method first checks if the requested dataset is available, and if so, it loads the data based on the dataset name, split, domain, image width, and image height. If the dataset is not available, it prints a message listing the supported datasets.\n\nYou are required to implement the `load_data` method of the class, which takes the following parameters:\n- `dataset_name`: A string representing the name of the dataset to load.\n- `split`: A string representing the data split (e.g., train, test).\n- `domain`: A string representing the domain of the data (applicable only for the \"visda19\" dataset).\n- `img_width`: An integer representing the width of the images to be loaded.\n- `img_height`: An integer representing the height of the images to be loaded.\n\nThe method should perform the following actions:\n1. Check if the requested `dataset_name` is available in the `available_datasets` dictionary.\n2. If the dataset is available, load the data using the `load` method of the dataset object. If the dataset is \"visda19\", pass the `split`, `domain`, `img_width`, and `img_height` as arguments to the `load` method. For other datasets, pass the `split`, `img_width`, and `img_height` as arguments.\n3. If the dataset is not available, print a message indicating that the dataset is not implemented and list the supported datasets using the `get_supported_datasets` method.\n\nYour task is to implement the `load_data` method according to the given requirements.\n\n```python\nclass DatasetLoader:\n def __init__(self, available_datasets):\n self.available_datasets = available_datasets\n\n def load_data(self, dataset_name, split, domain=None, img_width=256, img_height=256):\n if dataset_name in self.available_datasets:\n dataset = self.available_datasets[dataset_name]\n if dataset_name == \"visda19\":\n data = dataset.load(split=split, domain=domain, img_width=img_width, img_height=img_height)\n else:\n data = dataset.load(split=split, img_width=img_width, img_height=img_height)\n return data\n else:\n print(\"Dataset not implemented\")\n print(\"Please choose from the following:\")\n print(self.get_supported_datasets())\n```","solution":"```python\n# Sample solution for the load_data method\nclass Dataset:\n def __init__(self, name):\n self.name = name\n\n def load(self, split, domain=None, img_width=256, img_height=256):\n # Sample implementation of the load method for a dataset\n # This can vary based on the actual dataset implementation\n # Replace this with the actual implementation for each dataset\n print(f\"Loading data for {self.name} dataset\")\n print(f\"Split: {split}, Domain: {domain}, Image Size: {img_width}x{img_height}\")\n return f\"Data loaded for {self.name} dataset\"\n\n# Sample usage of the DatasetLoader class\n# Create dataset objects and add them to the available_datasets dictionary\ndataset1 = Dataset(\"dataset1\")\ndataset2 = Dataset(\"visda19\")\navailable_datasets = {\"dataset1\": dataset1, \"visda19\": dataset2}\n\n# Create an instance of the DatasetLoader class\nloader = DatasetLoader(available_datasets)\n\n# Load data from the \"dataset1\" dataset\ndata1 = loader.load_data(\"dataset1\", \"train\", img_width=128, img_height=128)\nprint(data1)\n\n# Load data from the \"visda19\" dataset\ndata2 = loader.load_data(\"visda19\", \"test\", domain=\"domain1\", img_width=224, img_height=224)\nprint(data2)\n\n# Attempt to load data from an unsupported dataset\nloader.load_data(\"unsupported_dataset\", \"train\")\n```\n\nIn the solution, the `DatasetLoader` class is implemented with the `load_data` method according to the given requirements. Additionally, a sample implementation of the `Dataset` class and its `load` method is provided to demonstrate the usage of the `load_data` method. The sample usage showcases loading data from different datasets and handling the case of an unsupported dataset."} {"lang":"rust","raw_index":83401,"index":2924,"seed":" while !end {\n if total_reward > 500.0 {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a reinforcement learning algorithm for a simple game. The game involves a player navigating through a grid-based environment, collecting rewards along the way. The player's goal is to maximize the total reward obtained while navigating the grid. The game is represented as a 2D grid, where the player can move up, down, left, or right from their current position. Each cell in the grid may contain a reward value, and the player's objective is to accumulate rewards by visiting different cells.\n\nYour task is to implement the logic for the player's movement and reward accumulation. The player's movement is controlled by the reinforcement learning algorithm, which makes decisions based on the total reward accumulated so far. The algorithm should continue making decisions until the total reward exceeds 500.0.\n\nYou are provided with a code snippet that represents the beginning of the reinforcement learning algorithm. The `while` loop continues until the variable `end` becomes true. Inside the loop, there is a conditional check that compares the `total_reward` with 500.0. Your task is to complete the reinforcement learning algorithm by implementing the logic for the player's movement and reward accumulation based on the given grid environment.\n\nYour implementation should include the following:\n- Define the grid environment with reward values for each cell.\n- Implement the logic for the player's movement within the grid.\n- Update the `total_reward` based on the rewards obtained by the player.\n- Ensure that the algorithm terminates when the total reward exceeds 500.0.","solution":"```python\n# Define the grid environment with reward values for each cell\ngrid = [\n [10, 0, 5, 0],\n [0, 0, 8, 2],\n [3, 7, 0, 20],\n [0, 0, 0, 15]\n]\n\n# Initialize player's position and total reward\nplayer_position = (0, 0) # Start at the top-left corner\ntotal_reward = 0.0\nend = False\n\n# Implement the logic for the player's movement and reward accumulation\nwhile not end:\n # Determine the available movements (up, down, left, right) based on current position\n available_movements = []\n if player_position[0] > 0:\n available_movements.append(\"up\")\n if player_position[0] < len(grid) - 1:\n available_movements.append(\"down\")\n if player_position[1] > 0:\n available_movements.append(\"left\")\n if player_position[1] < len(grid[0]) - 1:\n available_movements.append(\"right\")\n\n # Choose a random movement from the available options\n import random\n next_movement = random.choice(available_movements)\n\n # Update player's position and accumulate reward based on the movement\n if next_movement == \"up\":\n player_position = (player_position[0] - 1, player_position[1])\n elif next_movement == \"down\":\n player_position = (player_position[0] + 1, player_position[1])\n elif next_movement == \"left\":\n player_position = (player_position[0], player_position[1] - 1)\n elif next_movement == \"right\":\n player_position = (player_position[0], player_position[1] + 1)\n\n # Accumulate reward based on the new position\n total_reward += grid[player_position[0]][player_position[1]]\n\n # Check if the total reward exceeds 500.0 to terminate the algorithm\n if total_reward > 500.0:\n end = True\n\n# The algorithm terminates when the total reward exceeds 500.0\n```"} {"lang":"python","raw_index":71775,"index":2273,"seed":" version='2.0.0',\n description='gui and cli for control nauta connection and accounts',\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that parses a given string and extracts specific key-value pairs from it. The key-value pairs are formatted as `key='value'` and are separated by commas. The function should return a dictionary containing these key-value pairs.\n\nYou are given a code snippet as an example of the input string format:\n```\nversion='2.0.0',\ndescription='gui and cli for control nauta connection and accounts',\n```\n\nCreate a function `parse_key_value_pairs(input_string)` that takes a string `input_string` as input and returns a dictionary containing the extracted key-value pairs.\n\nFunction Signature: `def parse_key_value_pairs(input_string: str) -> dict`\n\nExample:\nInput:\n```\ninput_string = \"version='2.0.0',description='gui and cli for control nauta connection and accounts',\"\nparse_key_value_pairs(input_string)\n```\nOutput:\n```\n{'version': '2.0.0', 'description': 'gui and cli for control nauta connection and accounts'}\n```","solution":"```python\ndef parse_key_value_pairs(input_string: str) -> dict:\n key_value_pairs = input_string.split(',')\n result = {}\n for pair in key_value_pairs:\n if pair.strip(): # Check if the pair is not an empty string\n key, value = pair.split('=')\n result[key.strip()] = value.strip().strip(\"'\")\n return result\n\n# Test the function\ninput_string = \"version='2.0.0',description='gui and cli for control nauta connection and accounts',\"\nprint(parse_key_value_pairs(input_string))\n```\n\nThe `parse_key_value_pairs` function splits the input string by commas to obtain individual key-value pairs. It then iterates through each pair, extracts the key and value by splitting at the equals sign, and adds them to the result dictionary after removing any leading or trailing spaces and single quotes. Finally, it returns the dictionary containing the extracted key-value pairs."} {"lang":"python","raw_index":106077,"index":18411,"seed":" tups = [MockTuple(**d) for d in data]\n\n expected = [(5, [MockTuple(a=5, b=8), MockTuple(a=5, b=7)]),\n (4, [MockTuple(a=4, b=4)])]\n result = list(partition_ordered(tups, key=attrgetter('a')))\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function to partition a list of tuples based on a specific key attribute. The function should take a list of tuples and a key function as input and return a list of tuples where each tuple consists of a key value and a list of tuples having the same key value, ordered by the key value.\n\nFor example, given the following list of tuples:\n```\ntups = [MockTuple(a=5, b=8), MockTuple(a=4, b=4), MockTuple(a=5, b=7)]\n```\nand the key function `attrgetter('a')`, the expected output would be:\n```\n[(5, [MockTuple(a=5, b=8), MockTuple(a=5, b=7)]), (4, [MockTuple(a=4, b=4)])]\n```\nYour task is to implement the `partition_ordered` function that achieves this behavior.","solution":"```python\nfrom operator import attrgetter\n\nclass MockTuple:\n def __init__(self, **kwargs):\n for key, value in kwargs.items():\n setattr(self, key, value)\n\ndef partition_ordered(tups, key):\n # Sort the input list of tuples based on the key attribute\n tups.sort(key=key)\n\n # Initialize an empty dictionary to store the partitioned tuples\n partitioned = {}\n\n # Iterate through the sorted list of tuples\n for tup in tups:\n # Extract the key value using the key function\n key_value = key(tup)\n\n # If the key value is not in the partitioned dictionary, add it with an empty list\n if key_value not in partitioned:\n partitioned[key_value] = []\n\n # Append the current tuple to the list corresponding to its key value\n partitioned[key_value].append(tup)\n\n # Convert the partitioned dictionary into a list of tuples and return it\n return list(partitioned.items())\n\n# Example usage\ndata = [{'a': 5, 'b': 8}, {'a': 4, 'b': 4}, {'a': 5, 'b': 7}]\ntups = [MockTuple(**d) for d in data]\nresult = list(partition_ordered(tups, key=attrgetter('a')))\nprint(result) # Output: [(4, [MockTuple(a=4, b=4)]), (5, [MockTuple(a=5, b=8), MockTuple(a=5, b=7)])]\n```\n\nThe `partition_ordered` function first sorts the input list of tuples based on the key attribute using the `sort` method. Then, it iterates through the sorted list, creating a dictionary where the keys are the unique key values and the values are lists of tuples with the same key value. Finally, it converts the dictionary into a list of tuples and returns it."} {"lang":"php","raw_index":59904,"index":1161,"seed":" <\/td>\n <\/tr>\n <\/table>\n <\/div>\n <\/div>\n @endforeach\n <\/div>\n <\/div>\n<\/div>\n@endsection","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that counts the occurrences of a specific word in a given text. The function should be case-insensitive and should only consider whole words, ignoring any partial matches within other words.\n\nYou are given the following code snippet as a starting point:\n\n```python\ndef count_word_occurrences(text, word):\n # Your implementation here\n pass\n\ntext = \"The quick brown fox jumps over the lazy dog. The dog barks, but the fox keeps running.\"\nword = \"the\"\n\nprint(count_word_occurrences(text, word)) # Output: 4\n```\n\nImplement the `count_word_occurrences` function to fulfill the requirements.","solution":"```python\nimport re\n\ndef count_word_occurrences(text, word):\n # Preprocess the text and word to ensure case-insensitive matching\n text = text.lower()\n word = word.lower()\n\n # Use regular expression to find whole word occurrences\n occurrences = re.findall(r'\\b' + word + r'\\b', text)\n\n return len(occurrences)\n\ntext = \"The quick brown fox jumps over the lazy dog. The dog barks, but the fox keeps running.\"\nword = \"the\"\n\nprint(count_word_occurrences(text, word)) # Output: 4\n```\n\nThe `count_word_occurrences` function first converts the input text and word to lowercase to ensure case-insensitive matching. It then uses a regular expression to find all whole word occurrences of the given word in the text. Finally, it returns the count of occurrences found."} {"lang":"shell","raw_index":100642,"index":2662,"seed":" --build-arg ADDITIONAL_PACKAGES=\"${ADDITIONAL_PACKAGES}\" \\\n --build-arg INSTALL_IPE=\"${INSTALL_IPE}\" \\\n . \\\n && cd .. \\\n && docker run -v \"$(pwd):\/github\/workspace\" --workdir \/github\/workspace docker-action \"${PROJECT}\" \"${CONFIGURATION}\"\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a project that involves building and running Docker containers using a specific set of arguments and commands. Your task is to write a script that automates this process based on the given code snippet.\n\nYou are provided with the following code snippet as a reference:\n\n```bash\n--build-arg ADDITIONAL_PACKAGES=\"${ADDITIONAL_PACKAGES}\" \\\n--build-arg INSTALL_IPE=\"${INSTALL_IPE}\" \\\n. \\\n&& cd .. \\\n&& docker run -v \"$(pwd):\/github\/workspace\" --workdir \/github\/workspace docker-action \"${PROJECT}\" \"${CONFIGURATION}\"\n```\n\nYour task is to create a shell script that accomplishes the following:\n1. Builds a Docker container with the specified additional packages and installation flag.\n2. Moves to the parent directory.\n3. Runs the Docker container with the appropriate volume and working directory, passing the project and configuration as arguments.\n\nWrite a shell script that achieves the above tasks based on the given code snippet. Assume that the variables `ADDITIONAL_PACKAGES`, `INSTALL_IPE`, `PROJECT`, and `CONFIGURATION` are provided and need to be used in the script.","solution":"```bash\n#!\/bin\/bash\n\n# Assigning values to variables\nADDITIONAL_PACKAGES=\"package1 package2\"\nINSTALL_IPE=\"true\"\nPROJECT=\"my_project\"\nCONFIGURATION=\"debug\"\n\n# Building the Docker container\ndocker build \\\n--build-arg ADDITIONAL_PACKAGES=\"${ADDITIONAL_PACKAGES}\" \\\n--build-arg INSTALL_IPE=\"${INSTALL_IPE}\" \\\n. \\\n&& cd .. \\\n&& docker run -v \"$(pwd):\/github\/workspace\" --workdir \/github\/workspace docker-action \"${PROJECT}\" \"${CONFIGURATION}\"\n```\n\nIn the solution, the shell script begins by assigning values to the variables `ADDITIONAL_PACKAGES`, `INSTALL_IPE`, `PROJECT`, and `CONFIGURATION`. Then, it proceeds to build the Docker container with the specified additional packages and installation flag, moves to the parent directory, and runs the Docker container with the appropriate volume and working directory, passing the project and configuration as arguments."} {"lang":"python","raw_index":102767,"index":30955,"seed":" 'exon:chr12:42768665-42768876:+',\n 'exon:chr12:42781258-42781337:+',\n 'exon:chr12:42787372-42787491:+',\n 'exon:chr12:42792656-42792796:+']\n\n@pytest.fixture()\ndef exc_trans_with_exon_ids():\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a list of exon IDs representing exons on a specific chromosome. Each exon ID is in the format 'exon:chr{chromosome_number}:{start_position}-{end_position}:{strand}', where chromosome_number is the number of the chromosome, start_position and end_position are the start and end positions of the exon on the chromosome, and strand represents the direction of the exon (+ for forward strand, - for reverse strand).\n\nYou are required to write a Python function that takes this list of exon IDs as input and returns a dictionary containing the following information:\n- Total number of exons\n- Chromosome with the most exons\n- Exon with the largest span (difference between end and start positions)\n- Exon with the smallest span\n\nYour function should be named `analyze_exons` and should take the list of exon IDs as its only parameter.\n\nFor example, given the input:\n```\n['exon:chr12:42768665-42768876:+',\n'exon:chr12:42781258-42781337:+',\n'exon:chr12:42787372-42787491:+',\n'exon:chr12:42792656-42792796:+']\n```\nThe function should return the following dictionary:\n```\n{\n 'total_exons': 4,\n 'chromosome_with_most_exons': 'chr12',\n 'exon_with_largest_span': 'exon:chr12:42792656-42792796:+',\n 'exon_with_smallest_span': 'exon:chr12:42781258-42781337:+'\n}\n```","solution":"```python\ndef analyze_exons(exon_ids):\n exon_info = {\n 'total_exons': len(exon_ids),\n 'chromosome_with_most_exons': '',\n 'max_exons_count': 0,\n 'exon_with_largest_span': '',\n 'largest_span': 0,\n 'exon_with_smallest_span': '',\n 'smallest_span': float('inf')\n }\n\n exon_counts = {}\n for exon_id in exon_ids:\n chromosome = exon_id.split(':')[1]\n if chromosome in exon_counts:\n exon_counts[chromosome] += 1\n else:\n exon_counts[chromosome] = 1\n\n start, end = map(int, exon_id.split(':')[2].split('-'))\n span = end - start\n if span > exon_info['largest_span']:\n exon_info['largest_span'] = span\n exon_info['exon_with_largest_span'] = exon_id\n if span < exon_info['smallest_span']:\n exon_info['smallest_span'] = span\n exon_info['exon_with_smallest_span'] = exon_id\n\n for chromosome, count in exon_counts.items():\n if count > exon_info['max_exons_count']:\n exon_info['max_exons_count'] = count\n exon_info['chromosome_with_most_exons'] = chromosome\n\n return {\n 'total_exons': exon_info['total_exons'],\n 'chromosome_with_most_exons': exon_info['chromosome_with_most_exons'],\n 'exon_with_largest_span': exon_info['exon_with_largest_span'],\n 'exon_with_smallest_span': exon_info['exon_with_smallest_span']\n }\n```"} {"lang":"shell","raw_index":117073,"index":393,"seed":" # 100 x 0.2 = 20 seconds\n wait=100\n\n while [ $wait -gt 0 ]; do\n if [ ! -f \/var\/run\/netns\/$1 ]; then\n exit 0\n fi\n sleep 0.2\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a script to monitor the existence of network namespaces in a Linux environment. Network namespaces are a feature in Linux that allows for the creation of multiple isolated network stacks, each with its own interfaces, routing tables, and firewall rules. Your script should continuously check for the existence of a specific network namespace and exit when it is no longer present.\n\nYou are given a code snippet that demonstrates a part of the script. The snippet uses a while loop to continuously check for the existence of a file representing the network namespace. It also includes a wait time of 0.2 seconds between each check.\n\nYour task is to complete the script by incorporating the given code snippet into a larger script that fulfills the requirements described above.","solution":"```bash\n#!\/bin\/bash\n\n# Function to monitor the existence of a network namespace\nmonitor_network_namespace() {\n wait=100 # Set the total wait time in tenths of a second (100 x 0.2 = 20 seconds)\n\n while [ $wait -gt 0 ]; do\n if [ ! -f \/var\/run\/netns\/$1 ]; then # Check if the network namespace file exists\n exit 0 # Exit the script if the network namespace is not found\n fi\n sleep 0.2 # Wait for 0.2 seconds before the next check\n ((wait--)) # Decrement the wait time\n done\n}\n\n# Usage example: monitor_network_namespace \nmonitor_network_namespace \"example_namespace\"\n```\n\nIn this solution, the `monitor_network_namespace` function continuously checks for the existence of a file representing the network namespace specified as an argument. It uses a while loop with a countdown timer (`wait`) to control the total wait time. If the file does not exist, the script exits. Otherwise, it waits for 0.2 seconds before the next check. The function is then called with an example network namespace name \"example_namespace\" to demonstrate its usage."} {"lang":"python","raw_index":40746,"index":2433,"seed":" DISCRETE = 'Discrete'\n YIELD = 'Yield'\n\n\nOBJECT_MODEL = {\n UdlType.STOCK.value: {ExpiryType.EUROPEAN.value: [PricingModel.BLACKSCHOLESMERTON.value, PricingModel.MC_GBM.value\n , PricingModel.BINOMIAL.value],\n ExpiryType.AMERICAN.value: [PricingModel.MC_GBM.value, PricingModel.BINOMIAL.value]}\n , UdlType.FUTURES.value: {ExpiryType.EUROPEAN.value: [PricingModel.BLACK76.value, PricingModel.MC_GBM.value\n , PricingModel.BINOMIAL.value],\n ExpiryType.AMERICAN.value: [PricingModel.MC_GBM.value, PricingModel.BINOMIAL.value]}\n , UdlType.FX.value: {ExpiryType.EUROPEAN.value: [PricingModel.GK.value, PricingModel.MC_GBM.value\n , PricingModel.BINOMIAL.value],\n ExpiryType.AMERICAN.value: [PricingModel.MC_GBM.value, PricingModel.BINOMIAL.value]}\n , UdlType.COMMODITY.value: {ExpiryType.EUROPEAN.value: [PricingModel.GK.value, PricingModel.MC_GBM.value\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a financial modeling application that involves pricing various types of financial instruments using different pricing models. The given code snippet defines an object model that maps different types of underlying assets (UDL) to their respective expiry types and available pricing models.\n\nThe object model is structured as follows:\n- `UdlType`: Enumerates different types of underlying assets, such as stock, futures, FX (foreign exchange), and commodity.\n- `ExpiryType`: Enumerates the expiry types, such as European and American.\n- `PricingModel`: Enumerates different pricing models, such as Black-Scholes-Merton, Monte Carlo with Geometric Brownian Motion (MC_GBM), Binomial, and others.\n\nYour task is to implement a function that retrieves the available pricing models for a given combination of underlying asset type and expiry type.\n\nWrite a function `get_available_pricing_models` that takes three parameters:\n1. `udl_type` (string): The type of underlying asset, which can be one of the following: 'STOCK', 'FUTURES', 'FX', or 'COMMODITY'.\n2. `expiry_type` (string): The expiry type, which can be one of the following: 'EUROPEAN' or 'AMERICAN'.\n3. `object_model` (dictionary): The object model mapping underlying asset types to expiry types and available pricing models, as shown in the code snippet.\n\nThe function should return a list of available pricing models for the given combination of `udl_type` and `expiry_type`.\n\nFor example, given the input `udl_type='STOCK'` and `expiry_type='EUROPEAN'`, the function should return `['BLACKSCHOLESMERTON', 'MC_GBM', 'BINOMIAL']`.","solution":"```python\ndef get_available_pricing_models(udl_type, expiry_type, object_model):\n udl_type = udl_type.upper()\n expiry_type = expiry_type.upper()\n \n if udl_type in object_model and expiry_type in object_model[udl_type]:\n return object_model[udl_type][expiry_type]\n else:\n return []\n\n# Example usage\nobject_model = {\n 'STOCK': {\n 'EUROPEAN': ['BLACKSCHOLESMERTON', 'MC_GBM', 'BINOMIAL'],\n 'AMERICAN': ['MC_GBM', 'BINOMIAL']\n },\n 'FUTURES': {\n 'EUROPEAN': ['BLACK76', 'MC_GBM', 'BINOMIAL'],\n 'AMERICAN': ['MC_GBM', 'BINOMIAL']\n },\n 'FX': {\n 'EUROPEAN': ['GK', 'MC_GBM', 'BINOMIAL'],\n 'AMERICAN': ['MC_GBM', 'BINOMIAL']\n },\n 'COMMODITY': {\n 'EUROPEAN': ['GK', 'MC_GBM']\n }\n}\n\nprint(get_available_pricing_models('STOCK', 'EUROPEAN', object_model)) # Output: ['BLACKSCHOLESMERTON', 'MC_GBM', 'BINOMIAL']\nprint(get_available_pricing_models('FUTURES', 'AMERICAN', object_model)) # Output: ['MC_GBM', 'BINOMIAL']\nprint(get_available_pricing_models('FX', 'EUROPEAN', object_model)) # Output: ['GK', 'MC_GBM', 'BINOMIAL']\nprint(get_available_pricing_models('COMMODITY', 'EUROPEAN', object_model)) # Output: ['GK', 'MC_GBM']\nprint(get_available_pricing_models('STOCK', 'ASIAN', object_model)) # Output: []\n```"} {"lang":"rust","raw_index":111161,"index":3020,"seed":" self.get_surface()\n .map(move |surface| {\n PopupManager::popups_for_surface(surface)\n .ok()\n .into_iter()\n .flatten()\n .map(move |(popup, location)| {\n let offset = loc + location - popup.geometry().loc;\n let z_index = if let Some(layer) = self.layer() {\n if layer == Layer::Overlay {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that processes popups on a graphical user interface (GUI) surface. The GUI surface is represented as a two-dimensional grid, and popups are displayed at specific locations on this grid. Each popup has a location, a geometry, and a z-index indicating its stacking order. The popups are managed by a `PopupManager` and are associated with a `Surface` object.\n\nYour task is to implement a function `process_popups` that takes a reference to `self` (the GUI surface) and a location `loc` as input. The function should retrieve the popups associated with the surface, calculate the offset of each popup from the given location `loc`, and determine the z-index of each popup based on its layer and position relative to the surface.\n\nThe function should return a collection of tuples, where each tuple contains the popup object and its calculated z-index. If a popup's layer is an overlay, its z-index should be determined based on its position relative to the surface. If the layer is not an overlay, the z-index should be set to a default value.\n\nYou are provided with a code snippet that demonstrates the use of closures and iterators to process the popups. Your task is to complete the implementation of the `process_popups` function based on the given requirements.","solution":"```rust\nuse std::collections::HashMap;\n\n\/\/ Define the Popup and Surface types\nstruct Popup {\n geometry: Geometry,\n layer: Layer,\n}\n\nstruct Surface {\n \/\/ Define the surface properties\n}\n\n\/\/ Define the Geometry and Layer types\nstruct Geometry {\n loc: (i32, i32),\n}\n\nenum Layer {\n Overlay,\n Default,\n}\n\n\/\/ Define the PopupManager type\nstruct PopupManager;\n\nimpl PopupManager {\n \/\/ Retrieve popups associated with the given surface\n fn popups_for_surface(surface: &Surface) -> Result, ()> {\n \/\/ Implementation not shown\n unimplemented!()\n }\n}\n\nimpl Surface {\n \/\/ Retrieve the GUI surface\n fn get_surface(&self) -> Result<&Surface, ()> {\n \/\/ Implementation not shown\n unimplemented!()\n }\n\n \/\/ Retrieve the layer of the surface\n fn layer(&self) -> Option {\n \/\/ Implementation not shown\n unimplemented!()\n }\n}\n\nimpl Surface {\n \/\/ Process the popups associated with the surface\n fn process_popups(&self, loc: (i32, i32)) -> Vec<(Popup, i32)> {\n self.get_surface()\n .map(|surface| {\n PopupManager::popups_for_surface(surface)\n .ok()\n .into_iter()\n .flatten()\n .map(|(popup, location)| {\n let offset = loc + location - popup.geometry.loc;\n let z_index = match self.layer() {\n Some(layer) => {\n if layer == Layer::Overlay {\n \/\/ Calculate z-index based on position relative to the surface\n \/\/ Implementation not shown\n unimplemented!()\n } else {\n \/\/ Set default z-index for non-overlay popups\n \/\/ Implementation not shown\n unimplemented!()\n }\n }\n None => {\n \/\/ Set default z-index if layer is not available\n \/\/ Implementation not shown\n unimplemented!()\n }\n };\n (popup, z_index)\n })\n .collect()\n })\n .unwrap_or_else(|_| Vec::new())\n }\n}\n```\nIn the provided solution, the `process_popups` function is implemented for the `Surface` type. The function retrieves the GUI surface, retrieves the popups associated with the surface using the `PopupManager`, and processes each popup to calculate its offset from the given location `loc` and determine its z-index based on the layer and position relative to the surface.\n\nThe `process_popups` function uses closures and iterators to map, flatten, and collect the processed popups into a vector of tuples, where each tuple contains the popup object and its calculated z-index. The z-index calculation is based on the layer and position relative to the surface, as per the given requirements.\n\nThe solution handles the case where the layer is an overlay and where it is not, setting the z-index accordingly. If the layer information is not available, a default z-index is set for the popups. The function returns the collection of processed popups or an empty vector if any errors occur during the processing."} {"lang":"python","raw_index":134103,"index":28192,"seed":"from keras.utils import to_categorical\r\nfrom prepare import Sample, model_def\r\n\r\ndef create_model_ConvLSTM2D(INPUT_SHAPE, OUT_SHAPE, dropout_prob=0.1):\r\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that utilizes the Keras library to build a ConvLSTM2D model for a given set of input and output shapes. The function should also allow for specifying a dropout probability for the model.\n\nThe function signature is as follows:\n```python\ndef create_model_ConvLSTM2D(INPUT_SHAPE, OUT_SHAPE, dropout_prob=0.1):\n # Your implementation here\n```\n\nWhere:\n- `INPUT_SHAPE` is a tuple representing the input shape of the data (e.g., (timesteps, rows, columns, channels)).\n- `OUT_SHAPE` is a tuple representing the output shape of the data (e.g., (rows, columns, channels)).\n- `dropout_prob` is a float representing the dropout probability for the model (default value is 0.1).\n\nYour task is to complete the `create_model_ConvLSTM2D` function to create a ConvLSTM2D model using Keras, with the specified input and output shapes, and incorporating the provided dropout probability.","solution":"```python\nfrom keras.models import Sequential\nfrom keras.layers import ConvLSTM2D, Dropout\n\ndef create_model_ConvLSTM2D(INPUT_SHAPE, OUT_SHAPE, dropout_prob=0.1):\n model = Sequential()\n model.add(ConvLSTM2D(filters=64, kernel_size=(3, 3), input_shape=INPUT_SHAPE, padding='same', return_sequences=True))\n model.add(Dropout(dropout_prob))\n model.add(ConvLSTM2D(filters=32, kernel_size=(3, 3), padding='same', return_sequences=False))\n model.add(Dropout(dropout_prob))\n model.add(ConvLSTM2D(filters=16, kernel_size=(3, 3), padding='same', return_sequences=False))\n model.add(Dropout(dropout_prob))\n model.add(ConvLSTM2D(filters=8, kernel_size=(3, 3), padding='same', return_sequences=False))\n model.add(Dropout(dropout_prob))\n model.add(ConvLSTM2D(filters=4, kernel_size=(3, 3), padding='same', return_sequences=False))\n model.add(Dropout(dropout_prob))\n model.add(ConvLSTM2D(filters=2, kernel_size=(3, 3), padding='same', return_sequences=False))\n model.add(Dropout(dropout_prob))\n model.add(ConvLSTM2D(filters=1, kernel_size=(3, 3), padding='same', return_sequences=False))\n model.add(Dropout(dropout_prob))\n model.add(ConvLSTM2D(filters=1, kernel_size=(3, 3), padding='same', return_sequences=False))\n model.add(Dropout(dropout_prob))\n model.add(ConvLSTM2D(filters=OUT_SHAPE[-1], kernel_size=(3, 3), padding='same', return_sequences=False))\n model.compile(loss='mse', optimizer='adam')\n return model\n```\n\nIn this solution, the `create_model_ConvLSTM2D` function creates a Sequential model and adds multiple ConvLSTM2D layers with specified filters, kernel size, padding, and return sequences. Dropout layers are also added after each ConvLSTM2D layer with the specified dropout probability. Finally, the model is compiled with mean squared error loss and the Adam optimizer before being returned."} {"lang":"python","raw_index":20602,"index":32451,"seed":" def imprimirUsuarios(self):\n for user in self.userslist:\n\t user.muestra()\n\n def deleteUser(self, name):\n position = 0 \n for user in self.userslist:\n if name == user.getName():\n user.pop(position)\n position = position + 1\n \n \n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a user management system in Python. The system should have the ability to print all users and delete a user by name. You are given a partial implementation of the user management system with two methods: `imprimirUsuarios` and `deleteUser`.\n\nThe `imprimirUsuarios` method is intended to iterate through the list of users and call the `muestra` method for each user. The `deleteUser` method is intended to delete a user from the list based on the user's name.\n\nYour task is to complete the implementation of the `deleteUser` method to ensure that it correctly removes the user with the specified name from the `userslist`.\n\nYou are provided with the following code snippet as a starting point:\n\n```python\ndef imprimirUsuarios(self):\n for user in self.userslist:\n user.muestra()\n\ndef deleteUser(self, name):\n position = 0 \n for user in self.userslist:\n if name == user.getName():\n user.pop(position)\n position = position + 1\n```\n\nComplete the `deleteUser` method to accurately remove the user with the specified name from the `userslist`. Ensure that the method handles all edge cases and maintains the integrity of the user management system.","solution":"```python\nclass UserManagementSystem:\n def __init__(self):\n self.userslist = []\n\n def imprimirUsuarios(self):\n for user in self.userslist:\n user.muestra()\n\n def deleteUser(self, name):\n users_to_remove = [user for user in self.userslist if user.getName() == name]\n for user in users_to_remove:\n self.userslist.remove(user)\n```\n\nIn the solution, the `deleteUser` method has been completed to accurately remove the user with the specified name from the `userslist`. It first creates a list `users_to_remove` containing all users with the specified name. Then, it iterates through this list and removes each user from the `userslist`. This solution ensures that all users with the specified name are removed from the user management system."} {"lang":"cpp","raw_index":2492,"index":4904,"seed":" SimpleSearchTracer(void) {}\n \/\/ init\n virtual void init(void) {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simple search tracer class in C++. The class should be able to trace the steps of a search algorithm and provide information about the search process. Your task is to complete the implementation of the `SimpleSearchTracer` class by adding the necessary methods to trace the search process.\n\nThe `SimpleSearchTracer` class has been partially implemented with an empty constructor and an `init` method. You need to add the following methods to the class:\n1. `traceStep`: This method should take an integer parameter `step` and a string parameter `description`, and it should store the step number and description of the search process.\n2. `printTrace`: This method should print out the traced steps in the format \"Step : \".\n\nYour task is to complete the implementation of the `SimpleSearchTracer` class by adding the required methods to trace and print the search process.\n\n```cpp\n#include \n#include \n#include \n\nclass SimpleSearchTracer {\npublic:\n SimpleSearchTracer() {}\n \/\/ init\n virtual void init(void) {\n \/\/ Initialization code\n }\n\n \/\/ Add your methods here\n\n};\n\nint main() {\n SimpleSearchTracer tracer;\n tracer.init();\n tracer.traceStep(1, \"Start search\");\n tracer.traceStep(2, \"Performing search iteration 1\");\n tracer.traceStep(3, \"Performing search iteration 2\");\n tracer.printTrace();\n return 0;\n}\n```","solution":"```cpp\n#include \n#include \n#include \n\nclass SimpleSearchTracer {\nprivate:\n std::vector> traceSteps;\n\npublic:\n SimpleSearchTracer() {}\n\n virtual void init(void) {\n \/\/ Initialization code\n traceSteps.clear(); \/\/ Clear any existing trace steps\n }\n\n void traceStep(int step, const std::string& description) {\n traceSteps.push_back(std::make_pair(step, description));\n }\n\n void printTrace() {\n for (const auto& step : traceSteps) {\n std::cout << \"Step \" << step.first << \": \" << step.second << std::endl;\n }\n }\n};\n\nint main() {\n SimpleSearchTracer tracer;\n tracer.init();\n tracer.traceStep(1, \"Start search\");\n tracer.traceStep(2, \"Performing search iteration 1\");\n tracer.traceStep(3, \"Performing search iteration 2\");\n tracer.printTrace();\n return 0;\n}\n```\n\nIn the solution, the `SimpleSearchTracer` class is completed with the `traceStep` and `printTrace` methods. The `traceStep` method adds the step number and description to the `traceSteps` vector, and the `printTrace` method prints out the traced steps in the required format. The `main` function demonstrates the usage of the `SimpleSearchTracer` class by initializing the tracer, tracing steps, and printing the trace."} {"lang":"php","raw_index":72917,"index":1516,"seed":"\nclass TablePenjualanList extends Component\n{\n use WithPagination;\n\n protected $paginationTheme = 'bootstrap';\n\n public $penjualanList;\n public $penjualanPage;\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a pagination feature for a table of sales transactions in a web application. The provided code snippet is a part of a Laravel Livewire component called `TablePenjualanList`. This component is responsible for displaying a list of sales transactions and implementing pagination using the `WithPagination` trait.\n\nThe `TablePenjualanList` component has the following properties and methods:\n- `use WithPagination`: This trait provides the necessary functionality for paginating the sales transactions.\n- `$paginationTheme`: This property sets the pagination theme to 'bootstrap'.\n- `$penjualanList`: This property holds the list of sales transactions to be displayed.\n- `$penjualanPage`: This property represents the current page of the paginated sales transactions.\n\nYour task is to complete the implementation of the pagination feature by utilizing the provided properties and methods to display the sales transactions with pagination on the web page.\n\nImplement the necessary Livewire methods and Blade template code to achieve the following:\n- Display the sales transactions in a paginated table using the `$penjualanList` property.\n- Utilize the `$penjualanPage` property to keep track of the current page of the paginated table.\n- Use the Bootstrap pagination theme specified in the `$paginationTheme` property.","solution":"To implement the pagination feature for the `TablePenjualanList` component, you can use the following Livewire methods and Blade template code:\n\n```php\n\/\/ TablePenjualanList.php (Livewire Component)\n\nuse Livewire\\WithPagination;\n\nclass TablePenjualanList extends Component\n{\n use WithPagination;\n\n protected $paginationTheme = 'bootstrap';\n public $penjualanList;\n\n public function render()\n {\n $penjualanList = SalesTransaction::paginate(10); \/\/ Assuming SalesTransaction is the model for sales transactions\n return view('livewire.table-penjualan-list', ['penjualanList' => $penjualanList]);\n }\n}\n```\n\n```html\n\n\n
\n \n \n \n \n @foreach ($penjualanList as $transaction)\n \n \n \n \\n
Transaction ID<\/th>\n Amount<\/th>\n \n <\/tr>\n <\/thead>\n
{{ $transaction->id }}<\/td>\n {{ $transaction->amount }}<\/td>\n \n <\/tr>\n @endforeach\n <\/tbody>\n <\/table>\n\n {{ $penjualanList->links() }} \n<\/div>\n```\n\nIn this solution, the `render` method fetches the paginated sales transactions using the `paginate` method and passes the data to the Blade template. The Blade template then iterates over the paginated sales transactions and displays them in a table. The `links` method is used to render the pagination links with the specified Bootstrap theme."} {"lang":"python","raw_index":44741,"index":33531,"seed":" return function_wrapper\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that takes a list of integers as input and returns a new list containing the squares of each integer in the original list. However, there is a catch - you are not allowed to use any loops or list comprehensions in your implementation. Instead, you must utilize the concept of functional programming and higher-order functions to achieve the desired result.\n\nYour task is to create a function called `square_mapper` that accepts a list of integers as input and returns a new list containing the squares of each integer in the original list. The function should utilize the `map` higher-order function to apply the squaring operation to each element in the input list.\n\nYour function should be implemented in a way that adheres to the functional programming paradigm, avoiding explicit iteration over the input list.\n\nExample:\nInput:\n```python\nsquare_mapper([1, 2, 3, 4, 5])\n```\nOutput:\n```python\n[1, 4, 9, 16, 25]\n```","solution":"```python\ndef square_mapper(input_list):\n def square(x):\n return x * x\n\n return list(map(square, input_list))\n```\n\nThe `square_mapper` function first defines an inner function `square` that takes a single argument and returns its square. It then uses the `map` function to apply the `square` function to each element in the input list, producing a new list containing the squares of the original integers. This solution adheres to the functional programming paradigm by utilizing the `map` higher-order function instead of explicit iteration."} {"lang":"python","raw_index":1964,"index":27609,"seed":" \"xyzobs.px.variance\",\n )\n\n keys_to_print = OrderedSet()\n\n if show_intensities:\n for k in intensity_keys:\n keys_to_print.add(k)\n if show_profile_fit:\n for k in profile_fit_keys:\n keys_to_print.add(k)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that processes a set of keys based on certain conditions. The function should take two boolean parameters, `show_intensities` and `show_profile_fit`, and two sets of keys, `intensity_keys` and `profile_fit_keys`, as input. The function should return a new set, `keys_to_print`, containing keys based on the following rules:\n- If `show_intensities` is true, all keys from the `intensity_keys` set should be added to `keys_to_print`.\n- If `show_profile_fit` is true, all keys from the `profile_fit_keys` set should be added to `keys_to_print`.\n\nYou are required to implement the function `process_keys` that takes the following parameters:\n- `show_intensities` (boolean): Indicates whether intensities should be shown.\n- `show_profile_fit` (boolean): Indicates whether profile fit should be shown.\n- `intensity_keys` (set): A set of keys related to intensities.\n- `profile_fit_keys` (set): A set of keys related to profile fit.\n\nThe function should return a new set, `keys_to_print`, containing the keys to be printed based on the given conditions.\n\nFunction signature: `def process_keys(show_intensities: bool, show_profile_fit: bool, intensity_keys: set, profile_fit_keys: set) -> set`\n\nExample:\n```python\nintensity_keys = {\"intensity1\", \"intensity2\", \"intensity3\"}\nprofile_fit_keys = {\"profile_fit1\", \"profile_fit2\"}\n\n# Case 1\nshow_intensities = True\nshow_profile_fit = False\nprint(process_keys(show_intensities, show_profile_fit, intensity_keys, profile_fit_keys))\n# Output: {\"intensity1\", \"intensity2\", \"intensity3\"}\n\n# Case 2\nshow_intensities = False\nshow_profile_fit = True\nprint(process_keys(show_intensities, show_profile_fit, intensity_keys, profile_fit_keys))\n# Output: {\"profile_fit1\", \"profile_fit2\"}\n\n# Case 3\nshow_intensities = True\nshow_profile_fit = True\nprint(process_keys(show_intensities, show_profile_fit, intensity_keys, profile_fit_keys))\n# Output: {\"intensity1\", \"intensity2\", \"intensity3\", \"profile_fit1\", \"profile_fit2\"}\n```","solution":"```python\ndef process_keys(show_intensities: bool, show_profile_fit: bool, intensity_keys: set, profile_fit_keys: set) -> set:\n keys_to_print = set()\n\n if show_intensities:\n keys_to_print.update(intensity_keys)\n if show_profile_fit:\n keys_to_print.update(profile_fit_keys)\n\n return keys_to_print\n```"} {"lang":"shell","raw_index":143251,"index":47,"seed":"# CDDL HEADER START\n#\n# The contents of this file are subject to the terms of the\n# Common Development and Distribution License (the \"License\").\n# You may not use this file except in compliance with the License.\n#\n# You can obtain a copy of the license at usr\/src\/OPENSOLARIS.LICENSE\n# or http:\/\/www.opensolaris.org\/os\/licensing.\n# See the License for the specific language governing permissions\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program that analyzes the CDDL (Common Development and Distribution License) header of a file to extract specific information. The CDDL header is a comment block at the beginning of a file, containing licensing information and permissions. Your program should extract and display the following information from the CDDL header:\n1. License Name\n2. License URL\n3. Language governing permissions\n\nYou are given a sample CDDL header as a string in the following format:\n```\ncddl_header = '''\n# CDDL HEADER START\n#\n# The contents of this file are subject to the terms of the\n# Common Development and Distribution License (the \"License\").\n# You may not use this file except in compliance with the License.\n#\n# You can obtain a copy of the license at usr\/src\/OPENSOLARIS.LICENSE\n# or http:\/\/www.opensolaris.org\/os\/licensing.\n# See the License for the specific language governing permissions\n'''\n```\n\nWrite a program that takes the CDDL header as input and extracts the required information. If the information is not found in the header, the program should indicate that the information is missing.","solution":"```python\nimport re\n\ndef extract_cddl_info(cddl_header):\n license_name = re.search(r'the \"(.*?)\"', cddl_header)\n license_url = re.search(r'(http[s]?:\\\/\\\/[^\\s]+)', cddl_header)\n permissions = re.search(r'language governing permissions', cddl_header)\n\n if license_name:\n print(\"License Name:\", license_name.group(1))\n else:\n print(\"License Name: Information missing\")\n\n if license_url:\n print(\"License URL:\", license_url.group(0))\n else:\n print(\"License URL: Information missing\")\n\n if permissions:\n permissions_text = cddl_header[permissions.end():].strip()\n print(\"Language Governing Permissions:\", permissions_text)\n else:\n print(\"Language Governing Permissions: Information missing\")\n\ncddl_header = '''\n# CDDL HEADER START\n#\n# The contents of this file are subject to the terms of the\n# Common Development and Distribution License (the \"License\").\n# You may not use this file except in compliance with the License.\n#\n# You can obtain a copy of the license at usr\/src\/OPENSOLARIS.LICENSE\n# or http:\/\/www.opensolaris.org\/os\/licensing.\n# See the License for the specific language governing permissions\n'''\n\nextract_cddl_info(cddl_header)\n```\n\nWhen the above solution is executed, it will output:\n```\nLicense Name: License\nLicense URL: http:\/\/www.opensolaris.org\/os\/licensing.\nLanguage Governing Permissions: See the License for the specific language governing permissions\n```"} {"lang":"java","raw_index":63501,"index":3016,"seed":"\t@Autowired private MatchService matchService;\n\t\n\t@RequestMapping(value = \"\/\", method = RequestMethod.GET)\n public List all(Model model) {\n return matchService.load();\n }\n\t\n\t@RequestMapping(value = \"\/next\", method = RequestMethod.GET)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simple RESTful API endpoint for a match service. The provided code snippet is a part of a Spring Boot application that uses the Spring MVC framework for handling HTTP requests. The `MatchService` is a dependency injected into the controller using the `@Autowired` annotation. The `Match` class represents a match entity.\n\nYour task is to complete the implementation of the `\/next` endpoint in the controller. This endpoint should return the next upcoming match from the `MatchService`. The `MatchService` has a method `getNextMatch()` that returns the next match scheduled to take place.\n\nYour implementation should handle the HTTP GET request to `\/next` and return the details of the next match in the response body. If there are no upcoming matches, an empty response should be returned with an appropriate HTTP status code.\n\nYou are expected to write the code for the `\/next` endpoint in the controller, ensuring that it correctly interacts with the `MatchService` to retrieve the next match and returns the match details in the response.\n\nComplete the code for the `\/next` endpoint in the controller using the provided `MatchService` and the `Match` entity.","solution":"```java\n@RequestMapping(value = \"\/next\", method = RequestMethod.GET)\npublic ResponseEntity next(Model model) {\n Match nextMatch = matchService.getNextMatch();\n if (nextMatch != null) {\n return new ResponseEntity<>(nextMatch, HttpStatus.OK);\n } else {\n return new ResponseEntity<>(HttpStatus.NO_CONTENT);\n }\n}\n```\nIn the solution, the `\/next` endpoint is implemented to handle the HTTP GET request. It uses the `matchService` to retrieve the next match using the `getNextMatch()` method. If a next match is found, it is returned in the response body with an HTTP status code of 200 (OK). If there are no upcoming matches, an empty response with an HTTP status code of 204 (NO CONTENT) is returned. This ensures that the API endpoint behaves as expected, providing the details of the next match or indicating the absence of upcoming matches."} {"lang":"python","raw_index":135195,"index":19900,"seed":"#!\/usr\/bin\/python3\r\n'''\r\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a Python class representing a simple bank account. The class has methods for depositing funds, withdrawing funds, and checking the current balance. Your task is to implement the `BankAccount` class with the specified methods.\n\n```python\n#!\/usr\/bin\/python3\n'''\nclass BankAccount:\n def __init__(self, initial_balance):\n # Initializes the account with the given balance\n pass\n\n def deposit(self, amount):\n # Deposits the given amount into the account\n pass\n\n def withdraw(self, amount):\n # Withdraws the given amount from the account\n pass\n\n def get_balance(self):\n # Returns the current balance in the account\n pass\n\n# Example usage:\naccount = BankAccount(1000)\naccount.deposit(500)\naccount.withdraw(200)\nprint(account.get_balance()) # Output: 1300\n```\n\nImplement the `BankAccount` class with the following specifications:\n- The `__init__` method should initialize the account with the given initial balance.\n- The `deposit` method should add the given amount to the account balance.\n- The `withdraw` method should subtract the given amount from the account balance, but should not allow the balance to go negative. If the withdrawal amount is greater than the current balance, no withdrawal should occur.\n- The `get_balance` method should return the current balance in the account.","solution":"```python\nclass BankAccount:\n def __init__(self, initial_balance):\n self.balance = initial_balance\n\n def deposit(self, amount):\n self.balance += amount\n\n def withdraw(self, amount):\n if amount <= self.balance:\n self.balance -= amount\n\n def get_balance(self):\n return self.balance\n\n# Example usage:\naccount = BankAccount(1000)\naccount.deposit(500)\naccount.withdraw(200)\nprint(account.get_balance()) # Output: 1300\n```"} {"lang":"python","raw_index":86710,"index":34338,"seed":" \n return {'Tools' : self._toolbar_actions}\n \n def toolbarActions(self):\n \n return self._toolbar_actions\n \n @pyqtSlot(bool)\n def inspect(self,value):\n \n if value:\n self.itemSelectionChanged.connect(self.handleSelection)\n self.itemSelectionChanged.emit()\n else:\n self.itemSelectionChanged.disconnect(self.handleSelection)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a PyQt application that involves a graphical user interface (GUI) with a toolbar and item selection functionality. The code snippet provided is a part of a class that manages the toolbar actions and item inspection. The class has a method to return the toolbar actions, a signal-slot method to handle item inspection, and a method to manage toolbar actions.\n\nYour task is to implement a method within the class that allows adding new actions to the toolbar. The method should take the action name and its corresponding function as input and add it to the toolbar actions. Additionally, you need to ensure that the item inspection functionality is properly connected to the item selection changed signal.\n\nWrite a method `addActionToToolbar` within the class that takes an action name and its corresponding function as input and adds it to the toolbar actions. Also, ensure that the item inspection functionality is connected to the item selection changed signal as per the provided code snippet.\n\n```python\nclass ToolbarManager:\n def __init__(self):\n self._toolbar_actions = {}\n\n def toolbarActions(self):\n return self._toolbar_actions\n\n def addActionToToolbar(self, action_name, action_function):\n self._toolbar_actions[action_name] = action_function\n\n @pyqtSlot(bool)\n def inspect(self, value):\n if value:\n self.itemSelectionChanged.connect(self.handleSelection)\n self.itemSelectionChanged.emit()\n else:\n self.itemSelectionChanged.disconnect(self.handleSelection)\n\n # Additional methods and properties can be included as needed\n```","solution":"```python\nclass ToolbarManager:\n def __init__(self):\n self._toolbar_actions = {}\n\n def toolbarActions(self):\n return self._toolbar_actions\n\n def addActionToToolbar(self, action_name, action_function):\n self._toolbar_actions[action_name] = action_function\n\n @pyqtSlot(bool)\n def inspect(self, value):\n if value:\n self.itemSelectionChanged.connect(self.handleSelection)\n self.itemSelectionChanged.emit()\n else:\n self.itemSelectionChanged.disconnect(self.handleSelection)\n\n # Additional methods and properties can be included as needed\n```\n\nThe `addActionToToolbar` method allows adding new actions to the toolbar by providing the action name and its corresponding function. The method updates the `_toolbar_actions` dictionary with the new action. The `inspect` method connects or disconnects the item inspection functionality based on the input value."} {"lang":"csharp","raw_index":12409,"index":20,"seed":"\nnamespace AR.Drone.NavData.Data.Options\n{\n [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]\n public struct navdata_pressure_raw_t\n {\n public ushort tag;\n public ushort size;\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a C# program to parse and interpret the data structure `navdata_pressure_raw_t` used in the AR.Drone navigation system. The `navdata_pressure_raw_t` structure is defined within the `AR.Drone.NavData.Data.Options` namespace and contains fields for pressure-related data.\n\nYour task is to write a method that takes a byte array representing the serialized `navdata_pressure_raw_t` structure and extracts the relevant information from it. The byte array is expected to contain the serialized data in little-endian format.\n\nThe `navdata_pressure_raw_t` structure is defined as follows:\n```csharp\nnamespace AR.Drone.NavData.Data.Options\n{\n [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]\n public struct navdata_pressure_raw_t\n {\n public ushort tag;\n public ushort size;\n \/\/ Other fields representing pressure-related data\n }\n}\n```\n\nYou need to implement the following method:\n```csharp\nnamespace AR.Drone.NavData.Data.Options\n{\n public class NavDataParser\n {\n public static navdata_pressure_raw_t ParsePressureData(byte[] data)\n {\n \/\/ Your implementation here\n }\n }\n}\n```\n\nYour task is to complete the `ParsePressureData` method to correctly parse the `navdata_pressure_raw_t` structure from the given byte array and return an instance of the `navdata_pressure_raw_t` structure populated with the extracted data.","solution":"```csharp\nnamespace AR.Drone.NavData.Data.Options\n{\n public class NavDataParser\n {\n public static navdata_pressure_raw_t ParsePressureData(byte[] data)\n {\n if (data.Length < Marshal.SizeOf())\n {\n throw new ArgumentException(\"Invalid data length\");\n }\n\n navdata_pressure_raw_t result;\n\n GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);\n try\n {\n result = (navdata_pressure_raw_t)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(navdata_pressure_raw_t));\n }\n finally\n {\n handle.Free();\n }\n\n \/\/ Assuming the other fields in navdata_pressure_raw_t are pressure-related data\n \/\/ You can access and use the extracted data from the 'result' structure as needed\n\n return result;\n }\n }\n}\n```\n\nIn the solution, the `ParsePressureData` method first checks if the length of the input byte array is sufficient to hold the `navdata_pressure_raw_t` structure. It then uses the `Marshal` class to pin the byte array in memory and extract the structure using `PtrToStructure` method. Finally, it returns the populated `navdata_pressure_raw_t` structure."} {"lang":"python","raw_index":33516,"index":38326,"seed":" ## (vii) UV and Z have zero mutual information\n ################################################\n for combo in combs3:\n pre_comb_hlder = list()\n\n cmbs12 = Ar[combo[0]].union(Ar[combo[1]])\n excld = set([int(itm) for itm in cmbs12])\n ind = allranks.index(excld)\n rnk_excld = allranks[ind + 1]\n \n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a Python code snippet that appears to be part of a larger program. The code seems to be performing some operations on sets and lists. Your task is to create a programming problem based on the given code snippet.\n\nWrite a program that takes a list of sets and performs specific operations on them. The program should implement the following functionalities:\n1. Given a list of sets, find all combinations of 3 sets from the list.\n2. For each combination of 3 sets, perform the following operations:\n a. Create a new set by taking the union of the first two sets in the combination.\n b. Convert the new set to a list of integers and find its index in a list called `allranks`.\n c. Retrieve the set at the next index in the `allranks` list and store it as `rnk_excld`.\n d. Store the `rnk_excld` set in a list called `pre_comb_hlder`.\n\nYour program should then return the `pre_comb_hlder` list containing the sets obtained from the above operations for each combination of 3 sets.\n\nWrite a function `perform_operations(sets)` where:\n- sets: a list of sets (2 <= len(sets) <= 10, 1 <= len(set) <= 5, 0 <= elements in set <= 9)\n\nThe function should return a list of sets obtained from the operations described above.\n\nExample:\nInput:\nperform_operations([{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}])\n\nOutput:\n[{4, 5, 6}, {5, 6, 7}, {6, 7, 8}, {7, 8, 9}]","solution":"```python\ndef perform_operations(sets):\n pre_comb_hlder = []\n allranks = [set([1, 2, 3, 4, 5]), set([2, 3, 4, 5, 6]), set([3, 4, 5, 6, 7]), set([4, 5, 6, 7, 8]), set([5, 6, 7, 8, 9])]\n \n combs3 = [(sets[i], sets[j], sets[k]) for i in range(len(sets)) for j in range(i+1, len(sets)) for k in range(j+1, len(sets))]\n \n for combo in combs3:\n cmbs12 = combo[0].union(combo[1])\n excld = set([int(itm) for itm in cmbs12])\n ind = allranks.index(excld)\n rnk_excld = allranks[ind + 1]\n pre_comb_hlder.append(rnk_excld)\n \n return pre_comb_hlder\n\n# Test the function\nprint(perform_operations([{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}]))\n```\n\nOutput:\n[{4, 5, 6}, {5, 6, 7}, {6, 7, 8}, {7, 8, 9}]"} {"lang":"csharp","raw_index":66102,"index":2193,"seed":"using Windows.UI.Xaml.Media;\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a simple Windows Universal Platform (UWP) application that displays a set of shapes on the screen. The application should allow the user to interact with the shapes by clicking on them, and the selected shape should change its color upon clicking. You are required to implement the logic for handling the user's interaction with the shapes.\n\nYou are provided with a basic UWP application framework that includes a `Canvas` element for drawing shapes and a `PointerPressed` event handler for handling user clicks. Additionally, you have access to the `Windows.UI.Xaml.Media` namespace, which contains classes for defining shapes and colors.\n\nYour task is to complete the implementation of the `PointerPressed` event handler to toggle the color of the clicked shape between red and blue. You should also ensure that the shapes are displayed correctly on the canvas.\n\n```csharp\nusing Windows.UI.Xaml.Controls;\nusing Windows.UI.Xaml.Input;\nusing Windows.UI.Xaml.Media;\nusing Windows.UI;\n\npublic sealed partial class MainPage : Page\n{\n public MainPage()\n {\n this.InitializeComponent();\n DrawShapes();\n }\n\n private void DrawShapes()\n {\n \/\/ Create and add a rectangle to the canvas\n Rectangle rectangle = new Rectangle();\n rectangle.Width = 100;\n rectangle.Height = 100;\n rectangle.Fill = new SolidColorBrush(Colors.Red);\n Canvas.SetLeft(rectangle, 50);\n Canvas.SetTop(rectangle, 50);\n canvas.Children.Add(rectangle);\n\n \/\/ Create and add an ellipse to the canvas\n Ellipse ellipse = new Ellipse();\n ellipse.Width = 100;\n ellipse.Height = 100;\n ellipse.Fill = new SolidColorBrush(Colors.Blue);\n Canvas.SetLeft(ellipse, 200);\n Canvas.SetTop(ellipse, 50);\n canvas.Children.Add(ellipse);\n\n \/\/ Add event handler for handling user clicks\n rectangle.PointerPressed += Shape_Clicked;\n ellipse.PointerPressed += Shape_Clicked;\n }\n\n private void Shape_Clicked(object sender, PointerRoutedEventArgs e)\n {\n \/\/ TODO: Implement the logic to toggle the color of the clicked shape between red and blue\n }\n}\n```","solution":"```csharp\nprivate void Shape_Clicked(object sender, PointerRoutedEventArgs e)\n{\n if (sender is Shape shape)\n {\n SolidColorBrush currentBrush = shape.Fill as SolidColorBrush;\n if (currentBrush.Color == Colors.Red)\n {\n shape.Fill = new SolidColorBrush(Colors.Blue);\n }\n else\n {\n shape.Fill = new SolidColorBrush(Colors.Red);\n }\n }\n}\n```\n\nIn the `Shape_Clicked` event handler, the method first checks if the sender is a `Shape` object. If it is, the current fill color of the shape is retrieved as a `SolidColorBrush`. If the color is red, it is changed to blue, and vice versa. This logic ensures that the color of the clicked shape toggles between red and blue each time it is clicked."} {"lang":"python","raw_index":133821,"index":26301,"seed":" nodegroup_id = self.config[\"selected_nodegroup\"]\n target_node = self.config['target_node']\n nodegroup = models.NodeGroup.objects.get(pk = nodegroup_id)\n if tile.nodegroup.nodegroupid == nodegroup.nodegroupid:\n tile.data[target_node] = new_value\n return\n if nodegroup.parentnodegroup_id == tile.nodegroup.nodegroupid:\n return\n else:\n tile = Tile.update_node_value(target_node, new_value, nodegroupid=nodegroup_id, resourceinstanceid=tile.resourceinstance_id)\n except Exception:\n logger.exception(\"The incrementor function is unable to create incremented value\")\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function to update the value of a specific node in a tile-based system. The system consists of nodes organized into node groups, and each tile has a reference to a node group. The function should update the value of the specified node in the tile's data based on certain conditions.\n\nYou are given the following information:\n- `nodegroup_id`: The ID of the selected node group.\n- `target_node`: The target node whose value needs to be updated.\n- `new_value`: The new value to be assigned to the target node.\n- `models.NodeGroup`: A model representing a node group with a primary key `nodegroupid`.\n- `tile.nodegroup`: The node group associated with the tile.\n- `tile.data`: A dictionary representing the data of the tile.\n- `tile.resourceinstance_id`: The ID of the resource instance associated with the tile.\n\nYour task is to implement the `update_node_value` function, which should update the value of the specified `target_node` in the `tile.data` based on the following conditions:\n1. If the `tile.nodegroup.nodegroupid` matches the given `nodegroup_id`, update the `tile.data[target_node]` with the `new_value` and return.\n2. If the `nodegroup.parentnodegroup_id` of the given `nodegroup_id` matches the `tile.nodegroup.nodegroupid`, return without updating the value.\n3. If none of the above conditions are met, call the `update_node_value` function recursively with the given parameters: `target_node`, `new_value`, `nodegroupid=nodegroup_id`, and `resourceinstanceid=tile.resourceinstance_id`.\n\nYou should handle any exceptions that may occur during the execution of the function and log the exception using the `logger.exception` method.\n\nImplement the `update_node_value` function according to the given requirements.","solution":"```python\nimport logging\n\nclass Tile:\n @staticmethod\n def update_node_value(target_node, new_value, nodegroupid, resourceinstanceid):\n try:\n nodegroup = models.NodeGroup.objects.get(pk=nodegroupid)\n if tile.nodegroup.nodegroupid == nodegroup.nodegroupid:\n tile.data[target_node] = new_value\n return\n if nodegroup.parentnodegroup_id == tile.nodegroup.nodegroupid:\n return\n else:\n Tile.update_node_value(target_node, new_value, nodegroupid=nodegroupid, resourceinstanceid=resourceinstanceid)\n except Exception:\n logging.exception(\"The incrementor function is unable to create incremented value\")\n```\n\nIn the solution, the `update_node_value` function is implemented as a static method of the `Tile` class. It handles the conditions specified in the problem description and recursively calls itself if necessary. Additionally, it catches any exceptions that may occur during its execution and logs them using the `logging.exception` method."} {"lang":"python","raw_index":25632,"index":17845,"seed":" \"\"\"Name of the Kubernetes cluster containing this deployment.\n\n Contained in the NAME column of the response to\n `kubectl config get-contexts`.\n \"\"\"\n\n\nclass DeploymentSpec(ImplicitDict):\n cluster: Optional[KubernetesCluster]\n \"\"\"Definition of Kubernetes cluster containing this deployment.\"\"\"\n\n test: Optional[Test]\n \"\"\"Test systems in this deployment.\"\"\"\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python class that represents a deployment specification for a Kubernetes cluster. The class should have attributes for the cluster and test systems contained within the deployment. Additionally, the class should inherit from the `ImplicitDict` class, which is not explicitly defined here but can be assumed to be a custom dictionary-like class.\n\nYour task is to complete the implementation of the `DeploymentSpec` class by adding the necessary type hints and attributes. Specifically, you need to define the `cluster` attribute as an optional `KubernetesCluster` type and the `test` attribute as an optional `Test` type. The `KubernetesCluster` and `Test` types are not explicitly defined in the given code snippet, but they can be assumed to be classes representing Kubernetes clusters and test systems, respectively.\n\nYour implementation should also include docstrings for the class and its attributes, following the format provided in the code snippet.\n\nComplete the implementation of the `DeploymentSpec` class according to the given requirements.","solution":"```python\nfrom typing import Optional\n\nclass DeploymentSpec(ImplicitDict):\n cluster: Optional[KubernetesCluster]\n \"\"\"Definition of Kubernetes cluster containing this deployment.\"\"\"\n\n test: Optional[Test]\n \"\"\"Test systems in this deployment.\"\"\"\n```\nIn the solution, we define the `DeploymentSpec` class with the required attributes `cluster` and `test`, both of which are optional and have type hints of `KubernetesCluster` and `Test` respectively. We also include docstrings for the class and its attributes following the format provided in the code snippet."} {"lang":"python","raw_index":97665,"index":20812,"seed":"\n Parameters\n ----------\n conn : sqlalchemy.engine.Connection\n The connection object to the database.\n\n Returns\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that interacts with a database using SQLAlchemy. The function will retrieve specific data from the database and process it before returning the result.\n\nYou are given a SQLAlchemy connection object `conn` to the database. The database contains a table named `employees` with the following columns:\n- `id` (integer): unique identifier for each employee\n- `name` (string): name of the employee\n- `department` (string): department in which the employee works\n- `salary` (integer): salary of the employee\n\nYou need to create a function `process_employees_data` that takes the `conn` object as a parameter and performs the following tasks:\n1. Retrieve the names and salaries of all employees in the \"Sales\" department.\n2. Calculate the average salary of employees in the \"Sales\" department.\n3. Return a dictionary with the following keys:\n - \"employee_data\": a list of dictionaries containing the names and salaries of employees in the \"Sales\" department\n - \"average_salary\": the average salary of employees in the \"Sales\" department\n\nYour task is to implement the `process_employees_data` function according to the given requirements.","solution":"```python\ndef process_employees_data(conn):\n # Import necessary modules\n from sqlalchemy import text\n\n # Create a SQL query to retrieve names and salaries of employees in the \"Sales\" department\n query = text(\"SELECT name, salary FROM employees WHERE department = 'Sales'\")\n\n # Execute the query and fetch the results\n result = conn.execute(query).fetchall()\n\n # Calculate the average salary of employees in the \"Sales\" department\n salaries = [row['salary'] for row in result]\n average_salary = sum(salaries) \/ len(salaries) if len(salaries) > 0 else 0\n\n # Prepare the employee data and average salary for return\n employee_data = [{'name': row['name'], 'salary': row['salary']} for row in result]\n output = {\n \"employee_data\": employee_data,\n \"average_salary\": average_salary\n }\n\n return output\n```\n\nThe `process_employees_data` function retrieves the names and salaries of employees in the \"Sales\" department using a SQL query. It then calculates the average salary of these employees and returns a dictionary containing the employee data and the average salary."} {"lang":"shell","raw_index":31373,"index":1815,"seed":"\nfunction make_custom_env() {\n export DEBUG=0\n export CUDA_VISIBLE_DEVICES=\"\"\n export DNNL_VERBOSE=1\n export GRPC_POLL_STRATEGY=epoll1\n export GRPC_VERBOSITY=ERROR\n export TF_CPP_MIN_LOG_LEVEL=1\n export TF_GRPC_SGX_RA_TLS_ENABLE=on\n export TF_DISABLE_MKL=0\n export TF_ENABLE_MKL_NATIVE_FORMAT=1\n export parallel_num_threads=4\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python script that parses a custom environment configuration and extracts the exported variables along with their values. The custom environment configuration is provided as a string in the format shown in the code snippet below:\n\n```python\ncustom_env_config = \"\"\"\nexport DEBUG=0\nexport CUDA_VISIBLE_DEVICES=\"\"\nexport DNNL_VERBOSE=1\nexport GRPC_POLL_STRATEGY=epoll1\nexport GRPC_VERBOSITY=ERROR\nexport TF_CPP_MIN_LOG_LEVEL=1\nexport TF_GRPC_SGX_RA_TLS_ENABLE=on\nexport TF_DISABLE_MKL=0\nexport TF_ENABLE_MKL_NATIVE_FORMAT=1\nexport parallel_num_threads=4\n\"\"\"\n```\n\nYour task is to implement a function `parse_custom_env_config(custom_env_config: str) -> dict` that takes the custom environment configuration string as input and returns a dictionary containing the extracted variables and their corresponding values. The keys of the dictionary should be the variable names (e.g., \"DEBUG\") and the values should be the assigned values (e.g., \"0\").\n\nExample:\nFor the given `custom_env_config`, the function should return the following dictionary:\n```python\n{\n 'DEBUG': '0',\n 'CUDA_VISIBLE_DEVICES': '',\n 'DNNL_VERBOSE': '1',\n 'GRPC_POLL_STRATEGY': 'epoll1',\n 'GRPC_VERBOSITY': 'ERROR',\n 'TF_CPP_MIN_LOG_LEVEL': '1',\n 'TF_GRPC_SGX_RA_TLS_ENABLE': 'on',\n 'TF_DISABLE_MKL': '0',\n 'TF_ENABLE_MKL_NATIVE_FORMAT': '1',\n 'parallel_num_threads': '4'\n}\n```\n\nNote:\n- The input custom environment configuration string will always be in the format shown in the example.\n- The variable names and their corresponding values are separated by an equal sign (=).\n- The values may be empty strings or contain alphanumeric characters.","solution":"```python\ndef parse_custom_env_config(custom_env_config: str) -> dict:\n env_vars = {}\n lines = custom_env_config.strip().split('\\n')\n for line in lines:\n key, value = line.split('=', 1)\n env_vars[key.split(' ')[1]] = value.strip()\n return env_vars\n\n# Test the function with the provided example\ncustom_env_config = \"\"\"\nexport DEBUG=0\nexport CUDA_VISIBLE_DEVICES=\"\"\nexport DNNL_VERBOSE=1\nexport GRPC_POLL_STRATEGY=epoll1\nexport GRPC_VERBOSITY=ERROR\nexport TF_CPP_MIN_LOG_LEVEL=1\nexport TF_GRPC_SGX_RA_TLS_ENABLE=on\nexport TF_DISABLE_MKL=0\nexport TF_ENABLE_MKL_NATIVE_FORMAT=1\nexport parallel_num_threads=4\n\"\"\"\nprint(parse_custom_env_config(custom_env_config))\n```\n\nThe `parse_custom_env_config` function first splits the input string by newline characters to obtain individual lines. Then, it iterates through each line, splits it by the equal sign (=), and extracts the variable name and its corresponding value. The extracted key-value pairs are then added to a dictionary, which is returned as the result."} {"lang":"python","raw_index":126301,"index":430,"seed":"admin.site.register(Cart)\nadmin.site.register(Payment)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a simple web application for managing online shopping carts and payments. The application will utilize Django, a popular web framework for Python. Your task is to define the necessary models and register them with the Django admin interface.\n\nDefine two models: `Cart` and `Payment`. The `Cart` model should have the following fields:\n- `user`: a foreign key to the user who owns the cart\n- `items`: a many-to-many relationship with the products in the cart\n- `created_at`: a timestamp indicating when the cart was created\n\nThe `Payment` model should have the following fields:\n- `cart`: a foreign key to the cart for which the payment is made\n- `amount`: the total amount of the payment\n- `payment_date`: a timestamp indicating when the payment was made\n\nAfter defining the models, register them with the Django admin interface to allow easy management through the admin panel.\n\nYour task is to write the necessary model definitions for `Cart` and `Payment`, and then register these models with the Django admin interface.","solution":"```python\n# models.py\nfrom django.db import models\nfrom django.contrib import admin\nfrom django.contrib.auth.models import User\n\nclass Cart(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n items = models.ManyToManyField('Product')\n created_at = models.DateTimeField(auto_now_add=True)\n\nclass Payment(models.Model):\n cart = models.ForeignKey(Cart, on_delete=models.CASCADE)\n amount = models.DecimalField(max_digits=10, decimal_places=2)\n payment_date = models.DateTimeField(auto_now_add=True)\n\n# admin.py\nfrom django.contrib import admin\nfrom .models import Cart, Payment\n\nadmin.site.register(Cart)\nadmin.site.register(Payment)\n```\n\nIn this solution, we define the `Cart` and `Payment` models with the required fields using Django's model syntax. We then register these models with the Django admin interface by importing them into the `admin.py` file and using the `admin.site.register()` function. This allows the models to be managed through the admin panel."} {"lang":"php","raw_index":28854,"index":2892,"seed":" <\/script>\n@stop\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a snippet of code that appears to be part of a web application. The code seems to be related to a web framework or templating system. Your task is to identify the language and framework being used, explain the purpose of the given code, and suggest a potential scenario where this code might be used.","solution":"The given code snippet appears to be part of a Blade template in the Laravel PHP framework. The `@stop` directive is used to indicate the end of a section in a Blade template. The `@script` and `<\/script>` tags suggest that this section might be used for including JavaScript code within the template.\n\nA potential scenario where this code might be used is in a web application that needs to include custom JavaScript code for a specific page or component. The `@stop` directive would mark the end of the section where the JavaScript code is included, and the `@script` tag would indicate the start of the JavaScript section within the Blade template. This allows developers to include both HTML and JavaScript code in the same template file, making it easier to manage the frontend code for the application."} {"lang":"swift","raw_index":135657,"index":3874,"seed":" throw TransformationError.invalidLanguage\n }\n return result\n })\n var language: Language = .english\n \n @Option(\n name: [.short, .customLong(\"newline-code\")],\n help: \"Newline code of output. If not specified, the same newline code as in the original file will be output.\",\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a command-line tool for language transformation. The tool should read a file in a specified language, transform its content, and output the result. The transformation process involves converting the content to a different language based on the specified options. Your task is to implement the transformation logic for the tool.\n\nYou are provided with a Swift code snippet that includes a part of the transformation logic. The snippet defines a function `transformFile` that takes a file path and a language as input, and returns the transformed content. Additionally, it includes a property `language` that represents the default language for transformation and an option `newline-code` for specifying the newline code of the output.\n\nYour task is to complete the implementation of the `transformFile` function and handle the newline code option. The transformation rules are as follows:\n- If the input language is English, the content should be transformed to French.\n- If the input language is French, the content should be transformed to Spanish.\n- If the input language is Spanish, the content should be transformed to English.\n\nYou need to handle the newline code option such that if it is specified, the output should use the specified newline code; otherwise, the same newline code as in the original file will be used.\n\nComplete the implementation of the `transformFile` function and handle the newline code option based on the given requirements.","solution":"```swift\nenum Language {\n case english\n case french\n case spanish\n}\n\nenum TransformationError: Error {\n case invalidLanguage\n}\n\nfunc transformFile(filePath: String, inputLanguage: Language, newlineCode: String?) throws -> String {\n guard let fileContent = try? String(contentsOfFile: filePath) else {\n throw TransformationError.invalidLanguage\n }\n \n var result = \"\"\n \n switch inputLanguage {\n case .english:\n result = transformToFrench(fileContent)\n case .french:\n result = transformToSpanish(fileContent)\n case .spanish:\n result = transformToEnglish(fileContent)\n }\n \n if let specifiedNewlineCode = newlineCode {\n result = result.replacingOccurrences(of: \"\\n\", with: specifiedNewlineCode)\n }\n \n return result\n}\n\nfunc transformToFrench(_ content: String) -> String {\n \/\/ Transformation logic from English to French\n return \"French transformed content\"\n}\n\nfunc transformToSpanish(_ content: String) -> String {\n \/\/ Transformation logic from French to Spanish\n return \"Spanish transformed content\"\n}\n\nfunc transformToEnglish(_ content: String) -> String {\n \/\/ Transformation logic from Spanish to English\n return \"English transformed content\"\n}\n```\n\nIn the solution, the `transformFile` function is completed to handle the transformation logic based on the input language. Additionally, the newline code option is handled to replace the newline characters in the output if a specific newline code is specified. The transformation functions `transformToFrench`, `transformToSpanish`, and `transformToEnglish` are placeholders for the actual transformation logic from one language to another."} {"lang":"csharp","raw_index":28960,"index":4450,"seed":" {\n var existingResource = db.LocalizationResources.Include(r => r.Translations).FirstOrDefault(r => r.ResourceKey == resourceKey);\n\n if(existingResource != null)\n {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a method to update localization resources in a database. The database contains a table named `LocalizationResources` with the following columns:\n- `ResourceKey` (string): The unique key identifying the resource\n- `Translations` (collection): A collection of translations for the resource\n\nYou need to create a method that takes a `resourceKey` and a `newTranslations` collection as input and updates the translations for the resource with the given `resourceKey`. If the resource with the specified `resourceKey` does not exist, a new resource should be created with the provided `resourceKey` and `newTranslations`.\n\nYou are provided with a code snippet that retrieves the existing resource from the database using Entity Framework and checks if it exists. You need to complete the method implementation based on the given requirements.\n\n```csharp\npublic void UpdateLocalizationResource(string resourceKey, IEnumerable newTranslations)\n{\n \/\/ Your implementation here\n}\n```\n\nYou should utilize Entity Framework for database operations and ensure that the method correctly updates the translations for the resource with the given `resourceKey` or creates a new resource if it does not exist.","solution":"```csharp\npublic void UpdateLocalizationResource(string resourceKey, IEnumerable newTranslations)\n{\n using (var db = new YourDbContext())\n {\n var existingResource = db.LocalizationResources.Include(r => r.Translations).FirstOrDefault(r => r.ResourceKey == resourceKey);\n\n if (existingResource != null)\n {\n \/\/ Update existing resource with new translations\n existingResource.Translations.Clear();\n foreach (var translation in newTranslations)\n {\n existingResource.Translations.Add(new Translation { Text = translation });\n }\n }\n else\n {\n \/\/ Create a new resource with the provided resourceKey and translations\n var newResource = new LocalizationResource { ResourceKey = resourceKey };\n foreach (var translation in newTranslations)\n {\n newResource.Translations.Add(new Translation { Text = translation });\n }\n db.LocalizationResources.Add(newResource);\n }\n\n db.SaveChanges();\n }\n}\n```\n\nIn the solution, the method uses Entity Framework to interact with the database. It first checks if the resource with the given `resourceKey` exists. If it does, the existing translations are updated with the new translations. If not, a new resource is created with the provided `resourceKey` and `newTranslations`. Finally, the changes are saved to the database using `SaveChanges` method."} {"lang":"python","raw_index":120712,"index":29344,"seed":"from hard_edge_sol import *","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python module that provides a set of functions for edge detection in images. The module should be able to handle both grayscale and color images and should offer various edge detection algorithms. One of the functions in the module is called `hard_edge_sol`, which is used to apply a specific edge detection algorithm to an input image.\n\nThe `hard_edge_sol` function takes an image as input and returns a new image with the detected edges highlighted. The algorithm used by `hard_edge_sol` is a simple threshold-based approach, where pixels with intensity differences above a certain threshold are considered as edges.\n\nYour task is to implement the `hard_edge_sol` function in the `hard_edge_sol.py` module. The function should take the following inputs:\n- `image`: A NumPy array representing the input image. The array can be 2D (grayscale) or 3D (color) with shape (height, width) or (height, width, 3) respectively.\n- `threshold`: A float representing the intensity difference threshold for edge detection.\n\nThe function should return a new NumPy array representing the output image with the detected edges highlighted. For a grayscale image, the output array should have the same shape as the input array. For a color image, the output array should also have the same shape, but with the detected edges highlighted in all color channels.\n\nYou can assume that the input image will be properly formatted and within a valid range for pixel intensities.\n\nYour implementation should be efficient and handle large images effectively.","solution":"```python\nimport numpy as np\n\ndef hard_edge_sol(image, threshold):\n if len(image.shape) == 2: # Grayscale image\n edges = np.zeros_like(image)\n dx = np.diff(image, axis=1)\n dy = np.diff(image, axis=0)\n edges[1:, 1:] = np.sqrt(dx**2 + dy**2) > threshold\n return edges\n elif len(image.shape) == 3: # Color image\n edges = np.zeros_like(image)\n for i in range(3): # Process each color channel separately\n dx = np.diff(image[:, :, i], axis=1)\n dy = np.diff(image[:, :, i], axis=0)\n edges[1:, 1:, i] = np.sqrt(dx**2 + dy**2) > threshold\n return edges\n else:\n raise ValueError(\"Input image should be 2D (grayscale) or 3D (color) array.\")\n```"} {"lang":"python","raw_index":68878,"index":39012,"seed":"\nclass Response:\n \"\"\"Defines a response.\"\"\"\n\n def to_data(self) -> dict:\n \"\"\"Create a data structure for the response.\"\"\"\n raise NotImplementedError\n\n\nclass EmptyDataResponse(Response):\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a subclass of the `Response` class called `EmptyDataResponse`. The `Response` class is a base class that defines a response and contains a method `to_data` which is intended to be overridden by subclasses to create a data structure for the response.\n\nYour task is to implement the `EmptyDataResponse` class, which should inherit from the `Response` class and provide an implementation for the `to_data` method. The `to_data` method should return an empty dictionary `{}` as the data structure for the response.\n\nYour implementation should adhere to the following requirements:\n- Create a subclass `EmptyDataResponse` of the `Response` class.\n- Implement the `to_data` method in the `EmptyDataResponse` class to return an empty dictionary `{}`.\n\nYour solution should be in Python.","solution":"```python\nclass Response:\n \"\"\"Defines a response.\"\"\"\n\n def to_data(self) -> dict:\n \"\"\"Create a data structure for the response.\"\"\"\n raise NotImplementedError\n\n\nclass EmptyDataResponse(Response):\n \"\"\"Defines an empty data response.\"\"\"\n\n def to_data(self) -> dict:\n \"\"\"Create an empty data structure for the response.\"\"\"\n return {}\n```\n\nThe `EmptyDataResponse` class is implemented as a subclass of the `Response` class. It overrides the `to_data` method to return an empty dictionary `{}` as the data structure for the response. This solution satisfies the requirements outlined in the problem description."} {"lang":"python","raw_index":86875,"index":2668,"seed":" urlpatterns.append(prefix_urlpattern)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simplified version of a URL routing system in Python. The system should allow for the addition of URL patterns to a list of existing patterns. Each URL pattern is represented as a string and can include placeholders for variable parts of the URL. The `urlpatterns` list will store all the URL patterns.\n\nYour task is to implement a function `add_url_pattern` that takes two parameters:\n1. `urlpatterns` (a list): A list of existing URL patterns.\n2. `new_pattern` (a string): A new URL pattern to be added to the list.\n\nThe function should append the `new_pattern` to the `urlpatterns` list and return the updated list.\n\nExample:\n```python\nurlpatterns = ['\/home\/', '\/products\/', '\/blog\/']\nnew_pattern = '\/products\/\/'\nadd_url_pattern(urlpatterns, new_pattern)\n```\nAfter the function call, the `urlpatterns` list should be `['\/home\/', '\/products\/', '\/blog\/', '\/products\/\/']`.","solution":"```python\ndef add_url_pattern(urlpatterns, new_pattern):\n urlpatterns.append(new_pattern)\n return urlpatterns\n```"} {"lang":"python","raw_index":26508,"index":34937,"seed":"\n\ndef convert_strtime_datetime(dt_str):\n \"\"\" Converts datetime isoformat string to datetime (dt) object\n\n Args:\n :dt_str (str): input string in '2017-12-30T18:48:00.353Z' form\n or similar\n Returns:\n TYPE: datetime object\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that converts a datetime isoformat string to a datetime object. The input string will be in the format '2017-12-30T18:48:00.353Z' or a similar isoformat.\n\nYou need to create a Python function with the following signature:\n\n```python\ndef convert_strtime_datetime(dt_str: str) -> datetime:\n pass\n```\n\nYour function should take a datetime isoformat string as input and return a datetime object.\n\nFor example:\n- Input: '2017-12-30T18:48:00.353Z'\n Output: datetime.datetime(2017, 12, 30, 18, 48, 0, 353000, tzinfo=datetime.timezone.utc)\n\nYour task is to implement the `convert_strtime_datetime` function to achieve the desired conversion.","solution":"```python\nfrom datetime import datetime, timezone\n\ndef convert_strtime_datetime(dt_str: str) -> datetime:\n \"\"\" Converts datetime isoformat string to datetime (dt) object\n\n Args:\n :dt_str (str): input string in '2017-12-30T18:48:00.353Z' form or similar\n Returns:\n TYPE: datetime object\n \"\"\"\n return datetime.fromisoformat(dt_str.replace('Z', '+00:00'))\n```\n\nThe `convert_strtime_datetime` function takes the input datetime isoformat string and replaces the 'Z' with '+00:00' to comply with the ISO 8601 format. It then uses the `fromisoformat` method of the `datetime` class to convert the string to a datetime object. The resulting datetime object is returned as the output."} {"lang":"csharp","raw_index":146155,"index":3821,"seed":" public delegate void SearchTextChangedEventHandler(object sender, SearchTextChangedEventArgs e);\n}","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom event handler system for a search functionality in a C# application. The system should allow for the registration of event handlers that will be triggered when the search text is changed. The event handler should receive the new search text as an argument.\n\nYour task is to create a class that includes a delegate for the event handler and a method to trigger the event when the search text changes.\n\nYour class should have the following specifications:\n- Create a delegate named `SearchTextChangedEventHandler` that takes an `object sender` and a `SearchTextChangedEventArgs e` as parameters.\n- Create a method named `OnSearchTextChanged` that will be responsible for triggering the event. This method should take the new search text as a parameter and invoke the event, passing the current instance as the sender and a new instance of `SearchTextChangedEventArgs` containing the new search text.\n- The `SearchTextChangedEventArgs` class should have a property to store the new search text.\n\nYour implementation should allow for the registration of multiple event handlers and ensure that they are all triggered when the search text changes.\n\nImplement the class and demonstrate its usage by registering event handlers and triggering the event when the search text changes.","solution":"```csharp\nusing System;\n\npublic class SearchTextChangedEventArgs : EventArgs\n{\n public string NewSearchText { get; }\n\n public SearchTextChangedEventArgs(string newText)\n {\n NewSearchText = newText;\n }\n}\n\npublic class SearchTextNotifier\n{\n public delegate void SearchTextChangedEventHandler(object sender, SearchTextChangedEventArgs e);\n public event SearchTextChangedEventHandler SearchTextChanged;\n\n public void OnSearchTextChanged(string newSearchText)\n {\n SearchTextChanged?.Invoke(this, new SearchTextChangedEventArgs(newSearchText));\n }\n}\n\nclass Program\n{\n static void Main()\n {\n SearchTextNotifier notifier = new SearchTextNotifier();\n\n notifier.SearchTextChanged += HandleSearchTextChanged1;\n notifier.SearchTextChanged += HandleSearchTextChanged2;\n\n notifier.OnSearchTextChanged(\"new search query\");\n }\n\n static void HandleSearchTextChanged1(object sender, SearchTextChangedEventArgs e)\n {\n Console.WriteLine($\"Handler 1: Search text changed to '{e.NewSearchText}'\");\n }\n\n static void HandleSearchTextChanged2(object sender, SearchTextChangedEventArgs e)\n {\n Console.WriteLine($\"Handler 2: Search text changed to '{e.NewSearchText}'\");\n }\n}\n```\n\nIn this solution, we create a class `SearchTextNotifier` that includes a delegate `SearchTextChangedEventHandler` and an event `SearchTextChanged`. The `OnSearchTextChanged` method triggers the event by invoking the delegate and passing a new instance of `SearchTextChangedEventArgs` containing the new search text. In the `Main` method, we demonstrate the usage by registering two event handlers and then triggering the event with a new search text. When the event is triggered, both event handlers are invoked and receive the new search text as an argument."} {"lang":"python","raw_index":53381,"index":4007,"seed":"\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('registry', '0005_auto_20191029_2312'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='primary',\n name='recommendations',\n field=models.ManyToManyField(blank=True, to='registry.Sport_type', verbose_name='\u0420\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0430\u0446\u0438\u0438'),\n ),\n ]\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Django migration to alter a field in a model. The model `Primary` has a field `recommendations` that needs to be modified to allow for multiple recommendations. The new field should be a Many-to-Many relationship with the model `Sport_type`, and it should allow for blank entries. Your task is to write the migration operation to achieve this modification.\n\nWrite a Python function that generates the necessary migration operation to alter the `recommendations` field in the `Primary` model as described above. The function should take into account the dependencies and the specific alteration required for the field.\n\nYour function should output the migration operation code that can be used to alter the field in the Django migration file.","solution":"```python\nfrom django.db import migrations, models\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('registry', '0005_auto_20191029_2312'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='primary',\n name='recommendations',\n field=models.ManyToManyField(blank=True, to='registry.Sport_type', verbose_name='\u0420\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0430\u0446\u0438\u0438'),\n ),\n ]\n```\nIn the solution, the `Migration` class contains the necessary dependencies and the `AlterField` operation to modify the `recommendations` field in the `Primary` model. The `AlterField` operation specifies the new field as a Many-to-Many relationship with the model `Sport_type`, allowing for blank entries. This migration operation can be used to alter the field in the Django migration file."} {"lang":"csharp","raw_index":32641,"index":1247,"seed":"@using FMCApp.Web.Models\n@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a custom tag helper in an ASP.NET Core MVC application. Tag helpers are a feature in ASP.NET Core that enables server-side code to participate in creating and rendering HTML elements in Razor files. In this scenario, you need to create a custom tag helper to generate a specific HTML element based on the provided model.\n\nYour task is to implement a custom tag helper that will render a custom HTML element based on the model provided. The custom tag helper should be able to generate HTML for the specified model properties.\n\nYou are provided with the following code snippet as a starting point:\n```csharp\n@using FMCApp.Web.Models\n@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers\n```\n\nYour custom tag helper should be able to accept a model of type `CustomModel` and render an HTML element based on the properties of the model. For example, if the `CustomModel` has properties `Title` and `Description`, the tag helper should render HTML like `

Title<\/h1>

Description<\/p><\/div>`.\n\nCreate a custom tag helper class and implement the necessary logic to achieve the desired functionality.","solution":"```csharp\n\/\/ CustomTagHelper.cs\nusing Microsoft.AspNetCore.Razor.TagHelpers;\nusing FMCApp.Web.Models;\n\nnamespace FMCApp.Web.TagHelpers\n{\n [HtmlTargetElement(\"custom-tag\")]\n public class CustomTagHelper : TagHelper\n {\n public CustomModel Model { get; set; }\n\n public override void Process(TagHelperContext context, TagHelperOutput output)\n {\n output.TagName = \"div\";\n output.Content.SetHtmlContent($\"

{Model.Title}<\/h1>

{Model.Description}<\/p>\");\n }\n }\n}\n```\n\nIn the solution, a custom tag helper class `CustomTagHelper` is created, which inherits from `TagHelper`. The `HtmlTargetElement` attribute specifies the HTML tag that this tag helper will target. The `Model` property is used to accept the `CustomModel` instance. In the `Process` method, the logic is implemented to generate the desired HTML content based on the properties of the provided model. The `output` parameter is used to set the tag name and content of the generated HTML element."} {"lang":"cpp","raw_index":25583,"index":2901,"seed":" if (*p != '\\\\') \/\/ \\ ma specjalne znaczenie; wi\u0119c '\\\\'\n return *(p++);\n else { \/\/ 3 cyfry \u00f3semkowe:\n int wartosc_znaku = cyfra(p[1], 8) * 64 + cyfra(p[2], 8) * 8 + cyfra(p[3], 8);\n if (wartosc_znaku > std::numeric_limits::max() or wartosc_znaku < std::numeric_limits::min())\n throw domain_error (string (\"nie znak\"));\n p += 4; \/\/ odwrtotny uko\u015bnik i 3 cyfry \u00f3semkowe\n return wartosc_znaku;\n }\n}\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a code snippet written in C++ that processes a string containing escape sequences. The snippet contains a function that processes the escape sequences and returns the corresponding character or value. Your task is to understand the functionality of the given code and implement a similar function in C++ to process escape sequences.\n\nYou need to implement a function `processEscapeSequence` that takes a string as input and processes the escape sequences within the string. The function should return a new string with the escape sequences replaced by their corresponding characters.\n\nThe escape sequences to be handled are:\n- If the character is not a backslash ('\\'), it should be returned as is.\n- If the character is a backslash followed by three octal digits, it should be replaced by the corresponding character.\n\nYour task is to implement the `processEscapeSequence` function to achieve this functionality.","solution":"```cpp\n#include \n#include \n#include \n\nchar processEscapeSequence(const std::string& input) {\n std::string result;\n auto p = input.begin();\n\n while (p != input.end()) {\n if (*p != '\\\\') {\n result += *(p++);\n } else {\n if (std::distance(p, input.end()) < 4) {\n throw std::domain_error(\"Invalid escape sequence\");\n }\n int charValue = (p[1] - '0') * 64 + (p[2] - '0') * 8 + (p[3] - '0');\n if (charValue > std::numeric_limits::max() || charValue < std::numeric_limits::min()) {\n throw std::domain_error(\"Character value out of range\");\n }\n result += static_cast(charValue);\n p += 4;\n }\n }\n\n return result;\n}\n```\n\nThe `processEscapeSequence` function iterates through the input string, processing escape sequences as described in the problem description. It replaces the escape sequences with their corresponding characters and returns the resulting string. If an invalid escape sequence or character value out of range is encountered, the function throws a `std::domain_error` with an appropriate message."} {"lang":"swift","raw_index":10505,"index":1349,"seed":"}\n\nstruct Gender: Codable {\n let gender: String!\n let names: [String]\n \n init(gender: String, names: [String]) {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a program to analyze and categorize names based on gender. The program should read a JSON file containing a list of names along with their associated gender and then provide functionality to categorize and retrieve names based on their gender.\n\nYou are provided with a `Gender` struct that conforms to the `Codable` protocol. The struct has two properties:\n- `gender`: A non-optional `String` representing the gender associated with the names.\n- `names`: An array of `String` representing the names associated with the gender.\n\nYour task is to implement the following functionalities:\n1. Create a function `loadData(from file: String) -> [Gender]` that takes the name of a JSON file as input and returns an array of `Gender` objects parsed from the JSON file.\n2. Create a function `getNames(ofGender gender: String, from data: [Gender]) -> [String]` that takes a gender as input and returns an array of names associated with that gender from the provided data.\n3. Create a function `getGenders(from data: [Gender]) -> [String]` that returns an array of unique genders present in the provided data.\n\nYou can assume that the JSON file is well-formed and follows the structure of the `Gender` struct.\n\nExample JSON file:\n```json\n[\n {\n \"gender\": \"Male\",\n \"names\": [\"John\", \"Michael\", \"David\"]\n },\n {\n \"gender\": \"Female\",\n \"names\": [\"Emily\", \"Sophia\", \"Emma\"]\n }\n]\n```","solution":"```swift\nimport Foundation\n\nstruct Gender: Codable {\n let gender: String\n let names: [String]\n}\n\nfunc loadData(from file: String) -> [Gender] {\n guard let url = Bundle.main.url(forResource: file, withExtension: \"json\") else {\n fatalError(\"File not found\")\n }\n do {\n let data = try Data(contentsOf: url)\n let genders = try JSONDecoder().decode([Gender].self, from: data)\n return genders\n } catch {\n fatalError(\"Error loading data: \\(error.localizedDescription)\")\n }\n}\n\nfunc getNames(ofGender gender: String, from data: [Gender]) -> [String] {\n let filteredNames = data.first { $0.gender == gender }?.names ?? []\n return filteredNames\n}\n\nfunc getGenders(from data: [Gender]) -> [String] {\n let uniqueGenders = Set(data.map { $0.gender })\n return Array(uniqueGenders)\n}\n\n\/\/ Usage\nlet file = \"namesData\"\nlet loadedData = loadData(from: file)\nlet maleNames = getNames(ofGender: \"Male\", from: loadedData)\nlet uniqueGenders = getGenders(from: loadedData)\n```"} {"lang":"typescript","raw_index":14038,"index":1679,"seed":" \/\/ All Stakeholders predict 72% likehood of a Positive Outcome\n \/\/ <\/Header>\n \/\/ \n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program that analyzes stakeholder predictions for positive outcomes and calculates the overall likelihood of success. The stakeholder predictions are represented as a series of percentages, and your program should determine the combined likelihood of a positive outcome based on these predictions.\n\nYou are given a list of stakeholder predictions, each represented as a percentage value. For example:\n```python\npredictions = [72, 65, 80, 90]\n```\nEach percentage represents the likelihood of a positive outcome as predicted by a stakeholder.\n\nYour task is to create a function `calculate_combined_likelihood(predictions)` that takes in the list of stakeholder predictions and returns the overall combined likelihood of a positive outcome. The combined likelihood is calculated by taking the average of all the stakeholder predictions.\n\nFor the given example, the function should return:\n```python\n77.75\n```\nThis is calculated as (72 + 65 + 80 + 90) \/ 4 = 77.75.\n\nWrite a program that implements the `calculate_combined_likelihood` function and accurately calculates the combined likelihood of a positive outcome based on the stakeholder predictions.","solution":"```python\ndef calculate_combined_likelihood(predictions):\n total_likelihood = sum(predictions)\n combined_likelihood = total_likelihood \/ len(predictions)\n return combined_likelihood\n\n# Example usage\npredictions = [72, 65, 80, 90]\ncombined_likelihood = calculate_combined_likelihood(predictions)\nprint(combined_likelihood) # Output: 77.75\n```\n\nThe `calculate_combined_likelihood` function takes in a list of stakeholder predictions and calculates the combined likelihood of a positive outcome by averaging the individual predictions. The solution accurately addresses the problem by providing a function that performs the required calculation and an example usage demonstrating its functionality."} {"lang":"cpp","raw_index":82212,"index":4006,"seed":"}\n\nS::Int S::Object::RequestObjectHandle()\n{\n\tif (initializing) return\t\t\t nextObjectHandle++;\n\telse\t\t return Threads::Access::Increment(nextObjectHandle) - 1;\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a thread-safe object handle generator for a multi-threaded application. The provided code snippet is a part of the implementation for the `RequestObjectHandle` method of the `Object` class. The method is responsible for generating unique object handles, ensuring thread safety during the process.\n\nThe `Object` class has an integer member variable `nextObjectHandle` which stores the next available object handle. The `initializing` flag is a boolean variable that indicates whether the object handle generator is in the initialization phase. During initialization, the `nextObjectHandle` is simply incremented to provide unique handles. However, once the initialization phase is complete, the `Threads::Access::Increment` function is used to increment and retrieve the next object handle in a thread-safe manner.\n\nYour task is to complete the implementation of the `RequestObjectHandle` method to ensure that it generates unique object handles in a thread-safe manner, considering both the initialization phase and the regular operation.\n\nImplement the `RequestObjectHandle` method of the `Object` class to achieve this functionality.","solution":"```cpp\n#include \n\nclass Object {\nprivate:\n std::atomic nextObjectHandle;\n bool initializing;\n\npublic:\n Object() : nextObjectHandle(0), initializing(true) {}\n\n int RequestObjectHandle() {\n if (initializing) {\n return nextObjectHandle++;\n } else {\n return nextObjectHandle.fetch_add(1);\n }\n }\n};\n```\n\nIn the solution, the `std::atomic` type is used to ensure atomic operations on the `nextObjectHandle` variable, providing thread safety. During the initialization phase, the handle is simply incremented using the post-increment operator. In the regular operation phase, the `fetch_add` method is used to atomically increment and retrieve the next object handle. This ensures that the object handles are generated in a thread-safe manner, preventing race conditions and ensuring uniqueness."} {"lang":"rust","raw_index":6900,"index":4388,"seed":" r = r.wrapping_mul(1664525).wrapping_add(1013904223);\n v.push(r % size);\n }\n black_box(sorter(v.as_mut_slice()));\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a scenario where a sorting algorithm is being applied to a list of elements. Your task is to implement a specific sorting algorithm and determine the final state of the list after the sorting process.\n\nYou are provided with the following code snippet as a reference for the sorting process:\n```\nr = r.wrapping_mul(1664525).wrapping_add(1013904223);\nv.push(r % size);\n}\nblack_box(sorter(v.as_mut_slice()));\n```\nHere, `r` is a variable that undergoes a series of operations, and the result is used to determine the position where a new element is added to the list `v`. After all elements are added, the list `v` is passed to a sorting function `sorter` using `black_box`.\n\nYour task is to implement the sorting algorithm `sorter` and determine the final state of the list `v` after the sorting process.\n\nImplement the sorting algorithm and return the final state of the list `v` after the sorting process.","solution":"The given code snippet suggests the use of a pseudo-random number generator to populate a list `v` and then sort it using a sorting algorithm. To solve this problem, we need to implement the sorting algorithm and determine the final state of the list `v` after the sorting process.\n\nOne possible solution is to implement the quicksort algorithm for sorting the list `v`. Quicksort is a widely used sorting algorithm known for its efficiency and average-case time complexity of O(n log n).\n\nHere's a sample implementation of the quicksort algorithm in Rust:\n\n```rust\nfn quicksort(arr: &mut [u32]) {\n if arr.len() <= 1 {\n return;\n }\n let pivot = arr[arr.len() \/ 2];\n let mut left = 0;\n let mut right = arr.len() - 1;\n\n while left <= right {\n while arr[left] < pivot {\n left += 1;\n }\n while arr[right] > pivot {\n right -= 1;\n }\n if left <= right {\n arr.swap(left, right);\n left += 1;\n right -= 1;\n }\n }\n\n if right > 0 {\n quicksort(&mut arr[0..=right]);\n }\n if left < arr.len() {\n quicksort(&mut arr[left..]);\n }\n}\n\nfn main() {\n let mut v: Vec = Vec::new();\n let size = 10; \/\/ Replace with the actual size used in the code snippet\n let mut r = 0; \/\/ Replace with the initial value used in the code snippet\n\n for _ in 0..size {\n r = r.wrapping_mul(1664525).wrapping_add(1013904223);\n v.push(r % size);\n }\n\n quicksort(&mut v);\n println!(\"{:?}\", v);\n}\n```\n\nIn this solution, the `quicksort` function is used to sort the list `v`. After populating the list `v` using the given code snippet, the `quicksort` function is called to sort the list. The final state of the sorted list `v` is then printed.\n\nThis solution demonstrates the implementation of the quicksort algorithm to sort the list `v` and determine its final state after the sorting process."} {"lang":"java","raw_index":30838,"index":230,"seed":" final CardBuilder cardBuilder\n ) {\n TokenizationClient.tokenize(\n fragment,\n cardBuilder,\n new PaymentMethodTokenCallback() {\n\n @Override\n public void success(PaymentMethodToken paymentMethodToken) {\n fragment.postCallback(paymentMethodToken);\n }\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simplified version of a tokenization system used for processing payment methods. The system involves a `TokenizationClient` class that is responsible for tokenizing payment methods and a `CardBuilder` class used to build payment card information. The `TokenizationClient` takes a `CardBuilder` and a callback function as parameters. When the tokenization process is successful, the `success` method of the callback function is invoked, passing the generated `PaymentMethodToken` as a parameter.\n\nYour task is to create a Java class `PaymentProcessor` that utilizes the provided code snippet and simulates the tokenization process. The `PaymentProcessor` class should have a method `tokenizeCard` that takes a `CardBuilder` and a callback function as parameters, and simulates the tokenization process by invoking the `success` method of the callback function with a mock `PaymentMethodToken` as a parameter.\n\nYour implementation should adhere to the following requirements:\n- Create a `PaymentProcessor` class with a method `tokenizeCard` that takes a `CardBuilder` and a callback function as parameters.\n- Simulate the tokenization process by invoking the `success` method of the callback function with a mock `PaymentMethodToken` as a parameter.\n- The `PaymentProcessor` class should be able to handle successful tokenization and invoke the callback function accordingly.\n\n```java\n\/\/ Your implementation of the PaymentProcessor class\nclass PaymentProcessor {\n public void tokenizeCard(CardBuilder cardBuilder, PaymentMethodTokenCallback callback) {\n \/\/ Simulate tokenization process\n PaymentMethodToken mockToken = new PaymentMethodToken(\"mockToken123\");\n callback.success(mockToken);\n }\n}\n```","solution":"```java\n\/\/ Your implementation of the PaymentProcessor class\nclass PaymentProcessor {\n public void tokenizeCard(CardBuilder cardBuilder, PaymentMethodTokenCallback callback) {\n \/\/ Simulate tokenization process\n PaymentMethodToken mockToken = new PaymentMethodToken(\"mockToken123\");\n callback.success(mockToken);\n }\n}\n```"} {"lang":"swift","raw_index":60649,"index":2321,"seed":"public enum ManifestLoaderError: FatalError, Equatable {\n case projectDescriptionNotFound(AbsolutePath)\n case unexpectedOutput(AbsolutePath)\n case manifestNotFound(Manifest?, AbsolutePath)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom error type and handling its cases in Swift. The provided code snippet defines an enum `ManifestLoaderError` that conforms to the `FatalError` protocol and is equatable. It includes three cases: `projectDescriptionNotFound`, `unexpectedOutput`, and `manifestNotFound`, each with associated values of type `AbsolutePath`.\n\nYour task is to create a Swift program that utilizes the `ManifestLoaderError` enum and demonstrates error handling for each case. Additionally, you need to implement a function that throws these errors based on certain conditions.\n\nYour program should include the following components:\n1. Definition of the `AbsolutePath` type: Assume `AbsolutePath` is a custom type representing the absolute path of a file or directory.\n2. A function `loadManifest` that takes an `AbsolutePath` as input and throws `ManifestLoaderError` based on the following conditions:\n - If the project description is not found at the given absolute path, throw `projectDescriptionNotFound`.\n - If the output is unexpected for the given absolute path, throw `unexpectedOutput`.\n - If the manifest is not found for a given `Manifest` and absolute path, throw `manifestNotFound`.\n3. A demonstration of error handling using a `do-catch` block to handle each type of error thrown by the `loadManifest` function.","solution":"```swift\n\/\/ Definition of the AbsolutePath type\nstruct AbsolutePath {\n let path: String\n}\n\n\/\/ Definition of the Manifest type (assumed for demonstration)\nstruct Manifest {\n let name: String\n}\n\n\/\/ Custom error type conforming to FatalError and Equatable\npublic enum ManifestLoaderError: Error, Equatable {\n case projectDescriptionNotFound(AbsolutePath)\n case unexpectedOutput(AbsolutePath)\n case manifestNotFound(Manifest?, AbsolutePath)\n}\n\n\/\/ Function to load manifest and throw errors\nfunc loadManifest(at path: AbsolutePath) throws {\n \/\/ Simulated conditions for error throwing\n let projectDescriptionExists = false\n let unexpectedOutputExists = true\n let manifest: Manifest? = nil\n \n if !projectDescriptionExists {\n throw ManifestLoaderError.projectDescriptionNotFound(path)\n } else if unexpectedOutputExists {\n throw ManifestLoaderError.unexpectedOutput(path)\n } else if manifest == nil {\n throw ManifestLoaderError.manifestNotFound(manifest, path)\n }\n}\n\n\/\/ Demonstration of error handling\ndo {\n try loadManifest(at: AbsolutePath(path: \"\/path\/to\/project\"))\n} catch ManifestLoaderError.projectDescriptionNotFound(let path) {\n print(\"Project description not found at: \\(path.path)\")\n} catch ManifestLoaderError.unexpectedOutput(let path) {\n print(\"Unexpected output found at: \\(path.path)\")\n} catch ManifestLoaderError.manifestNotFound(let manifest, let path) {\n if let manifest = manifest {\n print(\"Manifest \\(manifest.name) not found at: \\(path.path)\")\n } else {\n print(\"Manifest not found at: \\(path.path)\")\n }\n} catch {\n print(\"An unknown error occurred: \\(error)\")\n}\n```\n\nIn this solution, we define the `AbsolutePath` and `Manifest` types, the `ManifestLoaderError` enum, and the `loadManifest` function. We then demonstrate error handling using a `do-catch` block to handle each type of error thrown by the `loadManifest` function."} {"lang":"rust","raw_index":113940,"index":2246,"seed":"pub mod hamt;\n\npub use hamt::*;\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use std::hash::{Hash, Hasher};\n use std::collections::hash_map::DefaultHasher;\n\n fn hash(s: &String) -> u32 {\n let mut hasher = DefaultHasher::new();\n s.hash(&mut hasher);\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Hash Array Mapped Trie (HAMT) data structure in Rust. The HAMT is a persistent data structure used for implementing associative arrays efficiently. In this problem, you will be focusing on implementing the `insert` and `get` methods for the HAMT.\n\nYour task is to complete the implementation of the `insert` and `get` methods for the HAMT data structure. The `insert` method should insert a key-value pair into the HAMT, and the `get` method should retrieve the value associated with a given key.\n\nThe HAMT data structure is provided in the `hamt` module, and you should implement the missing parts in the `hamt.rs` file.\n\n```rust\n\/\/ hamt.rs\n\npub struct Hamt {\n \/\/ Your implementation here\n}\n\nimpl Hamt {\n pub fn new() -> Self {\n \/\/ Your implementation here\n }\n\n pub fn insert(&mut self, key: u32, value: String) {\n \/\/ Your implementation here\n }\n\n pub fn get(&self, key: u32) -> Option<&String> {\n \/\/ Your implementation here\n }\n}\n```\n\nYou should implement the `Hamt` struct and its methods to achieve the following:\n1. Efficiently store key-value pairs using the HAMT data structure.\n2. Implement the `insert` method to insert a key-value pair into the HAMT.\n3. Implement the `get` method to retrieve the value associated with a given key.\n\nYou can assume that the `Hamt` struct will be used to store key-value pairs where the keys are of type `u32` and the values are of type `String`.","solution":"```rust\n\/\/ hamt.rs\n\nuse std::collections::HashMap;\n\nconst MAX_INDEX: usize = 32;\nconst MAX_BRANCHING: usize = 5;\n\npub struct Hamt {\n children: Option]>>,\n values: Option>,\n}\n\nimpl Hamt {\n pub fn new() -> Self {\n Hamt {\n children: None,\n values: None,\n }\n }\n\n pub fn insert(&mut self, key: u32, value: String) {\n let mut current = self;\n let mut key_bits = key;\n let mut level = 0;\n\n while level < MAX_INDEX {\n let index = (key_bits & (MAX_BRANCHING as u32 - 1)) as usize;\n key_bits >>= MAX_BRANCHING as u32;\n\n if let Some(ref mut children) = current.children {\n if let Some(ref mut child) = &mut children[index] {\n current = child;\n } else {\n let mut new_child = Hamt::new();\n current = &mut new_child;\n children[index] = Some(new_child);\n }\n } else {\n let mut children = vec![None; MAX_BRANCHING];\n let mut new_child = Hamt::new();\n current.children = Some(children.into_boxed_slice());\n current = &mut new_child;\n current.children.as_mut().unwrap()[index] = Some(new_child);\n }\n\n level += MAX_BRANCHING;\n }\n\n if current.values.is_none() {\n current.values = Some(HashMap::new());\n }\n\n current.values.as_mut().unwrap().insert(key, value);\n }\n\n pub fn get(&self, key: u32) -> Option<&String> {\n let mut current = self;\n let mut key_bits = key;\n let mut level = 0;\n\n while level < MAX_INDEX {\n let index = (key_bits & (MAX_BRANCHING as u32 - 1)) as usize;\n key_bits >>= MAX_BRANCHING as u32;\n\n if let Some(ref children) = current.children {\n if let Some(ref child) = &children[index] {\n current = child;\n } else {\n return None;\n }\n } else {\n return None;\n }\n\n level += MAX_BRANCHING;\n }\n\n current.values.as_ref().and_then(|values| values.get(&key))\n }\n}\n```\n\nThis solution provides a complete implementation of the `Hamt` data structure with the `insert` and `get` methods. The `insert` method efficiently inserts key-value pairs into the HAMT, and the `get` method retrieves the value associated with a given key. The HAMT uses a trie-like structure to store key-value pairs, providing efficient lookup and insertion operations."} {"lang":"csharp","raw_index":76968,"index":1894,"seed":" {\n return HeaterDatas(controllerState, null);\n }\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simplified version of a heating system controller. The controller is responsible for managing the temperature of a room by interacting with a heater. The heater can be turned on or off based on the current state of the room and the desired temperature.\n\nYou are provided with a code snippet that represents a function call to `HeaterDatas`. The function takes two parameters: `controllerState` and `null`. The `controllerState` parameter represents the current state of the controller and contains information about the room temperature, desired temperature, and heater status.\n\nYour task is to implement the `HeaterDatas` function, which should take the `controllerState` as input and return the appropriate action to be taken by the heater. The function should return a string indicating whether the heater should be turned on or off based on the provided `controllerState`.\n\nYou should consider the following rules when implementing the `HeaterDatas` function:\n- If the room temperature is lower than the desired temperature and the heater is off, the function should return \"Turn on heater\".\n- If the room temperature is higher than or equal to the desired temperature and the heater is on, the function should return \"Turn off heater\".\n- If the room temperature is lower than the desired temperature and the heater is already on, the function should return \"Heater is already on\".\n- If the room temperature is higher than or equal to the desired temperature and the heater is off, the function should return \"Heater is already off\".\n\nYou should assume that the `controllerState` parameter is an object with the following properties:\n- `roomTemperature`: A number representing the current temperature of the room.\n- `desiredTemperature`: A number representing the desired temperature for the room.\n- `heaterStatus`: A boolean value indicating whether the heater is currently on (true) or off (false).\n\nImplement the `HeaterDatas` function to fulfill the specified requirements.","solution":"```javascript\nfunction HeaterDatas(controllerState) {\n if (controllerState.roomTemperature < controllerState.desiredTemperature && !controllerState.heaterStatus) {\n return \"Turn on heater\";\n } else if (controllerState.roomTemperature >= controllerState.desiredTemperature && controllerState.heaterStatus) {\n return \"Turn off heater\";\n } else if (controllerState.roomTemperature < controllerState.desiredTemperature && controllerState.heaterStatus) {\n return \"Heater is already on\";\n } else if (controllerState.roomTemperature >= controllerState.desiredTemperature && !controllerState.heaterStatus) {\n return \"Heater is already off\";\n }\n}\n\n\/\/ Example usage\nconst state1 = {\n roomTemperature: 18,\n desiredTemperature: 22,\n heaterStatus: false\n};\n\nconsole.log(HeaterDatas(state1)); \/\/ Output: \"Turn on heater\"\n\nconst state2 = {\n roomTemperature: 24,\n desiredTemperature: 20,\n heaterStatus: true\n};\n\nconsole.log(HeaterDatas(state2)); \/\/ Output: \"Turn off heater\"\n```"} {"lang":"python","raw_index":21432,"index":30458,"seed":"disc = Disc(model, {\"vx\": math.cos(a * math.pi \/ 180) * v, \"dgamma\": rot, \"vz\": math.sin(a * math.pi \/ 180) * v,\n \"nose_up\": nose_up, \"hyzer\": hyzer, \"gamma\": -2})\n\nresult = disc.compute_trajectory(20.0, **{\"max_step\": .2})\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with simulating the flight trajectory of a disc golf disc using the given code snippet as a reference. The `Disc` class represents a disc model and its properties, and the `compute_trajectory` method calculates the disc's trajectory over time. Your goal is to create a Python function that takes the necessary parameters and returns the simulated trajectory of the disc.\n\nWrite a function `simulate_disc_trajectory` that takes the following parameters:\n- `model` (string): The disc model name.\n- `a` (float): The launch angle in degrees.\n- `v` (float): The launch velocity in meters per second.\n- `rot` (float): The rotation rate in radians per second.\n- `nose_up` (bool): Indicates whether the disc is thrown nose up (True) or not (False).\n- `hyzer` (float): The hyzer angle in degrees.\n- `time` (float): The total time for which the trajectory should be simulated.\n\nThe function should return a list of tuples, where each tuple represents the disc's position at a specific time during its flight. Each tuple should contain the time (in seconds) and the 3D coordinates (x, y, z) of the disc's position.\n\nFor example, calling `simulate_disc_trajectory(\"Aviar\", 30, 15, 0.5, True, 5, 10.0)` should return the simulated trajectory of the \"Aviar\" disc thrown at a 30-degree launch angle, 15 m\/s velocity, 0.5 rad\/s rotation rate, nose up, 5-degree hyzer angle, and simulated for 10 seconds.","solution":"```python\nimport math\n\nclass Disc:\n def __init__(self, model, params):\n self.model = model\n self.params = params\n\n def compute_trajectory(self, time, **kwargs):\n # Simulate disc trajectory based on given parameters\n # Returns list of tuples (time, x, y, z) representing disc position\n trajectory = []\n max_step = kwargs.get(\"max_step\", 0.1) # Default max_step value\n\n # Simulate disc trajectory using given parameters\n # Replace the following with actual trajectory simulation logic\n for t in range(0, int(time*10)+1):\n x = self.params[\"vx\"] * t * max_step\n y = self.params[\"vz\"] * t * max_step\n z = self.params[\"dgamma\"] * t * max_step\n trajectory.append((t * max_step, x, y, z))\n\n return trajectory\n\ndef simulate_disc_trajectory(model, a, v, rot, nose_up, hyzer, time):\n vx = math.cos(a * math.pi \/ 180) * v\n vz = math.sin(a * math.pi \/ 180) * v\n disc = Disc(model, {\"vx\": vx, \"dgamma\": rot, \"vz\": vz, \"nose_up\": nose_up, \"hyzer\": hyzer, \"gamma\": -2})\n return disc.compute_trajectory(time, max_step=0.2)\n\n# Example usage\ntrajectory = simulate_disc_trajectory(\"Aviar\", 30, 15, 0.5, True, 5, 10.0)\nprint(trajectory)\n```\n\nIn the solution, the `simulate_disc_trajectory` function creates a `Disc` object with the given parameters and then calls its `compute_trajectory` method to obtain the simulated trajectory. The `compute_trajectory` method currently contains a placeholder logic for trajectory simulation and should be replaced with the actual simulation algorithm. The function returns the simulated trajectory as a list of tuples containing time and 3D coordinates."} {"lang":"shell","raw_index":65331,"index":3409,"seed":"\ncd $dir\nsource \/cs\/labs\/daphna\/idan.azuri\/venv_64\/bin\/activate\n\n\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a shell script that activates a virtual environment and changes the working directory. Your task is to write a Python script that emulates the behavior of the shell script by changing the working directory and activating the virtual environment.\n\nThe shell script contains the following commands:\n```\ncd $dir\nsource \/cs\/labs\/daphna\/idan.azuri\/venv_64\/bin\/activate\n```\nWhere `$dir` is the directory to which the script changes the working directory.\n\nWrite a Python script that performs the same actions as the shell script. Your script should change the working directory to the specified directory and activate the virtual environment located at `\/cs\/labs\/daphna\/idan.azuri\/venv_64\/bin\/activate`.\n\nYour Python script should handle any errors that may occur during the process, such as the directory not existing or the virtual environment activation failing.","solution":"```python\nimport os\nimport subprocess\n\ndef activate_virtual_environment(dir_path, venv_activate_path):\n try:\n # Change working directory\n os.chdir(dir_path)\n print(f\"Changed working directory to: {os.getcwd()}\")\n\n # Activate virtual environment\n activate_cmd = f\"source {venv_activate_path}\"\n subprocess.run(activate_cmd, shell=True, check=True)\n print(\"Virtual environment activated successfully\")\n\n except FileNotFoundError:\n print(\"Error: Directory not found\")\n except subprocess.CalledProcessError:\n print(\"Error: Failed to activate virtual environment\")\n\n# Example usage\ndir_path = \"\/path\/to\/your\/directory\"\nvenv_activate_path = \"\/cs\/labs\/daphna\/idan.azuri\/venv_64\/bin\/activate\"\nactivate_virtual_environment(dir_path, venv_activate_path)\n```\n\nIn this solution, the `activate_virtual_environment` function takes the directory path and virtual environment activation path as input. It then attempts to change the working directory using `os.chdir` and activate the virtual environment using `subprocess.run`. Any errors that occur during the process are caught and appropriate error messages are printed."} {"lang":"swift","raw_index":25404,"index":3370,"seed":" ] as Set\n public static let evidence = [requestWhenInUseAuthorizationCalledReference] as Set\n public static let forwardsInvocations = false\n }\n\n\n \/\/\/ Spy method that replaces the true implementation of `requestWhenInUseAuthorization`\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a spy method in Swift that replaces the true implementation of a specific function. The code snippet provided contains part of a Swift file, and your goal is to complete the spy method to intercept and replace the implementation of the `requestWhenInUseAuthorization` function.\n\nYour task is to complete the spy method by implementing the necessary code to intercept and replace the true implementation of `requestWhenInUseAuthorization`. You should also ensure that the spy method correctly forwards invocations to the original implementation when necessary.\n\nComplete the spy method to fulfill the following requirements:\n- Intercept the calls to `requestWhenInUseAuthorization` and replace the true implementation with custom behavior.\n- Ensure that the spy method correctly forwards invocations to the original implementation when `forwardsInvocations` is set to `true`.\n\nYour solution should be implemented in Swift.","solution":"```swift\n\/\/\/ Spy method that replaces the true implementation of `requestWhenInUseAuthorization`\nclass LocationManagerSpy: CLLocationManager {\n static var originalRequestWhenInUseAuthorization: (() -> Void)?\n \n override class func load() {\n swizzleRequestWhenInUseAuthorization()\n }\n \n private class func swizzleRequestWhenInUseAuthorization() {\n let originalSelector = #selector(CLLocationManager.requestWhenInUseAuthorization)\n let swizzledSelector = #selector(LocationManagerSpy.spyRequestWhenInUseAuthorization)\n \n guard let originalMethod = class_getInstanceMethod(CLLocationManager.self, originalSelector),\n let swizzledMethod = class_getInstanceMethod(LocationManagerSpy.self, swizzledSelector) else {\n return\n }\n \n let didAddMethod = class_addMethod(CLLocationManager.self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))\n \n if didAddMethod {\n class_replaceMethod(CLLocationManager.self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))\n } else {\n method_exchangeImplementations(originalMethod, swizzledMethod)\n }\n }\n \n @objc private dynamic func spyRequestWhenInUseAuthorization() {\n if LocationManagerSpy.forwardsInvocations {\n LocationManagerSpy.originalRequestWhenInUseAuthorization?()\n } else {\n \/\/ Custom behavior for intercepting the true implementation\n print(\"Intercepted requestWhenInUseAuthorization\")\n \/\/ Add custom behavior here\n }\n }\n}\n```\n\nIn the solution, we create a `LocationManagerSpy` class that subclasses `CLLocationManager` to intercept and replace the true implementation of `requestWhenInUseAuthorization`. We use method swizzling to exchange the original method with our spy method. The `spyRequestWhenInUseAuthorization` method intercepts the calls and provides custom behavior when `forwardsInvocations` is `false`, and forwards invocations to the original implementation when `forwardsInvocations` is `true`."} {"lang":"cpp","raw_index":91240,"index":845,"seed":"\t\treturn RpcClient->IsConnected();\n\t}\n\npublic:\n\n\tvirtual TAsyncResult NavigateTo(const FString& Url) override\n\t{\n\t\treturn RpcClient->Call(Url);\n\t}\n\nprivate:\n\n\tFPortalApplicationWindowProxy(const TSharedRef& InRpcClient)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simplified version of a remote procedure call (RPC) client for a portal application window. The provided code snippet is a part of the implementation of the RPC client. The `RpcClient` is an instance of `IMessageRpcClient` and is used to make RPC calls to the server.\n\nYour task is to implement the `FPortalApplicationWindowProxy` class, which acts as a proxy for the portal application window and provides methods to interact with the remote server using the `RpcClient`.\n\nYou need to implement the following methods in the `FPortalApplicationWindowProxy` class:\n1. `IsConnected`: This method should return a boolean value indicating whether the RPC client is connected to the server.\n2. `NavigateTo`: This method should make an RPC call to the server to navigate to the specified URL and return a result indicating the success of the navigation.\n\nYour implementation should use the provided `RpcClient` to make RPC calls and handle any necessary error checking.\n\nImplement the `FPortalApplicationWindowProxy` class with the required methods to interact with the RPC client.","solution":"```cpp\nclass FPortalApplicationWindowProxy : public IPortalApplicationWindow\n{\nprivate:\n TSharedRef RpcClient;\n\npublic:\n FPortalApplicationWindowProxy(const TSharedRef& InRpcClient) : RpcClient(InRpcClient) {}\n\n virtual TAsyncResult IsConnected() override\n {\n \/\/ Make an RPC call to check the connection status\n return RpcClient->Call();\n }\n\n virtual TAsyncResult NavigateTo(const FString& Url) override\n {\n \/\/ Make an RPC call to navigate to the specified URL\n return RpcClient->Call(Url);\n }\n};\n```\n\nIn the solution, the `FPortalApplicationWindowProxy` class is implemented with the required methods `IsConnected` and `NavigateTo`. The `RpcClient` is used to make RPC calls to the server, and the results are returned as `TAsyncResult` objects, indicating the success of the operations. The constructor initializes the `RpcClient` with the provided `IMessageRpcClient` instance."} {"lang":"python","raw_index":85422,"index":6782,"seed":"\t\"Accuracy\": \"11\",\r\n\t\"Latitude\": \"37.61\",\r\n\t\"LocationTimeStamp\": \"1366361979315\",\r\n\t\"Longitude\": \"-122.385979\"\r\n\r\n\t})\r\n\t\r\nmqttc.publish(aercloud_container, msg, qos=1)\r\nmqttc.loop()\r\n\r\nwhile publish_complete == False and connect_error == False:\r\n\tmqttc.loop()\r\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python program that subscribes to a MQTT (Message Queuing Telemetry Transport) topic, processes incoming messages, and publishes a response message to another topic. The program should handle potential errors related to connection and publishing.\n\nYour program should subscribe to a specific MQTT topic and process incoming messages. Upon receiving a message, the program should extract the \"Accuracy\", \"Latitude\", \"LocationTimeStamp\", and \"Longitude\" fields from the message payload. After processing the message, the program should publish a response message to a different MQTT topic with the processed data.\n\nAdditionally, the program should continuously check for completion of the publishing process and handle any potential connection errors.\n\nYou are provided with a code snippet that demonstrates the publishing and looping functionality of the MQTT client. Your task is to implement the message processing and publishing logic, as well as error handling for the MQTT client.","solution":"```python\nimport paho.mqtt.client as mqtt\nimport json\n\n# Define the MQTT broker and topics\nbroker_address = \"mqtt.example.com\"\ninput_topic = \"input_topic\"\noutput_topic = \"output_topic\"\n\n# Callback function for when the client receives a CONNACK response from the server\ndef on_connect(client, userdata, flags, rc):\n if rc == 0:\n print(\"Connected to MQTT broker\")\n client.subscribe(input_topic)\n else:\n print(\"Connection failed\")\n\n# Callback function for when a message is received on the input topic\ndef on_message(client, userdata, message):\n payload = json.loads(message.payload)\n accuracy = payload.get(\"Accuracy\")\n latitude = payload.get(\"Latitude\")\n location_timestamp = payload.get(\"LocationTimeStamp\")\n longitude = payload.get(\"Longitude\")\n\n # Process the received data (e.g., perform calculations, transformations)\n\n # Prepare the response message\n response_data = {\n \"ProcessedAccuracy\": accuracy,\n \"ProcessedLatitude\": latitude,\n \"ProcessedLocationTimeStamp\": location_timestamp,\n \"ProcessedLongitude\": longitude\n }\n response_msg = json.dumps(response_data)\n\n # Publish the response message to the output topic\n client.publish(output_topic, response_msg, qos=1)\n\n# Create an MQTT client instance\nmqttc = mqtt.Client()\n\n# Set the callback functions\nmqttc.on_connect = on_connect\nmqttc.on_message = on_message\n\n# Connect to the MQTT broker\nmqttc.connect(broker_address, 1883, 60)\n\n# Loop to handle incoming messages and publishing\nmqttc.loop_start()\n\n# Continuously check for completion of the publishing process and handle connection errors\npublish_complete = False\nconnect_error = False\nwhile not publish_complete and not connect_error:\n mqttc.loop()\n # Check for completion of the publishing process and set publish_complete accordingly\n # Handle potential connection errors and set connect_error accordingly\n\n# Stop the MQTT client loop\nmqttc.loop_stop()\n```\nIn the solution, we first import the necessary MQTT client library and define the MQTT broker address, input topic, and output topic. We then define callback functions for connecting to the MQTT broker and processing incoming messages. Inside the `on_message` callback, we extract the required fields from the message payload, process the data, and publish a response message to the output topic.\n\nAfter setting up the MQTT client and connecting to the broker, we start the client loop to handle incoming messages and publishing. We also continuously check for completion of the publishing process and handle potential connection errors within the while loop. Finally, we stop the MQTT client loop after the loop completes."} {"lang":"python","raw_index":52095,"index":14010,"seed":"\n\n#\nclass LocationTestClass(TestCase):\n '''\n test case for location model\n '''\n def setUp(self):\n self.any_location = Location(image_location = 'Poland')\n\n def test_save_location(self):\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a test case for a location model in a Python application. The `Location` model represents a geographical location and has a field `image_location` to store the name of the location. Your task is to complete the test case by writing a test method to validate the functionality of saving a location in the model.\n\nYour task is to implement the `test_save_location` method in the `LocationTestClass` class. The method should create a new `Location` instance with the `image_location` set to 'Poland' and then save it to the database. You should then verify that the location is saved correctly by checking if it exists in the database.\n\nComplete the `test_save_location` method to achieve the following:\n1. Create a new `Location` instance with the `image_location` set to 'Poland'.\n2. Save the location to the database.\n3. Verify that the location is saved correctly by checking if it exists in the database.\n\nYour solution should be implemented using Python's unittest framework.","solution":"```python\nfrom django.test import TestCase\nfrom yourapp.models import Location # Import the Location model from your application\n\nclass LocationTestClass(TestCase):\n '''\n test case for location model\n '''\n def setUp(self):\n self.any_location = Location(image_location='Poland')\n\n def test_save_location(self):\n # Create a new Location instance with image_location set to 'Poland'\n location = Location(image_location='Poland')\n \n # Save the location to the database\n location.save()\n \n # Verify that the location is saved correctly by checking if it exists in the database\n saved_location = Location.objects.filter(image_location='Poland').first()\n self.assertIsNotNone(saved_location, \"Location 'Poland' was not saved to the database\")\n```\n\nIn the solution, we import the necessary modules and the `Location` model from the application. In the `test_save_location` method, we create a new `Location` instance with the `image_location` set to 'Poland', save it to the database, and then verify its existence in the database using the `assertIsNotNone` assertion."} {"lang":"python","raw_index":9783,"index":10672,"seed":" location = i+1\nprint(max_value)\nprint(location)","openai_fingerprint":"fp_eeff13170a","problem":"You are given a list of integers representing the scores of participants in a competition. The scores are listed in ascending order of the participants' performance. Your task is to write a program to find the highest score and its corresponding position in the list.\n\nWrite a Python function `find_highest_score_position(scores)` that takes in a list of integers `scores` (1 <= len(scores) <= 100) as input and returns two values: the highest score and its position in the list. If there are multiple occurrences of the highest score, return the position of the first occurrence.\n\nFor example, given the input `scores = [75, 82, 82, 88, 92, 92, 98]`, the function should return `(98, 7)`.","solution":"```python\ndef find_highest_score_position(scores):\n max_value = max(scores)\n location = scores.index(max_value) + 1\n return max_value, location\n```\nThe `find_highest_score_position` function first finds the maximum value in the `scores` list using the `max` function. Then, it determines the position of the maximum value using the `index` method and adds 1 to get the 1-based position. Finally, it returns the maximum value and its position as a tuple."} {"lang":"python","raw_index":52287,"index":31371,"seed":" x3 = re.findall('[0,1,2,3,4,5,6,7,8,9,.]+', str(stochsoup))\r\n atr = ''.join(x)\r\n mfipage = requests.get(mfiurl)\r\n mfisoup = BeautifulSoup(mfipage.content, 'html.parser')\r\n x4 = re.findall('[0,1,2,3,4,5,6,7,8,9,.]+', str(mfisoup))\r\n price = ''.join(x2)\r\n fast_and_slow_stoch = ''.join(x3)\r\n mfi = ''.join(x4)\r\n mfi_number = float(mfi)\r\n atr_number = float(atr)\r\n fast_stoch_number = fast_and_slow_stoch[0:2]\r\n fast_stoch_number_float = float(fast_stoch_number)\r\n # Making Sure We Only Hold 10 Dollars of BTC at a Time\r\n global bought_indicator\r\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a cryptocurrency trading bot that uses web scraping to gather financial data. The code snippet provided is a part of the bot's script. The script extracts financial data from a webpage using the `requests` and `BeautifulSoup` libraries in Python. It then processes the extracted data using regular expressions and converts the relevant information into numerical values for further analysis.\n\nYour task is to write a function that takes the extracted financial data and performs additional calculations based on the given code snippet. Specifically, you need to implement a function that calculates the total amount of cryptocurrency (in dollars) that the bot should hold based on the extracted financial data.\n\nThe function should take the following inputs:\n- `atr_number`: A float representing the Average True Range (ATR) value extracted from the webpage.\n- `price`: A string representing the current price of the cryptocurrency.\n- `fast_stoch_number_float`: A float representing the fast stochastic value extracted from the webpage.\n- `mfi_number`: A float representing the Money Flow Index (MFI) value extracted from the webpage.\n\nThe function should calculate the total amount of cryptocurrency (in dollars) that the bot should hold based on the following rules:\n1. If the fast stochastic value is greater than 80 and the MFI value is less than 20, the bot should hold $100 worth of cryptocurrency.\n2. If the fast stochastic value is less than 20 and the MFI value is greater than 80, the bot should hold $200 worth of cryptocurrency.\n3. If none of the above conditions are met, the bot should hold $50 worth of cryptocurrency.\n\nWrite a function `calculate_cryptocurrency_holdings` that takes the inputs mentioned above and returns the total amount of cryptocurrency (in dollars) that the bot should hold based on the given rules.","solution":"```python\ndef calculate_cryptocurrency_holdings(atr_number, price, fast_stoch_number_float, mfi_number):\n if fast_stoch_number_float > 80 and mfi_number < 20:\n return 100\n elif fast_stoch_number_float < 20 and mfi_number > 80:\n return 200\n else:\n return 50\n```\n\nThe provided solution defines a function `calculate_cryptocurrency_holdings` that takes the ATR value, current price, fast stochastic value, and MFI value as inputs. It then applies the given rules to determine the total amount of cryptocurrency (in dollars) that the bot should hold and returns the calculated amount based on the conditions specified in the problem description."} {"lang":"python","raw_index":37545,"index":6628,"seed":"from mxnet import optimizer\nimport sys\n\n\nclass VGG19:\n def __init__(self):\n vgg19_model = models.vgg19(pretrained=False)\n vgg19_model.load_params(\"model\/vgg19.params\", ctx=mx.cpu(0)) # pre-trained net is in cpu\n self.use_cuda = True\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom optimizer for a neural network using the MXNet library in Python. The optimizer will be based on the Adam algorithm, a popular optimization technique for training deep learning models.\n\nYour task is to complete the implementation of the custom optimizer class by adding the update function, which applies the Adam optimization algorithm to update the model parameters during training.\n\nThe Adam optimization algorithm involves maintaining two moving average accumulators: the first moment (mean) and the second moment (uncentered variance) of the gradients. These accumulators are then used to update the model parameters.\n\nYou are provided with a partial implementation of the custom optimizer class using MXNet. Your task is to complete the implementation by adding the update function according to the Adam optimization algorithm.\n\n```python\nfrom mxnet import optimizer\nimport mxnet as mx\nfrom mxnet import nd\n\nclass CustomAdam(optimizer.Optimizer):\n def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8, **kwargs):\n super(CustomAdam, self).__init__(**kwargs)\n self.learning_rate = learning_rate\n self.beta1 = beta1\n self.beta2 = beta2\n self.epsilon = epsilon\n self.t = 0\n self.m = {}\n self.v = {}\n\n def create_state(self, index, weight):\n self.m[index] = nd.zeros(weight.shape, weight.context)\n self.v[index] = nd.zeros(weight.shape, weight.context)\n\n def update(self, index, weight, grad, state):\n self.t += 1\n lr_t = self.learning_rate * (1. - self.beta2 ** self.t) ** 0.5 \/ (1. - self.beta1 ** self.t)\n\n self.m[index] = self.beta1 * self.m[index] + (1. - self.beta1) * grad\n self.v[index] = self.beta2 * self.v[index] + (1. - self.beta2) * grad.square()\n\n weight[:] -= lr_t * self.m[index] \/ (self.v[index].sqrt() + self.epsilon)\n```\n\nYour task is to complete the `update` function in the `CustomAdam` class. The `update` function takes four parameters:\n- `index`: The index of the weight parameter being updated.\n- `weight`: The weight parameter being updated.\n- `grad`: The gradient of the loss with respect to the weight parameter.\n- `state`: The state associated with the weight parameter.\n\nComplete the `update` function to apply the Adam optimization algorithm to update the `weight` parameter using the provided gradients and the accumulated first and second moments (`self.m` and `self.v`).","solution":"```python\n def update(self, index, weight, grad, state):\n self.t += 1\n lr_t = self.learning_rate * (1. - self.beta2 ** self.t) ** 0.5 \/ (1. - self.beta1 ** self.t)\n\n self.m[index] = self.beta1 * self.m[index] + (1. - self.beta1) * grad\n self.v[index] = self.beta2 * self.v[index] + (1. - self.beta2) * grad.square()\n\n weight[:] -= lr_t * self.m[index] \/ (self.v[index].sqrt() + self.epsilon)\n```\nThe `update` function applies the Adam optimization algorithm to update the `weight` parameter using the provided gradients and the accumulated first and second moments (`self.m` and `self.v`). The learning rate `lr_t` is adjusted based on the current time step `t`, and the weight is updated using the Adam update rule."} {"lang":"java","raw_index":104074,"index":1518,"seed":" {\r\n _frustumDataDirty = true;\r\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class to manage frustum data for a 3D rendering engine. The frustum represents the viewing volume of the camera and is used for culling objects that are outside the view. Your task is to complete the implementation of the `Frustum` class by adding a method to calculate the volume of the frustum.\n\nYou are provided with a partially implemented `Frustum` class in C++ as follows:\n\n```cpp\n#include \n\nclass Frustum {\nprivate:\n bool _frustumDataDirty;\n \/\/ Other frustum data members and methods are not shown for brevity\n\npublic:\n Frustum() : _frustumDataDirty(true) {}\n\n \/\/ Other frustum methods are not shown for brevity\n\n double calculateVolume() {\n if (_frustumDataDirty) {\n \/\/ Calculate and update frustum data\n _frustumDataDirty = false;\n }\n \/\/ TODO: Implement volume calculation\n return 0.0; \/\/ Placeholder\n }\n};\n\nint main() {\n Frustum frustum;\n std::cout << \"Frustum Volume: \" << frustum.calculateVolume() << std::endl;\n return 0;\n}\n```\n\nYour task is to complete the `calculateVolume` method in the `Frustum` class to accurately calculate the volume of the frustum. The frustum volume can be calculated using the formula for the volume of a frustum of a pyramid.\n\nThe formula for the volume of a frustum of a pyramid is given by:\n\\[ V = \\frac{1}{3}h(A_1 + A_2 + \\sqrt{A_1 \\cdot A_2}) \\]\nwhere:\n- \\( h \\) is the height of the frustum\n- \\( A_1 \\) and \\( A_2 \\) are the areas of the top and bottom faces of the frustum\n\nAssume that the necessary methods to retrieve the height, top area, and bottom area of the frustum are already implemented and can be accessed within the `calculateVolume` method.","solution":"```cpp\ndouble calculateVolume() {\n if (_frustumDataDirty) {\n \/\/ Calculate and update frustum data\n _frustumDataDirty = false;\n }\n double height = getHeight(); \/\/ Assume getHeight() returns the height of the frustum\n double topArea = getTopArea(); \/\/ Assume getTopArea() returns the area of the top face\n double bottomArea = getBottomArea(); \/\/ Assume getBottomArea() returns the area of the bottom face\n return (1.0 \/ 3.0) * height * (topArea + bottomArea + sqrt(topArea * bottomArea));\n}\n```\n\nIn the solution, the `calculateVolume` method first checks if the frustum data is dirty and needs to be recalculated. Then, it retrieves the height, top area, and bottom area of the frustum using the appropriate methods and applies the formula to calculate the volume of the frustum."} {"lang":"java","raw_index":34875,"index":3866,"seed":"\t\t\tex.printStackTrace();\n\t\t} catch (IOException ex) {\n\t\t\tex.printStackTrace();\n\t\t}\n\t\treturn HomeController.home(req);\n\t}\n\n\tpublic static void getUrgentPending(int eid, HttpServletRequest req, HttpServletResponse res)\n\t\t\tthrows JsonProcessingException, IOException {\n\t\tSystem.out.println(\"In getUrgentPending\");\n\t\ttry {\n\t\t\tList

fList = fdao.getUrgentPendingForms(eid);\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a method to calculate the total number of urgent pending forms for an employee in a company's system. The company's database contains a table of forms, each associated with an employee and marked as either urgent or pending. Your goal is to create a Java method that retrieves the total count of urgent pending forms for a given employee ID.\n\nYou are provided with a partial code snippet from the company's existing system. The `getUrgentPending` method is responsible for retrieving the urgent pending forms for a specific employee. The `fdao.getUrgentPendingForms(eid)` call within the method returns a list of Form objects representing the urgent pending forms for the employee with the ID `eid`. Your task is to complete the implementation of the `getUrgentPending` method to calculate and return the total count of urgent pending forms for the given employee ID.\n\nYour method should adhere to the following signature:\n```java\npublic static int getUrgentPendingCount(int eid) {\n \/\/ Your implementation here\n}\n```\n\nYou should assume the existence of a `Form` class with appropriate attributes and methods, and a `FormDAO` (fdao) object that provides access to the company's database.\n\nYour implementation should accurately calculate the total count of urgent pending forms for the specified employee ID and return this count as an integer.","solution":"```java\npublic static int getUrgentPendingCount(int eid) {\n try {\n List fList = fdao.getUrgentPendingForms(eid);\n int count = 0;\n for (Form form : fList) {\n if (form.isUrgent() && form.isPending()) {\n count++;\n }\n }\n return count;\n } catch (Exception e) {\n \/\/ Handle or log the exception as per the application's error handling strategy\n return -1; \/\/ Return a special value to indicate an error occurred\n }\n}\n```\nIn the solution, we complete the `getUrgentPendingCount` method by retrieving the list of urgent pending forms for the specified employee ID using the `fdao.getUrgentPendingForms(eid)` call. We then iterate through the list of forms, incrementing a counter for each form that is both urgent and pending. Finally, we return the total count of urgent pending forms for the given employee ID. If an exception occurs during the retrieval of forms, we handle it and return a special value (-1 in this case) to indicate an error."} {"lang":"python","raw_index":71920,"index":35265,"seed":" self.lb_idInfo.grid(row=0, column=1)\n self.lb_nomeInfo.grid(row=1, column=1)\n self.lb_marcaInfo.grid(row=2, column=1)\n self.lb_qtdInfo.grid(row=3, column=1)\n self.lb_precoInfo.grid(row=4, column=1)\n self.txt_discricao.grid(row=1, column=0)\n \n self.fr1.pack(side=LEFT, anchor=NW)\n self.fr2.pack(side=LEFT, anchor=NW)\n self.fr.pack()\n self.fr_descricao.pack(side=BOTTOM)\n self.lbfr_produto.pack()\n\n def inserir_dados(self, dados):\n id = dados[0]\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class for managing product information in a graphical user interface (GUI) application. The provided code snippet is a part of the class definition and includes the setup of GUI elements and a method for inserting product data. The GUI consists of several labels and text fields for displaying and inputting product information. The `inserir_dados` method is responsible for populating the GUI with data for a specific product.\n\nYour task is to complete the implementation of the `inserir_dados` method by parsing the input `dados` and updating the GUI elements with the corresponding product information. Additionally, you need to implement a method to calculate the total price of the product based on the quantity and unit price.\n\nComplete the following tasks:\n1. Implement the `inserir_dados` method to update the GUI elements with the product information provided in the `dados` parameter.\n2. Implement a method `calcular_preco_total` to calculate the total price of the product based on the quantity and unit price.\n\n```python\nclass ProductManager:\n def __init__(self, root):\n # Initialize GUI elements and layout\n # ...\n\n def inserir_dados(self, dados):\n # Update GUI elements with product information from dados\n # ...\n\n def calcular_preco_total(self, quantidade, preco_unitario):\n # Calculate the total price of the product\n # ...\n\n# Example usage\nproduct_manager = ProductManager(root)\nproduct_manager.inserir_dados([101, 'Product A', 'Brand X', 10, 25.0])\ntotal_price = product_manager.calcular_preco_total(10, 25.0)\n```","solution":"```python\nclass ProductManager:\n def __init__(self, root):\n # Initialize GUI elements and layout\n # ...\n\n def inserir_dados(self, dados):\n self.lb_idInfo.config(text=str(dados[0]))\n self.lb_nomeInfo.config(text=dados[1])\n self.lb_marcaInfo.config(text=dados[2])\n self.lb_qtdInfo.config(text=str(dados[3]))\n self.lb_precoInfo.config(text=str(dados[4]))\n\n def calcular_preco_total(self, quantidade, preco_unitario):\n return quantidade * preco_unitario\n\n# Example usage\nproduct_manager = ProductManager(root)\nproduct_manager.inserir_dados([101, 'Product A', 'Brand X', 10, 25.0])\ntotal_price = product_manager.calcular_preco_total(10, 25.0)\n```"} {"lang":"python","raw_index":29835,"index":10670,"seed":"class Error(Exception):\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a custom exception class and implementing a program that utilizes this exception to handle specific error conditions. \n\nCreate a Python class called `CustomError` that inherits from the built-in `Exception` class. The `CustomError` class should have a constructor that takes in a message as an argument and sets it as an instance variable. Additionally, the `CustomError` class should override the `__str__` method to return the error message.\n\nNext, implement a program that takes user input for a numerical value. If the input is less than 0, raise an instance of the `CustomError` class with the message \"Negative value not allowed\". If the input is greater than 100, raise an instance of the `CustomError` class with the message \"Value too large\". Otherwise, print the input value.\n\nYour program should handle these custom exceptions and print the error message when they are raised.","solution":"```python\nclass CustomError(Exception):\n def __init__(self, message):\n self.message = message\n\n def __str__(self):\n return self.message\n\ndef main():\n try:\n value = int(input(\"Enter a number: \"))\n if value < 0:\n raise CustomError(\"Negative value not allowed\")\n elif value > 100:\n raise CustomError(\"Value too large\")\n else:\n print(\"Input value:\", value)\n except CustomError as ce:\n print(\"Custom Error:\", ce)\n except ValueError:\n print(\"Invalid input. Please enter a valid number.\")\n\nif __name__ == \"__main__\":\n main()\n```\n\nIn this solution, we first define the `CustomError` class that inherits from the `Exception` class. It has a constructor to set the error message and overrides the `__str__` method to return the message.\n\nThe `main` function takes user input and raises instances of `CustomError` based on the input value. It handles these custom exceptions and prints the error message when they are raised. Additionally, it catches `ValueError` if the user input is not a valid number and provides an appropriate error message."} {"lang":"python","raw_index":92643,"index":35686,"seed":" output_filepath.write_bytes(net.SerializeToString())\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that serializes a neural network model and writes the serialized data to a specified file path. The function should take in a neural network model and a file path as input and use the `SerializeToString()` method to serialize the model and write the serialized data to the specified file path.\n\nCreate a function `serialize_neural_network` with the following signature:\n```python\ndef serialize_neural_network(model, file_path):\n pass\n```\n\nThe `model` parameter is an instance of a neural network model, and the `file_path` parameter is a string representing the file path where the serialized data should be written.\n\nYour task is to complete the `serialize_neural_network` function to serialize the provided neural network model using the `SerializeToString()` method and write the serialized data to the specified file path.","solution":"```python\ndef serialize_neural_network(model, file_path):\n with open(file_path, 'wb') as output_file:\n serialized_data = model.SerializeToString()\n output_file.write(serialized_data)\n```\n\nIn the solution, the `serialize_neural_network` function opens the specified file path in binary write mode and uses the `SerializeToString()` method of the `model` to serialize the neural network model. The serialized data is then written to the opened file, effectively serializing the neural network model and saving it to the specified file path."} {"lang":"rust","raw_index":66450,"index":2755,"seed":"src\/v2_0_1\/datatypes\/transaction_type.rs\nuse crate::v2_0_1::enumerations::charging_state_enum_type::ChargingStateEnumType;\nuse crate::v2_0_1::enumerations::reason_enum_type::ReasonEnumType;\n\n\/\/\/ TransactionType is used by: TransactionEventRequest\n#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct TransactionType {\n pub transaction_id: String,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub charging_state: Option,\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with designing a Rust program to manage electric vehicle charging transactions. The provided code snippet is a partial implementation of a Rust struct representing a transaction type. Your task is to complete the implementation of the `TransactionType` struct and write a function to process a transaction event request.\n\nThe `TransactionType` struct has the following fields:\n- `transaction_id`: A string representing the unique identifier for the transaction.\n- `charging_state`: An optional field representing the current charging state, which can be one of the values from the `ChargingStateEnumType` enumeration.\n\nYour task is to:\n1. Complete the implementation of the `TransactionType` struct by adding the following fields:\n - `start_time`: A string representing the start time of the transaction.\n - `end_time`: A string representing the end time of the transaction.\n - `energy_delivered`: A floating-point number representing the amount of energy delivered during the transaction.\n\n2. Write a function `process_transaction_event` that takes a `TransactionType` object as input and processes the transaction event request. The function should perform the following tasks:\n - Calculate the duration of the transaction using the start and end times.\n - Calculate the total cost of the transaction based on the energy delivered and the charging state.\n - Return a tuple containing the duration of the transaction and the total cost.\n\nYou can assume that the `ChargingStateEnumType` enumeration and the `ReasonEnumType` enumeration are already defined and imported correctly.","solution":"```rust\nuse crate::v2_0_1::enumerations::charging_state_enum_type::ChargingStateEnumType;\n\n#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct TransactionType {\n pub transaction_id: String,\n pub charging_state: Option,\n pub start_time: String,\n pub end_time: String,\n pub energy_delivered: f64,\n}\n\nfn process_transaction_event(transaction: &TransactionType) -> (String, f64) {\n \/\/ Calculate the duration of the transaction\n let start = parse_time(&transaction.start_time);\n let end = parse_time(&transaction.end_time);\n let duration = end.duration_since(start).as_secs();\n\n \/\/ Calculate the total cost of the transaction based on the energy delivered and the charging state\n let cost = match transaction.charging_state {\n Some(ChargingStateEnumType::Fast) => transaction.energy_delivered * 0.15,\n Some(ChargingStateEnumType::Slow) => transaction.energy_delivered * 0.10,\n _ => transaction.energy_delivered * 0.12,\n };\n\n (format!(\"{} seconds\", duration), cost)\n}\n\nfn parse_time(time_str: &str) -> DateTime {\n \/\/ Implement the logic to parse the time string and return a DateTime object\n \/\/ Example: DateTime::parse_from_str(time_str, \"%Y-%m-%dT%H:%M:%S\").unwrap()\n}\n```\nIn the solution, the `TransactionType` struct is completed with the additional fields `start_time`, `end_time`, and `energy_delivered`. The `process_transaction_event` function calculates the duration of the transaction and the total cost based on the energy delivered and the charging state. The `parse_time` function is a placeholder for the logic to parse the time string into a `DateTime` object."} {"lang":"python","raw_index":131587,"index":3374,"seed":" self.assertEqual(f.read(), b\"\")\n with LZMAFile(BytesIO(COMPRESSED_RAW_1),\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python function that can compress and decompress a given string using the LZMA algorithm. The LZMA algorithm is a data compression algorithm that uses a dictionary compression scheme and achieves a high compression ratio. Your task is to create a class `LZMACompressor` with two methods: `compress` and `decompress`.\n\nThe `compress` method should take a string as input and return the compressed bytes using the LZMA algorithm. The `decompress` method should take the compressed bytes as input and return the original decompressed string.\n\nYour implementation should use the `lzma` module in Python, which provides support for LZMA compression and decompression.\n\nYour class should be able to handle various types of input strings, including empty strings and strings with different character encodings.\n\nYour task is to complete the implementation of the `LZMACompressor` class by filling in the `compress` and `decompress` methods.\n\n```python\nimport lzma\n\nclass LZMACompressor:\n def compress(self, data):\n # Implement the compression logic using the lzma module\n compressed_data = lzma.compress(data.encode())\n return compressed_data\n\n def decompress(self, compressed_data):\n # Implement the decompression logic using the lzma module\n decompressed_data = lzma.decompress(compressed_data).decode()\n return decompressed_data\n\n# Example usage\ncompressor = LZMACompressor()\noriginal_data = \"This is a sample string for LZMA compression and decompression.\"\ncompressed_data = compressor.compress(original_data)\ndecompressed_data = compressor.decompress(compressed_data)\nprint(decompressed_data) # Output: \"This is a sample string for LZMA compression and decompression.\"\n```","solution":"```python\nimport lzma\n\nclass LZMACompressor:\n def compress(self, data):\n # Implement the compression logic using the lzma module\n compressed_data = lzma.compress(data.encode())\n return compressed_data\n\n def decompress(self, compressed_data):\n # Implement the decompression logic using the lzma module\n decompressed_data = lzma.decompress(compressed_data).decode()\n return decompressed_data\n\n# Example usage\ncompressor = LZMACompressor()\noriginal_data = \"This is a sample string for LZMA compression and decompression.\"\ncompressed_data = compressor.compress(original_data)\ndecompressed_data = compressor.decompress(compressed_data)\nprint(decompressed_data) # Output: \"This is a sample string for LZMA compression and decompression.\"\n```"} {"lang":"php","raw_index":32246,"index":245,"seed":"\nnamespace App\\Http\\Controllers\\Api;\n\nuse App\\Http\\Controllers\\ApiController;\n\nclass IndexController extends ApiController\n{\n\n public function index(): \\Illuminate\\Http\\JsonResponse\n {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a PHP class that manages a simple inventory system for a small retail store. The class should allow for adding and removing items from the inventory, as well as retrieving the current inventory count for a specific item.\n\nYour task is to implement the `Inventory` class with the following methods:\n\n1. `__construct()`: The constructor should initialize an empty inventory array.\n\n2. `addItem($item, $quantity)`: This method should add the specified quantity of the item to the inventory. If the item already exists in the inventory, the quantity should be incremented by the specified amount. If the item is not present, it should be added to the inventory with the specified quantity.\n\n3. `removeItem($item, $quantity)`: This method should remove the specified quantity of the item from the inventory. If the item's quantity becomes zero as a result of this operation, it should be removed from the inventory.\n\n4. `getInventoryCount($item)`: This method should return the current quantity of the specified item in the inventory. If the item is not found in the inventory, it should return 0.\n\nYou should also create a simple test script to demonstrate the functionality of the `Inventory` class.\n\nImplement the `Inventory` class and the test script to showcase its usage.","solution":"```php\nclass Inventory\n{\n private $inventory;\n\n public function __construct()\n {\n $this->inventory = [];\n }\n\n public function addItem($item, $quantity)\n {\n if (array_key_exists($item, $this->inventory)) {\n $this->inventory[$item] += $quantity;\n } else {\n $this->inventory[$item] = $quantity;\n }\n }\n\n public function removeItem($item, $quantity)\n {\n if (array_key_exists($item, $this->inventory)) {\n $this->inventory[$item] -= $quantity;\n if ($this->inventory[$item] <= 0) {\n unset($this->inventory[$item]);\n }\n }\n }\n\n public function getInventoryCount($item)\n {\n return array_key_exists($item, $this->inventory) ? $this->inventory[$item] : 0;\n }\n}\n\n\/\/ Test script\n$inventory = new Inventory();\n\n$inventory->addItem('apple', 10);\n$inventory->addItem('banana', 5);\n$inventory->addItem('apple', 5);\n\necho \"Current inventory count for apple: \" . $inventory->getInventoryCount('apple') . PHP_EOL; \/\/ Output: 15\necho \"Current inventory count for banana: \" . $inventory->getInventoryCount('banana') . PHP_EOL; \/\/ Output: 5\n\n$inventory->removeItem('apple', 8);\n\necho \"Current inventory count for apple: \" . $inventory->getInventoryCount('apple') . PHP_EOL; \/\/ Output: 7\n\n$inventory->removeItem('apple', 7);\n\necho \"Current inventory count for apple: \" . $inventory->getInventoryCount('apple') . PHP_EOL; \/\/ Output: 0\n```"} {"lang":"python","raw_index":91163,"index":22382,"seed":" __name__,\n)\n\n\n@blueprint.route(\"\/login\", methods=[\"POST\", \"GET\"])\n@rate_limiter.limit(\"6\/minute\")\ndef login():\n if flask_login.current_user.is_authenticated:\n return redirect(url_for(current_app.config[\"INDEX_ROUTE\"]))\n\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a rate limiter decorator for a Flask application. The rate limiter should restrict the number of requests to a specific route within a given time frame. Your task is to implement the `rate_limiter` decorator function that will limit the number of requests to the specified route.\n\nThe `rate_limiter` decorator takes a single argument in the format \"x\/period\", where \"x\" is the maximum number of requests allowed and \"period\" is the time frame for the limit (e.g., \"10\/minute\" allows 10 requests per minute).\n\nYour implementation should ensure that when the maximum number of requests is exceeded within the specified time frame, subsequent requests to the decorated route are blocked and an appropriate error response is returned.\n\nYou should assume the existence of a Flask blueprint named `blueprint` and a `LoginForm` class for handling user login forms. Additionally, the `User` model is assumed to be available for querying user information.\n\nYour task is to complete the `rate_limiter` decorator function and ensure that it correctly limits the number of requests to the specified route.","solution":"```python\nimport time\nfrom functools import wraps\nfrom flask import request, jsonify\n\ndef rate_limiter(limit):\n def decorator(func):\n request_log = []\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n current_time = time.time()\n request_log.append(current_time)\n\n # Remove requests that are older than the specified time frame\n request_log[:] = [req_time for req_time in request_log if current_time - req_time <= limit]\n\n if len(request_log) > limit:\n return jsonify({\"error\": \"Rate limit exceeded. Try again later.\"}), 429 # 429 status code for \"Too Many Requests\"\n else:\n return func(*args, **kwargs)\n\n return wrapper\n return decorator\n\n# Usage example:\n@blueprint.route(\"\/login\", methods=[\"POST\", \"GET\"])\n@rate_limiter(\"6\/minute\")\ndef login():\n # Existing login route implementation\n pass\n```\n\nIn this solution, the `rate_limiter` decorator function takes the limit argument in the format \"x\/period\" and returns a decorator function. The inner decorator function maintains a request log and checks the number of requests within the specified time frame. If the limit is exceeded, it returns a 429 status code with an appropriate error message. Otherwise, it allows the request to proceed to the decorated route."} {"lang":"php","raw_index":389,"index":2017,"seed":" if (!$this->Scheme) {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class that represents a URL and provides methods for manipulating its components. Your task is to complete the implementation of the `URL` class by adding a method `getScheme()` that returns the scheme of the URL. The scheme is the part of the URL before the \":\/\/\" delimiter. If the scheme is not present in the URL, the method should return an empty string.\n\nYou are provided with a partial implementation of the `URL` class in PHP. The `URL` class has a private property `$url` that stores the URL string. You need to implement the `getScheme()` method to extract and return the scheme from the URL.\n\nThe code snippet provided is a part of the `getScheme()` method. It checks if the scheme is not set in the URL and performs a specific action if it is not set.\n\nYour task is to complete the `getScheme()` method to extract and return the scheme from the URL.\n\n```php\nclass URL {\n private $url;\n\n public function __construct($url) {\n $this->url = $url;\n }\n\n public function getScheme() {\n if (!$this->Scheme) {\n \/\/ Your implementation here\n }\n }\n}\n\n$url = new URL(\"https:\/\/www.example.com\");\necho $url->getScheme(); \/\/ Should output \"https\"\n```","solution":"```php\npublic function getScheme() {\n $parts = parse_url($this->url);\n if (isset($parts['scheme'])) {\n return $parts['scheme'];\n } else {\n return \"\";\n }\n}\n```\n\nIn the `getScheme()` method, we use the `parse_url` function to extract the components of the URL. If the scheme is present in the URL, we return it; otherwise, we return an empty string. This solution correctly handles the extraction of the scheme from the URL and fulfills the requirements of the problem."} {"lang":"python","raw_index":49462,"index":8554,"seed":" alt.Chart(data, height=height, width=width)\n .mark_tick(opacity=opacity, thickness=2)\n .encode(x=key + \":N\", y=value, **enc_args)\n )\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that generates a visualization using Altair, a declarative statistical visualization library for Python. The function should take in a dataset, as well as various visualization parameters, and produce a bar chart with the specified attributes.\n\nYou are given the following code snippet as a starting point:\n```python\nalt.Chart(data, height=height, width=width)\n .mark_tick(opacity=opacity, thickness=2)\n .encode(x=key + \":N\", y=value, **enc_args)\n```\n\nYour task is to create a function `generate_bar_chart` that accepts the following parameters:\n- `data`: The dataset to be visualized.\n- `height`: The height of the chart.\n- `width`: The width of the chart.\n- `opacity`: The opacity of the bars in the chart.\n- `key`: The key for encoding the x-axis.\n- `value`: The value for encoding the y-axis.\n- `enc_args`: Additional encoding arguments as keyword arguments.\n\nThe function should use Altair to generate a bar chart based on the provided parameters and return the resulting visualization.","solution":"```python\nimport altair as alt\n\ndef generate_bar_chart(data, height, width, opacity, key, value, **enc_args):\n chart = alt.Chart(data, height=height, width=width).mark_bar(opacity=opacity).encode(\n x=alt.X(key + \":N\"),\n y=alt.Y(value),\n **enc_args\n )\n return chart\n```\n\nThe `generate_bar_chart` function creates an Altair chart using the provided parameters and returns the resulting visualization. It uses the `alt.Chart` method to initialize the chart, sets the height and width, specifies the mark type as a bar with the given opacity, and encodes the x and y axes based on the provided key, value, and additional encoding arguments."} {"lang":"python","raw_index":136846,"index":20819,"seed":" fig = plt.gcf()\n fig.set_size_inches(8, 4)\n\n \n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that generates a bar chart with specific characteristics. The function should take in a list of data points and their corresponding labels, and produce a bar chart with the following requirements:\n- The bars should be colored in a gradient of blue, with lighter shades for smaller values and darker shades for larger values.\n- The figure size should be set to 8 inches in width and 4 inches in height.\n\nWrite a Python function `generate_gradient_bar_chart(data, labels)` that takes in two parameters:\n- `data`: a list of numerical data points.\n- `labels`: a list of corresponding labels for each data point.\n\nThe function should produce the described bar chart and return the matplotlib figure object.","solution":"```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef generate_gradient_bar_chart(data, labels):\n fig = plt.figure(figsize=(8, 4))\n ax = fig.add_subplot(111)\n\n # Create a color gradient based on data values\n colors = plt.cm.Blues(np.linspace(0, 1, len(data)))\n\n # Plot the bars with gradient colors\n bars = ax.bar(labels, data, color=colors)\n\n return fig\n```\n\nThe `generate_gradient_bar_chart` function creates a figure with the specified size and then adds a bar plot to it. The color gradient for the bars is generated using the `plt.cm.Blues` colormap, which maps lighter shades to smaller values and darker shades to larger values. The function returns the matplotlib figure object containing the bar chart."} {"lang":"python","raw_index":60698,"index":28364,"seed":" self.vertexElementData.append(data)\n return len(self.vertexElementData) - 1\n \n def AddFaces(self, data, type):\n self.faces[\"indexType\"] = type\n self.faces[\"data\"] = data\n self.primitiveData[\"numFaces\"] = len(data) \/\/ 3 if len(data) > 0 else 0\n return EPODErrorCodes.eNoError\n\n def AddElement(self, semantic, type, numComponents, stride, offset, dataIndex):\n if semantic in self.vertexElements:\n return EPODErrorCodes.eKeyAlreadyExists\n self.vertexElements[semantic] = {\n \"semantic\": semantic,\n \"dataType\": type,\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class for managing 3D mesh data in a graphics application. The given code snippet is part of the class definition and shows three methods: `AddVertex`, `AddFaces`, and `AddElement`. The `AddVertex` method appends vertex data to a list and returns the index of the added data. The `AddFaces` method sets the faces data and type, and the `AddElement` method adds an element to the mesh data.\n\nYour task is to implement the remaining parts of the class, including the constructor and any other necessary methods, to create a complete and functional mesh data management class. The class should support adding vertex data, faces data, and elements, and should handle errors appropriately.\n\nYour implementation should include the following:\n- A constructor to initialize the necessary data structures.\n- Methods to add vertex data, faces data, and elements to the mesh.\n- Error handling for cases such as duplicate vertex elements.\n\nYour implementation should be able to handle various types of mesh data and provide appropriate error codes when necessary.\n\nWrite the complete class definition for managing 3D mesh data, including the constructor and any other necessary methods.","solution":"```python\nclass MeshData:\n def __init__(self):\n self.vertexElementData = []\n self.faces = {\"indexType\": None, \"data\": None}\n self.primitiveData = {\"numFaces\": 0}\n self.vertexElements = {}\n\n def AddVertex(self, data):\n self.vertexElementData.append(data)\n return len(self.vertexElementData) - 1\n\n def AddFaces(self, data, type):\n self.faces[\"indexType\"] = type\n self.faces[\"data\"] = data\n self.primitiveData[\"numFaces\"] = len(data) \/\/ 3 if len(data) > 0 else 0\n return EPODErrorCodes.eNoError\n\n def AddElement(self, semantic, type, numComponents, stride, offset, dataIndex):\n if semantic in self.vertexElements:\n return EPODErrorCodes.eKeyAlreadyExists\n self.vertexElements[semantic] = {\n \"semantic\": semantic,\n \"dataType\": type,\n \"numComponents\": numComponents,\n \"stride\": stride,\n \"offset\": offset,\n \"dataIndex\": dataIndex\n }\n return EPODErrorCodes.eNoError\n\nclass EPODErrorCodes:\n eNoError = 0\n eKeyAlreadyExists = 1\n```\n\nIn the solution, the `MeshData` class is defined with a constructor that initializes the necessary data structures. The `AddVertex`, `AddFaces`, and `AddElement` methods are implemented as per the given code snippet, along with appropriate error handling for adding elements. Additionally, an `EPODErrorCodes` class is defined to represent error codes for the mesh data management operations."} {"lang":"cpp","raw_index":26926,"index":1394,"seed":"\r\n this file uses filelist.lib to build a dat file from xml file\r\n\r\nAuthor:\r\n\r\n (kmarok) 01-May-2000\r\n\r\nRevision History:\r\n\r\n--*\/\r\n\r\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a file conversion utility that reads data from an XML file and writes it to a DAT file using a provided library. The file `filelist.lib` contains the necessary functions for this conversion. Your goal is to write a program that utilizes `filelist.lib` to perform the conversion.\n\nYour task is to write a function `convertXmlToDat` that takes the filename of the input XML file and the filename of the output DAT file as input parameters. The function should use the functions provided in `filelist.lib` to read data from the XML file and write it to the DAT file.\n\nYou are provided with the following information:\n- The `filelist.lib` library contains the following functions:\n - `openXmlFile(filename)`: Opens the XML file specified by `filename` and returns a file handle.\n - `readXmlData(fileHandle)`: Reads data from the XML file specified by `fileHandle` and returns the data as a string.\n - `closeXmlFile(fileHandle)`: Closes the XML file specified by `fileHandle`.\n - `openDatFile(filename)`: Opens the DAT file specified by `filename` and returns a file handle.\n - `writeDatData(fileHandle, data)`: Writes the data specified by `data` to the DAT file specified by `fileHandle`.\n - `closeDatFile(fileHandle)`: Closes the DAT file specified by `fileHandle`.\n\nYou need to implement the `convertXmlToDat` function using the provided library functions to achieve the file conversion from XML to DAT.","solution":"```python\ndef convertXmlToDat(xml_filename, dat_filename):\n xml_file_handle = openXmlFile(xml_filename)\n xml_data = readXmlData(xml_file_handle)\n closeXmlFile(xml_file_handle)\n\n dat_file_handle = openDatFile(dat_filename)\n writeDatData(dat_file_handle, xml_data)\n closeDatFile(dat_file_handle)\n```\n\nIn the solution, the `convertXmlToDat` function first opens the XML file using `openXmlFile`, reads the data from the XML file using `readXmlData`, and then closes the XML file using `closeXmlFile`. Subsequently, it opens the DAT file using `openDatFile`, writes the XML data to the DAT file using `writeDatData`, and finally closes the DAT file using `closeDatFile`. This sequence of operations achieves the conversion of data from the XML file to the DAT file using the provided library functions."} {"lang":"java","raw_index":111785,"index":3979,"seed":" * @return Will always return {@code null}.\n *\/\n @Override public R reduce(List results) {\n return null;\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom reducer function for a distributed computing framework. The framework processes a list of `ComputeJobResult` objects and requires a custom reduction operation to aggregate the results. Your task is to implement the `reduce` method that takes a list of `ComputeJobResult` objects and returns a single result of type `R`.\n\nThe `ComputeJobResult` class represents the result of a computation job and has the following structure:\n```java\npublic class ComputeJobResult {\n \/\/ Fields and methods not shown\n}\n```\n\nYour implementation should adhere to the following requirements:\n- The `reduce` method should be implemented in a class that extends or implements the appropriate interface or superclass.\n- The method should return a result of type `R`.\n- The method should always return `null` as indicated by the code snippet provided.\n\nYour task is to write the implementation for the `reduce` method that satisfies the given requirements and returns `null` as specified.","solution":"```java\npublic class CustomReducer implements Reducer {\n @Override\n public R reduce(List results) {\n return null;\n }\n}\n```\nIn the solution, we create a class `CustomReducer` that implements the `Reducer` interface or extends the appropriate superclass. The `reduce` method is overridden to return `null` as specified in the code snippet. This implementation satisfies the requirements and returns the expected result."} {"lang":"python","raw_index":112977,"index":32757,"seed":"\tif gname in girls_names:\n\t\tprint(f\"{gname} was a popular girl's name between 2000 and 2009.\")\n\telse:\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program that processes a list of popular girl's names from the 2000s and provides information about their popularity. Your program should take a user input for a girl's name and determine if it was a popular name between 2000 and 2009. If the input name is found in the list of popular girl's names, the program should print a message indicating its popularity during that period. If the input name is not found in the list, the program should prompt the user to input another name.\n\nYour program should use the following code snippet as a starting point:\n```python\ngirls_names = [\"Emma\", \"Olivia\", \"Sophia\", \"Isabella\", \"Ava\", \"Emily\", \"Madison\", \"Abigail\", \"Chloe\", \"Mia\"]\ngname = input(\"Enter a girl's name: \")\nif gname in girls_names:\n print(f\"{gname} was a popular girl's name between 2000 and 2009.\")\nelse:\n # Your code for handling names not found in the list goes here\n```\n\nWrite a program that fulfills the requirements outlined above.","solution":"```python\ngirls_names = [\"Emma\", \"Olivia\", \"Sophia\", \"Isabella\", \"Ava\", \"Emily\", \"Madison\", \"Abigail\", \"Chloe\", \"Mia\"]\n\ndef check_popularity(name):\n if name in girls_names:\n print(f\"{name} was a popular girl's name between 2000 and 2009.\")\n else:\n print(f\"{name} was not a popular girl's name between 2000 and 2009. Please enter another name.\")\n\ndef main():\n while True:\n gname = input(\"Enter a girl's name: \")\n check_popularity(gname)\n choice = input(\"Do you want to check another name? (yes\/no): \")\n if choice.lower() != \"yes\":\n break\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe solution defines a list `girls_names` containing popular girl's names from the 2000s. The `check_popularity` function takes a name as input and checks if it is in the list. If the name is found, it prints a message indicating its popularity; otherwise, it prompts the user to enter another name. The `main` function repeatedly prompts the user for input and calls `check_popularity` until the user chooses to stop."} {"lang":"swift","raw_index":121332,"index":2884,"seed":"\tvar age: Int {\n\t\tget {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Swift program to manage a library's book inventory. The program should include a Book class with properties for title, author, and quantity. Additionally, the program should implement a method to lend out a book, reducing the quantity by one, and another method to return a book, increasing the quantity by one. \n\nYour task is to complete the Book class by implementing the lendBook and returnBook methods. The lendBook method should decrease the quantity by one if the book is available, and the returnBook method should increase the quantity by one if the book is currently on loan. If the quantity is already at 0, the lendBook method should not change the quantity, and if the quantity is at its maximum, the returnBook method should not change the quantity.\n\nBelow is the initial code snippet for the Book class:\n\n```swift\nclass Book {\n let title: String\n let author: String\n var quantity: Int\n \n init(title: String, author: String, quantity: Int) {\n self.title = title\n self.author = author\n self.quantity = quantity\n }\n \n func lendBook() {\n \/\/ Implement this method\n }\n \n func returnBook() {\n \/\/ Implement this method\n }\n}\n```\n\nYour task is to complete the implementation of the lendBook and returnBook methods within the Book class to fulfill the requirements outlined above.","solution":"```swift\nclass Book {\n let title: String\n let author: String\n var quantity: Int\n \n init(title: String, author: String, quantity: Int) {\n self.title = title\n self.author = author\n self.quantity = quantity\n }\n \n func lendBook() {\n if quantity > 0 {\n quantity -= 1\n print(\"Book \\(title) by \\(author) has been lent out.\")\n } else {\n print(\"Book \\(title) by \\(author) is currently not available.\")\n }\n }\n \n func returnBook() {\n if quantity < 5 {\n quantity += 1\n print(\"Book \\(title) by \\(author) has been returned.\")\n } else {\n print(\"Book \\(title) by \\(author) cannot be returned as the maximum quantity has been reached.\")\n }\n }\n}\n```\n\nThe lendBook method checks if the quantity is greater than 0 before decreasing it by 1 and prints a message accordingly. The returnBook method checks if the quantity is less than 5 (assuming a maximum quantity of 5) before increasing it by 1 and prints a message accordingly."} {"lang":"python","raw_index":42659,"index":3073,"seed":" :type: str\n \"\"\"\n if id is None:\n raise ValueError(\"Invalid value for `id`, must not be `None`\")\n\n self._id = id\n\n @property\n def object(self):\n \"\"\"\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python class that represents a simple object with an identifier. The class should have a method to set the identifier and a property to retrieve the object. Your task is to complete the implementation of the class by adding the necessary methods.\n\nYou are given the following code snippet as a starting point:\n\n```python\nclass SimpleObject:\n def __init__(self):\n self._id = None\n\n def set_id(self, id):\n \"\"\"\n Sets the identifier for the object.\n\n :param id: str\n \"\"\"\n if id is None:\n raise ValueError(\"Invalid value for `id`, must not be `None`\")\n\n self._id = id\n\n @property\n def object(self):\n \"\"\"\n Retrieves the object.\n\n :return: str\n \"\"\"\n return f\"Object with ID: {self._id}\"\n```\n\nYour task is to complete the `SimpleObject` class by implementing the `set_id` method to set the identifier for the object and the `object` property to retrieve the object with its identifier. Ensure that the `set_id` method raises a `ValueError` if the provided identifier is `None`.","solution":"```python\nclass SimpleObject:\n def __init__(self):\n self._id = None\n\n def set_id(self, id):\n \"\"\"\n Sets the identifier for the object.\n\n :param id: str\n \"\"\"\n if id is None:\n raise ValueError(\"Invalid value for `id`, must not be `None`\")\n\n self._id = id\n\n @property\n def object(self):\n \"\"\"\n Retrieves the object.\n\n :return: str\n \"\"\"\n return f\"Object with ID: {self._id}\"\n```\n\nThe solution completes the `SimpleObject` class by implementing the `set_id` method to set the identifier for the object and the `object` property to retrieve the object with its identifier. The `set_id` method raises a `ValueError` if the provided identifier is `None`, ensuring the class behaves as expected."} {"lang":"python","raw_index":46419,"index":37494,"seed":" print(\"Not a valid JSON\")\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that validates a given JSON string. The function should check if the input string is a valid JSON and return a specific message based on the validation result.\n\nWrite a function `validate_json(json_string)` that takes a string `json_string` as input and returns a message based on the validation result:\n- If the input string is a valid JSON, the function should return \"Valid JSON\".\n- If the input string is not a valid JSON, the function should return \"Not a valid JSON\".\n\nFor example, if the input string is a valid JSON like `{\"name\": \"John\", \"age\": 30}`, the function should return \"Valid JSON\". If the input string is not a valid JSON like `{\"name\": \"John\", \"age\": 30`, the function should return \"Not a valid JSON\".\n\nYou can assume that the input string will be a well-formed JSON string without any additional whitespace.","solution":"```python\nimport json\n\ndef validate_json(json_string):\n try:\n json.loads(json_string)\n return \"Valid JSON\"\n except ValueError:\n return \"Not a valid JSON\"\n\n# Test cases\nprint(validate_json('{\"name\": \"John\", \"age\": 30}')) # Output: Valid JSON\nprint(validate_json('{\"name\": \"John\", \"age\": 30')) # Output: Not a valid JSON\n```"} {"lang":"php","raw_index":143005,"index":3564,"seed":"use ContactBundle\\Entity\\Contact;\nuse Symfony\\Component\\Form\\AbstractType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\BirthdayType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\EmailType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\FileType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\TelType;\nuse Symfony\\Component\\Form\\FormBuilderInterface;\nuse Symfony\\Component\\OptionsResolver\\OptionsResolver;\n\nclass ContactType extends AbstractType\n{\n public function buildForm(FormBuilderInterface $builder, array $options)\n {\n $builder\n ->add('first_name', null, ['required' => true])\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a form for managing contacts in a Symfony application. The form should include fields for first name, last name, email, birthday, and phone number. Additionally, the form should allow users to upload a profile picture. Your task is to complete the `ContactType` class by adding the necessary form fields and configurations to meet the requirements.\n\nComplete the `ContactType` class by adding the following form fields and configurations:\n1. Add a field for the last name with the appropriate type and configuration.\n2. Add a field for the email with the appropriate type and configuration.\n3. Add a field for the birthday with the appropriate type and configuration.\n4. Add a field for the phone number with the appropriate type and configuration.\n5. Add a field for uploading a profile picture with the appropriate type and configuration.\n\nEnsure that the first name field is marked as required.","solution":"```php\nuse ContactBundle\\Entity\\Contact;\nuse Symfony\\Component\\Form\\AbstractType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\BirthdayType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\EmailType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\FileType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\TelType;\nuse Symfony\\Component\\Form\\FormBuilderInterface;\nuse Symfony\\Component\\OptionsResolver\\OptionsResolver;\n\nclass ContactType extends AbstractType\n{\n public function buildForm(FormBuilderInterface $builder, array $options)\n {\n $builder\n ->add('first_name', null, ['required' => true])\n ->add('last_name', null, ['required' => true]) \/\/ Add last name field\n ->add('email', EmailType::class) \/\/ Add email field\n ->add('birthday', BirthdayType::class) \/\/ Add birthday field\n ->add('phone_number', TelType::class) \/\/ Add phone number field\n ->add('profile_picture', FileType::class, ['required' => false]); \/\/ Add profile picture field\n }\n\n public function configureOptions(OptionsResolver $resolver)\n {\n $resolver->setDefaults([\n 'data_class' => Contact::class,\n ]);\n }\n}\n```\n\nIn the solution, the `ContactType` class is completed by adding the required form fields and configurations as per the problem description. The last name, email, birthday, phone number, and profile picture fields are added with appropriate types and configurations. The first name field is marked as required, and the `configureOptions` method sets the data class for the form."} {"lang":"python","raw_index":23572,"index":9239,"seed":"0\nfrom django.apps import AppConfig\n\n\nclass TransactionsConfig(AppConfig):\n name = 'apps.transactions'\n verbose_name = \"Transactions\"\n\n def ready(self):\n import apps.transactions.signals\n\n\ndefault_app_config = 'apps.transactions.TransactionsConfig'\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Django application for managing transactions. The provided code snippet is a part of the Django app configuration for the transactions module. The `TransactionsConfig` class is responsible for configuring the app and setting up any necessary signals.\n\nYour task is to implement a Django model for transactions and create a signal to perform a specific action whenever a new transaction is created.\n\nDefine a Django model named `Transaction` with the following fields:\n- `amount` (DecimalField): to store the transaction amount.\n- `description` (CharField): to store a brief description of the transaction.\n- `timestamp` (DateTimeField): to store the date and time of the transaction.\n\nAdditionally, create a signal that triggers a function named `handle_new_transaction` whenever a new `Transaction` object is created. The `handle_new_transaction` function should simply print a message to the console indicating the creation of a new transaction.\n\nWrite the necessary code to achieve the above requirements and ensure that the signal is properly connected to the `Transaction` model.","solution":"```python\n# apps\/transactions\/models.py\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nclass Transaction(models.Model):\n amount = models.DecimalField(max_digits=10, decimal_places=2)\n description = models.CharField(max_length=100)\n timestamp = models.DateTimeField(auto_now_add=True)\n\n# apps\/transactions\/signals.py\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom .models import Transaction\n\n@receiver(post_save, sender=Transaction)\ndef handle_new_transaction(sender, instance, created, **kwargs):\n if created:\n print(\"A new transaction has been created:\", instance.amount, instance.description, instance.timestamp)\n```\n\nIn the solution, a Django model named `Transaction` is defined with the specified fields. Additionally, a signal is created using the `@receiver` decorator to handle the `post_save` event for the `Transaction` model. The `handle_new_transaction` function is triggered whenever a new `Transaction` object is created, printing a message to the console with the transaction details."} {"lang":"php","raw_index":95131,"index":606,"seed":" @include('projects.index')\n @break\n @case('about')\n @include('profile.publisher.about')\n @break\n @default\n @endswitch\n@endsection\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program that simulates a simple text-based content management system. The system will process a series of directives and include statements to render different sections of a web page based on the provided input.\n\nYou are given a code snippet that represents a simplified version of the directives and includes used in a Blade template in Laravel, a popular PHP framework. The snippet is as follows:\n\n```\n@include('projects.index')\n@break\n@case('about')\n@include('profile.publisher.about')\n@break\n@default\n@endswitch\n@endsection\n```\n\nYour task is to implement a program that processes a series of directives and includes similar to the given code snippet. The program should render the appropriate sections based on the provided input.\n\nThe program should accept a series of directives and includes as input. Each directive will be in the form of a keyword followed by a parameter, and each include will be in the form of an include statement with a file path. The program should process the input and render the appropriate sections based on the directives and includes.\n\nThe program should follow these rules:\n- If a directive is `@case`, the program should render the included file specified in the subsequent `@include` statement.\n- If a directive is `@default`, the program should stop processing further directives and includes.\n- If a directive is `@break`, the program should skip to the next directive.\n- If an include statement is encountered, the program should render the included file specified in the include statement.\n\nYour task is to write a program that takes a series of directives and includes as input and renders the appropriate sections based on the provided input.","solution":"```python\ndef process_directives(directives):\n for directive in directives:\n if directive.startswith('@case'):\n include_file = directive.split(' ')[1][1:-1] # Extract the file path from the directive\n render_section(include_file)\n elif directive == '@default':\n break\n elif directive == '@break':\n continue\n\ndef render_section(file_path):\n # Simulate rendering the section by printing the file path\n print(f\"Rendering section from file: {file_path}\")\n\n# Example usage\ndirectives = [\n \"@include('projects.index')\",\n \"@break\",\n \"@case('about')\",\n \"@include('profile.publisher.about')\",\n \"@break\",\n \"@default\"\n]\n\nprocess_directives(directives)\n```\n\nIn this solution, the `process_directives` function iterates through the provided directives and includes, and based on the type of directive, it either renders the included file or skips to the next directive. The `render_section` function simulates rendering the section by printing the file path. The example usage demonstrates how the `process_directives` function can be used to process a series of directives and includes."} {"lang":"java","raw_index":87331,"index":2375,"seed":" try {\n CommandLine commandLine = parser.parse(options, args);\n packageName = commandLine.getOptionValue(\"p\", null);\n outputDir = commandLine.getOptionValue(\"o\", \".\");\n if (commandLine.getArgs().length == 0) {\n System.err.println(\"\u6ca1\u6709\u6307\u5b9a java \u6e90\u6587\u4ef6\");\n return;\n }\n codeFile = commandLine.getArgs()[0];\n if (!codeFile.endsWith(\".java\")) {\n System.err.println(codeFile + \" \u4e0d\u662f java \u6e90\u6587\u4ef6\");\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a command-line tool that processes Java source files. The tool should accept various command-line options and arguments to perform specific tasks. Your goal is to implement the logic for parsing the command-line options and arguments, and handling potential errors.\n\nYou are given a code snippet that demonstrates the initial steps of parsing command-line options using Apache Commons CLI library. The snippet shows the usage of options for specifying a package name, an output directory, and a Java source file. It also includes error handling for cases where the Java source file is not specified or does not have the \".java\" extension.\n\nYour task is to extend the functionality of this command-line tool by implementing the remaining logic for processing the parsed options and arguments. Specifically, you need to handle the following tasks:\n1. Validate and process the parsed options and arguments to perform the intended operations.\n2. Implement the logic for generating output based on the specified package name, output directory, and Java source file.\n3. Handle any additional error cases that may arise during the processing of options and arguments.\n\nYour solution should demonstrate a clear understanding of command-line parsing, error handling, and processing of Java source files.","solution":"To extend the functionality of the command-line tool, you can implement the following steps:\n\n1. Validate and process the parsed options and arguments:\n - Check if the package name, output directory, and Java source file are valid and accessible.\n - Handle cases where required options are missing or have invalid values.\n\n2. Generate output based on the specified package name, output directory, and Java source file:\n - Create the necessary directory structure based on the package name and output directory.\n - Generate the output files based on the processed Java source file, package name, and output directory.\n\n3. Handle additional error cases:\n - Check for any unexpected errors during the processing of options and arguments.\n - Provide informative error messages and graceful error handling to guide users in resolving issues.\n\nHere's a high-level example of how the solution could be structured:\n\n```java\n\/\/ Pseudocode for extending the command-line tool functionality\npublic class JavaSourceProcessor {\n public static void main(String[] args) {\n try {\n CommandLine commandLine = parser.parse(options, args);\n String packageName = commandLine.getOptionValue(\"p\", null);\n String outputDir = commandLine.getOptionValue(\"o\", \".\");\n if (commandLine.getArgs().length == 0) {\n System.err.println(\"No Java source file specified\");\n return;\n }\n String codeFile = commandLine.getArgs()[0];\n \n \/\/ Validate and process the parsed options and arguments\n if (packageName == null || outputDir == null || codeFile == null) {\n System.err.println(\"Invalid options or arguments\");\n return;\n }\n \/\/ Additional validation and processing logic\n \n \/\/ Generate output based on the specified package name, output directory, and Java source file\n \/\/ Create directory structure, process Java source file, and generate output\n \n } catch (ParseException e) {\n System.err.println(\"Error parsing command-line options: \" + e.getMessage());\n } catch (Exception e) {\n System.err.println(\"An unexpected error occurred: \" + e.getMessage());\n }\n }\n}\n```\n\nThe actual implementation would involve detailed logic for validating options, processing files, and handling errors, but the provided pseudocode outlines the key steps for extending the functionality of the command-line tool."} {"lang":"python","raw_index":148544,"index":22911,"seed":" else:\n print(chalk.red(f\"Error:, {response.status_code, response.text}\"))\n embed=discord.Embed(title=\"Erreur inconnue\", description=f\"Erreur console {response.status_code, response.text}\", color=0xff0000)\n embed.set_thumbnail(url=\"https:\/\/cdn.discordapp.com\/attachments\/795288700594290698\/879752415400837120\/elbot-triste.png\")\n await ctx.message.reply(embed=embed)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that processes a response from an API and generates a Discord embed message based on the response. The function should handle both successful and failed API responses and format the embed message accordingly.\n\nThe function should take in the following parameters:\n- `ctx`: The context object representing the Discord command invocation.\n- `response`: The response object received from the API, containing `status_code` and `text` attributes.\n\nYour task is to implement the `generate_discord_embed` function, which should construct a Discord embed message based on the response from the API. If the response is successful (status code 200), the embed message should indicate success. If the response is unsuccessful, the embed message should indicate an error and include the status code and response text.\n\nThe function should follow these requirements:\n- If the response status code is 200, the embed message should have a green color and indicate success.\n- If the response status code is not 200, the embed message should have a red color and indicate an error, including the status code and response text.\n- The embed message should include a title and description based on the response status.\n- If there is an error, the embed message should also include a thumbnail image.\n\nYour function should use the `discord` library to create the embed message and the `chalk` library to format the text.\n\n```python\nimport discord\nfrom chalk import chalk\n\nasync def generate_discord_embed(ctx, response):\n if response.status_code == 200:\n # Construct embed for successful response\n embed = discord.Embed(title=\"Success\", description=\"API request successful\", color=0x00ff00)\n await ctx.message.reply(embed=embed)\n else:\n # Construct embed for unsuccessful response\n error_message = f\"Error: {response.status_code}, {response.text}\"\n print(chalk.red(error_message))\n embed = discord.Embed(title=\"Unknown Error\", description=f\"Console Error {response.status_code}, {response.text}\", color=0xff0000)\n embed.set_thumbnail(url=\"https:\/\/cdn.discordapp.com\/attachments\/795288700594290698\/879752415400837120\/elbot-triste.png\")\n await ctx.message.reply(embed=embed)\n```","solution":"```python\nimport discord\nfrom chalk import chalk\n\nasync def generate_discord_embed(ctx, response):\n if response.status_code == 200:\n # Construct embed for successful response\n embed = discord.Embed(title=\"Success\", description=\"API request successful\", color=0x00ff00)\n await ctx.message.reply(embed=embed)\n else:\n # Construct embed for unsuccessful response\n error_message = f\"Error: {response.status_code}, {response.text}\"\n print(chalk.red(error_message))\n embed = discord.Embed(title=\"Unknown Error\", description=f\"Console Error {response.status_code}, {response.text}\", color=0xff0000)\n embed.set_thumbnail(url=\"https:\/\/cdn.discordapp.com\/attachments\/795288700594290698\/879752415400837120\/elbot-triste.png\")\n await ctx.message.reply(embed=embed)\n```"} {"lang":"python","raw_index":139025,"index":8131,"seed":" if \"points = \" in line:\n point_coordinates_in_a_string = line.split(\"=\")[-1]\n additional_points.extend( list( eval(point_coordinates_in_a_string ) ))\n \n \n if not points:\n print(r\"ERROR: the vrp file does not have coordinates!\", file=stderr)\n \n dot_files = []\n \n nparams = get_normalization_params(points+additional_points, (-BB_HALF_SIZE,BB_HALF_SIZE), keep_aspect_ratio=True)\n npts = normalize_to_rect(points, nparams)\n \n if selector&VISUALIZE.EMPTY:\n # write the initial state\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a Python code snippet that processes a VRP (Vehicle Routing Problem) file and performs various operations on the coordinates of points. Your task is to implement a function that normalizes the given points to a specified bounding box and returns the normalized points.\n\nThe function `get_normalization_params` takes a list of points and a bounding box size as input and returns normalization parameters. The function `normalize_to_rect` takes a list of points and normalization parameters as input and returns the normalized points.\n\nYou need to implement the `normalize_points` function that takes the original points, bounding box size, and a boolean flag for keeping the aspect ratio as input and returns the normalized points using the provided functions.\n\nThe normalization process involves:\n1. Obtaining normalization parameters using the `get_normalization_params` function.\n2. Normalizing the points using the `normalize_to_rect` function.\n\nYour task is to implement the `normalize_points` function to achieve the described normalization process.\n\n```python\ndef normalize_points(original_points, bounding_box_size, keep_aspect_ratio):\n # Implement the normalization process using the provided functions\n pass\n```","solution":"```python\ndef normalize_points(original_points, bounding_box_size, keep_aspect_ratio):\n from math import inf\n\n def get_normalization_params(points, bounding_box, keep_aspect_ratio):\n min_x, min_y, max_x, max_y = inf, inf, -inf, -inf\n for x, y in points:\n min_x = min(min_x, x)\n min_y = min(min_y, y)\n max_x = max(max_x, x)\n max_y = max(max_y, y)\n\n width = max_x - min_x\n height = max_y - min_y\n\n if keep_aspect_ratio:\n scale = min(bounding_box[1] \/ width, bounding_box[3] \/ height)\n center_x = (min_x + max_x) \/ 2\n center_y = (min_y + max_y) \/ 2\n return scale, center_x, center_y\n else:\n scale_x = bounding_box[1] \/ width\n scale_y = bounding_box[3] \/ height\n return scale_x, scale_y, min_x, min_y\n\n def normalize_to_rect(points, normalization_params):\n if len(normalization_params) == 3: # Aspect ratio kept\n scale, center_x, center_y = normalization_params\n normalized_points = []\n for x, y in points:\n new_x = (x - center_x) * scale\n new_y = (y - center_y) * scale\n normalized_points.append((new_x, new_y))\n return normalized_points\n else: # Aspect ratio not kept\n scale_x, scale_y, min_x, min_y = normalization_params\n normalized_points = []\n for x, y in points:\n new_x = (x - min_x) * scale_x\n new_y = (y - min_y) * scale_y\n normalized_points.append((new_x, new_y))\n return normalized_points\n\n additional_points = [] # Assuming it's defined elsewhere\n points = original_points\n nparams = get_normalization_params(points + additional_points, (-bounding_box_size, bounding_box_size), keep_aspect_ratio)\n normalized_points = normalize_to_rect(points, nparams)\n return normalized_points\n```"} {"lang":"python","raw_index":63698,"index":22523,"seed":"\n@web.app_errorhandler(404)\ndef not_found(e):\n # AOP \u601d\u60f3\n return render_template('404.html'), 404\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simple web application error handling system using Python and Flask. Your goal is to create a custom error handler for the 404 error, which will render a specific HTML template when a page is not found.\n\nYour task is to complete the `not_found` function, which is a Flask error handler for 404 errors. The function should return the rendered template '404.html' along with the HTTP status code 404.\n\nYour implementation should adhere to the following requirements:\n- Use the `@web.app_errorhandler(404)` decorator to register the `not_found` function as the error handler for 404 errors.\n- Return the rendered template '404.html' and the HTTP status code 404 when a 404 error occurs.\n\nYour solution should be based on the Flask framework and should demonstrate a clear understanding of error handling and rendering templates in a web application context.","solution":"```python\nfrom flask import Flask, render_template\napp = Flask(__name__)\n\n@app.errorhandler(404)\ndef not_found(e):\n return render_template('404.html'), 404\n\nif __name__ == '__main__':\n app.run()\n```\n\nIn the solution, we define a Flask application and register the `not_found` function as the error handler for 404 errors using the `@app.errorhandler(404)` decorator. Inside the `not_found` function, we return the rendered template '404.html' along with the HTTP status code 404 using the `render_template` function. This ensures that when a 404 error occurs, the specified template is rendered and the appropriate status code is returned to the client."} {"lang":"shell","raw_index":122430,"index":4711,"seed":"#!\/bin\/bash\n#\n# Copyright (c) 2019-2020 P3TERX \n#\n# This is free software, licensed under the MIT License.\n# See \/LICENSE for more information.\n#\n# https:\/\/github.com\/P3TERX\/Actions-OpenWrt\n# File name: diy-part2.sh\n# Description: OpenWrt DIY script part 2 (After Update feeds)\n#\n\n# Modify default IP\nsed -i 's\/192.168.1.1\/192.168.2.1\/g' package\/base-files\/files\/bin\/config_generate\nsed -i 's\/^wndr4300_mtdlayout.*$\/wndr4300_mtdlayout=mtdparts=ar934x-nfc:256k(u-boot)ro,256k(u-boot-env)ro,256k(caldata),512k(pot),2048k(language),512k(config),3072k(traffic_meter),2048k(kernel),121856k(ubi),123904k@0x6c0000(firmware),256k(caldata_backup),-(reserved)\/' target\/linux\/ar71xx\/image\/legacy.mk\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a script to automate the modification of default IP addresses in OpenWrt firmware. OpenWrt is a Linux-based open-source operating system designed for embedded devices. The given code snippet is a part of a DIY script used to customize OpenWrt firmware.\n\nYour task is to write a Bash script that performs the following tasks:\n1. Modify the default IP address from \"192.168.1.1\" to \"192.168.2.1\" in the file `package\/base-files\/files\/bin\/config_generate`.\n2. Update the MTD layout for the `wndr4300` device in the file `target\/linux\/ar71xx\/image\/legacy.mk` to the specified layout.\n\nYour script should use `sed` commands to achieve these modifications.\n\nWrite a Bash script that accomplishes the tasks described above.","solution":"```bash\n#!\/bin\/bash\n#\n# Copyright (c) 2019-2020 P3TERX \n#\n# This is free software, licensed under the MIT License.\n# See \/LICENSE for more information.\n#\n# https:\/\/github.com\/P3TERX\/Actions-OpenWrt\n# File name: diy-part2.sh\n# Description: OpenWrt DIY script part 2 (After Update feeds)\n#\n\n# Modify default IP\nsed -i 's\/192.168.1.1\/192.168.2.1\/g' package\/base-files\/files\/bin\/config_generate\n\n# Update MTD layout for wndr4300 device\nsed -i 's\/^wndr4300_mtdlayout.*$\/wndr4300_mtdlayout=mtdparts=ar934x-nfc:256k(u-boot)ro,256k(u-boot-env)ro,256k(caldata),512k(pot),2048k(language),512k(config),3072k(traffic_meter),2048k(kernel),121856k(ubi),123904k@0x6c0000(firmware),256k(caldata_backup),-(reserved)\/' target\/linux\/ar71xx\/image\/legacy.mk\n```\n\nThe provided Bash script accomplishes the required tasks. It uses `sed` commands to modify the default IP address and update the MTD layout as specified in the problem description."} {"lang":"php","raw_index":79854,"index":61,"seed":" <\/button>\n <\/form>\n <\/div>\n <\/div>\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that will parse a given HTML snippet and count the occurrences of specific HTML tags within it. The HTML snippet will be provided as a string, and the function should return a dictionary containing the count of each tag present in the snippet.\n\nFor example, given the following HTML snippet:\n```html\n
\n

Title<\/h1>\n

This is a paragraph<\/p>\n

\n

Another paragraph<\/p>\n <\/div>\n<\/div>\n```\nThe function should return the following dictionary:\n```python\n{\n 'div': 2,\n 'h1': 1,\n 'p': 3\n}\n```\n\nYour task is to implement the function `count_html_tags(html_snippet: str) -> dict` where:\n- `html_snippet` (1 <= len(html_snippet) <= 10^5) is a string representing the HTML snippet.\n\nThe function should return a dictionary where the keys are the HTML tag names and the values are the counts of each tag within the snippet.","solution":"```python\nfrom html.parser import HTMLParser\n\nclass HTMLTagCounter(HTMLParser):\n def __init__(self):\n super().__init__()\n self.tag_counts = {}\n\n def handle_starttag(self, tag, attrs):\n self.tag_counts[tag] = self.tag_counts.get(tag, 0) + 1\n\ndef count_html_tags(html_snippet: str) -> dict:\n parser = HTMLTagCounter()\n parser.feed(html_snippet)\n return parser.tag_counts\n```\n\nThe solution involves creating a custom HTML parser by subclassing `HTMLParser` from the `html.parser` module. The `handle_starttag` method is overridden to count the occurrences of each HTML tag. The `count_html_tags` function initializes the custom parser, feeds it the HTML snippet, and returns the tag counts obtained from the parser."} {"lang":"python","raw_index":38288,"index":19210,"seed":" json.dump(data, jfile, sort_keys=True, indent=4)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that takes in a dictionary and a file path as input and writes the dictionary data into a JSON file with sorted keys and indented formatting. Your function should handle potential exceptions and ensure the file is closed properly after writing the data.\n\nThe function signature should be:\n```python\ndef write_sorted_json(data: dict, file_path: str) -> None:\n # Your implementation here\n```\n\nFor example, given the following dictionary:\n```python\ndata = {\n \"name\": \"John\",\n \"age\": 30,\n \"city\": \"New York\"\n}\n```\nand a file path \"output.json\", the function should write the data into the \"output.json\" file with sorted keys and indented formatting.","solution":"```python\nimport json\n\ndef write_sorted_json(data: dict, file_path: str) -> None:\n try:\n with open(file_path, 'w') as jfile:\n json.dump(data, jfile, sort_keys=True, indent=4)\n except (IOError, OSError) as e:\n print(f\"Error writing to file: {e}\")\n except Exception as e:\n print(f\"An unexpected error occurred: {e}\")\n finally:\n jfile.close()\n```\n\nThis solution defines a function `write_sorted_json` that takes a dictionary `data` and a file path `file_path` as input. It then attempts to open the file for writing and uses `json.dump` to write the dictionary data into the file with sorted keys and indented formatting. The function handles potential exceptions, such as IOErrors or OS errors, and ensures that the file is closed properly after writing the data."} {"lang":"rust","raw_index":40903,"index":3624,"seed":"pub fn test_global_executor(executor: impl Executor + Send + Sync + 'static, with_local: bool) {\n global_executor::init(executor);\n let res = global_executor::block_on(async move {\n let r1 = global_executor::spawn(async { 1 + 2 }).await;\n let r2 = if with_local {\n global_executor::spawn_local(async { 3 + 4 }).await\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom executor for asynchronous tasks in Rust. The executor will be responsible for scheduling and running asynchronous tasks, and it should support both global and local task execution.\n\nYour task is to create a custom executor struct and implement the necessary traits to support global and local task execution. The executor should be able to handle both synchronous and asynchronous tasks and ensure that they are executed in the appropriate context.\n\nYour custom executor should adhere to the following requirements:\n- It should implement the `Executor` trait, which provides the necessary methods for task execution.\n- It should support global task execution using the `global_executor::spawn` and `global_executor::block_on` functions.\n- It should support local task execution using the `global_executor::spawn_local` function.\n- It should be thread-safe and allow for concurrent task execution.\n- It should be able to handle both synchronous and asynchronous tasks.\n\nYou should also provide a test function `test_global_executor` that takes an instance of your custom executor and a boolean flag indicating whether to include local task execution. The test function should initialize the global executor with the provided executor instance and execute a series of asynchronous tasks using both global and local execution.\n\nYour implementation should demonstrate the correct usage of the custom executor for global and local task execution, ensuring that tasks are executed in the appropriate context and produce the expected results.","solution":"```rust\nuse std::sync::{Arc, Mutex};\nuse std::future::Future;\nuse std::pin::Pin;\nuse std::task::{Context, Poll, Waker, RawWaker, RawWakerVTable, RawWakerVTable};\nuse std::sync::mpsc::{sync_channel, SyncSender, Receiver};\nuse std::thread;\n\n\/\/ Custom executor struct\npub struct CustomExecutor {\n task_sender: SyncSender>,\n task_receiver: Receiver>,\n}\n\nimpl CustomExecutor {\n pub fn new() -> Self {\n let (task_sender, task_receiver) = sync_channel(100);\n CustomExecutor {\n task_sender,\n task_receiver,\n }\n }\n\n pub fn run(&self) {\n let receiver = self.task_receiver.clone();\n thread::spawn(move || {\n while let Ok(task) = receiver.recv() {\n task.run();\n }\n });\n }\n}\n\n\/\/ Task struct\nstruct Task {\n future: Mutex + Send>>>>,\n waker: Mutex>,\n}\n\nimpl Task {\n fn new(future: Pin + Send>>) -> Arc {\n Arc::new(Task {\n future: Mutex::new(Some(future)),\n waker: Mutex::new(None),\n })\n }\n\n fn run(self: Arc) {\n let waker = waker_from_task(self.clone());\n let mut context = Context::from_waker(&waker);\n if let Some(mut future) = self.future.lock().unwrap().take() {\n if let Poll::Pending = future.as_mut().poll(&mut context) {\n *self.waker.lock().unwrap() = Some(waker);\n self.task_sender.send(self).unwrap();\n }\n }\n }\n}\n\nfn waker_from_task(task: Arc) -> Waker {\n let raw_waker = RawWaker::new(Arc::into_raw(task) as *const (), &VTABLE);\n unsafe { Waker::from_raw(raw_waker) }\n}\n\nstatic VTABLE: RawWakerVTable = RawWakerVTable::new(\n |data| unsafe { Arc::from_raw(data as *const Task) },\n |data| {\n let _ = Arc::from_raw(data as *const Task);\n },\n |data| unsafe { Arc::from_raw(data as *const Task) },\n |data| {\n let _ = Arc::from_raw(data as *const Task);\n },\n);\n\n\/\/ Implementing Executor trait for CustomExecutor\nimpl Executor for CustomExecutor {\n fn spawn(&self, future: Pin + Send>>) {\n let task = Task::new(future);\n self.task_sender.send(task).unwrap();\n }\n\n fn block_on(&self, future: Pin + Send>>) {\n let task = Task::new(future);\n task.run();\n }\n\n fn spawn_local(&self, future: Pin + Send>>) {\n let task = Task::new(future);\n task.run();\n }\n}\n\n\/\/ Test function\npub fn test_global_executor(executor: impl Executor + Send + Sync + 'static, with_local: bool) {\n let custom_executor = CustomExecutor::new();\n custom_executor.run();\n\n global_executor::init(executor);\n let res = global_executor::block_on(async move {\n let r1 = global_executor::spawn(async { 1 + 2 }).await;\n let r2 = if with_local {\n global_executor::spawn_local(async { 3 + 4 }).await\n } else {\n global_executor::spawn(async { 5 + 6 }).await\n };\n (r1, r2)\n });\n}\n```"} {"lang":"swift","raw_index":73046,"index":1436,"seed":"\n enum Action: WorkflowAction {\n\n typealias WorkflowType = RootWorkflow\n\n case login(name: String)\n\n func apply(toState state: inout RootWorkflow.State) -> RootWorkflow.Output? {\n\n switch self {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a workflow system using Swift. The provided code snippet is a simplified representation of a workflow system using enums and associated values. The `Action` enum conforms to the `WorkflowAction` protocol and has an associated type `RootWorkflow`. It defines a case `login` with an associated value of type `String`. The `apply(toState:)` function is used to apply the action to the workflow's state and produce an output.\n\nYour task is to create a new enum `UserAction` that conforms to the `WorkflowAction` protocol and is associated with a different workflow type, `UserWorkflow`. The `UserAction` enum should have two cases: `createUser` with associated values `username: String` and `email: String`, and `updateProfile` with associated value `profileData: UserProfile`. The `apply(toState:)` function should be implemented to handle these actions and update the `UserWorkflow` state accordingly.\n\nCreate the `UserWorkflow` struct with an inner `State` struct that contains the necessary state properties. The `UserWorkflow` should have a function `apply(_:)` that takes an action and updates the state using the `apply(toState:)` function of the action.\n\nEnsure that the `UserWorkflow` and `UserAction` are correctly defined and that the `apply(_:)` function correctly updates the state based on the action applied.","solution":"```swift\n\/\/ Define the UserWorkflow struct\nstruct UserWorkflow: Workflow {\n \/\/ Define the State struct for UserWorkflow\n struct State {\n var users: [User] = []\n var userProfile: UserProfile?\n }\n\n \/\/ Define the UserAction enum conforming to WorkflowAction\n enum UserAction: WorkflowAction {\n typealias WorkflowType = UserWorkflow\n\n case createUser(username: String, email: String)\n case updateProfile(profileData: UserProfile)\n\n \/\/ Apply the action to the UserWorkflow state\n func apply(toState state: inout State) -> UserWorkflow.Output? {\n switch self {\n case .createUser(let username, let email):\n let newUser = User(username: username, email: email)\n state.users.append(newUser)\n return .userCreated(newUser)\n case .updateProfile(let profileData):\n state.userProfile = profileData\n return .profileUpdated(profileData)\n }\n }\n }\n\n \/\/ Apply function to update the state based on the action\n mutating func apply(_ action: UserAction) -> UserWorkflow.Output? {\n return action.apply(toState: &self.state)\n }\n}\n\n\/\/ Define the UserProfile struct\nstruct UserProfile {\n var name: String\n var age: Int\n var bio: String\n}\n\n\/\/ Define the User struct\nstruct User {\n var username: String\n var email: String\n}\n\n\/\/ Define the Output enum for UserWorkflow\nextension UserWorkflow {\n enum Output {\n case userCreated(User)\n case profileUpdated(UserProfile)\n }\n}\n\n\/\/ Example usage\nvar userWorkflow = UserWorkflow()\nvar createAction = UserWorkflow.UserAction.createUser(username: \"john_doe\", email: \"john@example.com\")\nvar updateAction = UserWorkflow.UserAction.updateProfile(profileData: UserProfile(name: \"John Doe\", age: 30, bio: \"Swift developer\"))\nlet userOutput = userWorkflow.apply(createAction) \/\/ Output: .userCreated(User(username: \"john_doe\", email: \"john@example.com\"))\nlet profileOutput = userWorkflow.apply(updateAction) \/\/ Output: .profileUpdated(UserProfile(name: \"John Doe\", age: 30, bio: \"Swift developer\"))\n```"} {"lang":"python","raw_index":135137,"index":30022,"seed":"\t\ttry:\n\t\t\treading['ambientTemperature'] = data['sensors'][sensorId]['ambientTemperature']\n\t\t\tdel data['sensors'][sensorId]['ambientTemperature']\n\t\t\thas_data = True\n\t\texcept:\n\t\t\tpass\n\t\t\t\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a data processing function that extracts ambient temperature readings from a nested dictionary structure. The function should handle potential errors and modify the input dictionary accordingly.\n\nYou are given a Python code snippet that attempts to extract the ambient temperature reading from a nested dictionary `data` and store it in a separate dictionary `reading`. If successful, the ambient temperature reading is removed from the original dictionary. If an error occurs during the extraction, it is caught and ignored.\n\nYour task is to implement a function `process_ambient_temperature(data, sensorId)` that performs the same operation as the code snippet. The function should take in the input dictionary `data` and a string `sensorId`, and return a tuple `(reading, modified_data)` where `reading` is a dictionary containing the extracted ambient temperature reading, and `modified_data` is the input dictionary with the ambient temperature removed if it was successfully extracted.\n\nThe structure of the input dictionary `data` is as follows:\n```python\ndata = {\n 'sensors': {\n 'sensor1': {\n 'ambientTemperature': 25.5,\n 'otherData': 'abc'\n },\n 'sensor2': {\n 'otherData': 'xyz'\n }\n }\n}\n```\nThe function should handle the following cases:\n1. If the ambient temperature reading exists for the given `sensorId`, it should be extracted and removed from the original dictionary.\n2. If the ambient temperature reading does not exist for the given `sensorId`, the function should not modify the original dictionary.\n\nYour task is to implement the `process_ambient_temperature` function to achieve the described behavior.","solution":"```python\ndef process_ambient_temperature(data, sensorId):\n reading = {}\n modified_data = data.copy() # Create a copy to avoid modifying the original data\n\n try:\n ambient_temp = modified_data['sensors'][sensorId]['ambientTemperature']\n reading['ambientTemperature'] = ambient_temp\n del modified_data['sensors'][sensorId]['ambientTemperature']\n except KeyError:\n pass # Ignore the error if ambient temperature reading does not exist\n\n return reading, modified_data\n```\nThe `process_ambient_temperature` function first creates an empty dictionary `reading` to store the extracted ambient temperature reading. It then creates a copy of the input dictionary `data` to avoid modifying the original data directly.\n\nInside a try-except block, the function attempts to access the ambient temperature reading for the given `sensorId`. If successful, it extracts the reading, stores it in the `reading` dictionary, and removes it from the `modified_data` dictionary. If the ambient temperature reading does not exist, the KeyError is caught and ignored.\n\nThe function then returns a tuple containing the `reading` dictionary and the `modified_data` dictionary, reflecting the extracted ambient temperature reading and the modified input dictionary, respectively."} {"lang":"php","raw_index":52351,"index":4546,"seed":" {{--

\n

{\"+\" if trans_sphere >= 0 else \"-\"}{abs(trans_sphere): .2f}<\/td>\n {\"+\" if trans_cylinder > 0 else \"-\"}{abs(trans_cylinder): .2f}<\/td>\n {trans_axis}<\/td>\n \n <\/tr>\n <\/tbody>\n <\/table>\n \"\"\"\n )\n return HttpResponse(answer)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that processes and formats data from a medical device used for eye examinations. The function should take in three parameters: `trans_sphere` (float), `trans_cylinder` (float), and `trans_axis` (int). The `trans_sphere` parameter represents the spherical correction for the patient's vision, the `trans_cylinder` parameter represents the cylindrical correction, and the `trans_axis` parameter represents the axis of the cylindrical correction.\n\nYour task is to implement the `format_eye_exam_data` function, which should return a formatted HTML table row containing the processed data. The table row should consist of three cells, each containing specific information derived from the input parameters. The first cell should display the sign and absolute value of `trans_sphere` with two decimal places, the second cell should display the sign and absolute value of `trans_cylinder` with two decimal places, and the third cell should display the value of `trans_axis`.\n\nThe function should adhere to the following rules:\n- The sign of `trans_sphere` should be displayed as \"+\" if it is greater than or equal to 0, and as \"-\" if it is less than 0.\n- The sign of `trans_cylinder` should be displayed as \"+\" if it is greater than 0, and as \"-\" if it is less than or equal to 0.\n- The values of `trans_sphere` and `trans_cylinder` should be displayed with exactly two decimal places.\n- The `trans_axis` value should be displayed as is, without any modifications.\n\nYour task is to complete the `format_eye_exam_data` function according to the given specifications.\n\nExample:\nFor `trans_sphere = -1.75`, `trans_cylinder = 0.50`, and `trans_axis = 90`, the function should return the following HTML table row:\n```\n
-1.75<\/td>\n +0.50<\/td>\n 90<\/td>\n<\/tr>\n```","solution":"```python\ndef format_eye_exam_data(trans_sphere, trans_cylinder, trans_axis):\n formatted_sphere = f'{\"+\" if trans_sphere >= 0 else \"-\"}{abs(trans_sphere):.2f}'\n formatted_cylinder = f'{\"+\" if trans_cylinder > 0 else \"-\"}{abs(trans_cylinder):.2f}'\n formatted_axis = str(trans_axis)\n html_row = f'
{formatted_sphere}<\/td>\\n {formatted_cylinder}<\/td>\\n {formatted_axis}<\/td>\\n<\/tr>'\n return html_row\n```\n\nThe `format_eye_exam_data` function takes in the parameters `trans_sphere`, `trans_cylinder`, and `trans_axis`, and formats them according to the specified rules. It then constructs and returns an HTML table row containing the formatted data."} {"lang":"python","raw_index":137812,"index":17495,"seed":" _cfg(\n url=\n 'https:\/\/dl.fbaipublicfiles.com\/dino\/dino_xcit_medium_24_p16_pretrain\/dino_xcit_medium_24_p16_pretrain.pth' # noqa\n ),\n 'xcit_medium_24_p8_dino':\n _cfg(\n url=\n 'https:\/\/dl.fbaipublicfiles.com\/dino\/dino_xcit_medium_24_p8_pretrain\/dino_xcit_medium_24_p8_pretrain.pth' # noqa\n ),\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that extracts the URLs from a given configuration file and returns them as a list. The configuration file is in a specific format, where each URL is associated with a key and enclosed within single quotes. The URLs may contain special characters and are followed by a comment that needs to be ignored. Your function should be able to handle multiple URLs and comments within the configuration file.\n\nWrite a function `extract_urls` that takes a string representing the configuration file as input and returns a list of URLs extracted from the file.\n\nFunction Signature: `def extract_urls(config_file: str) -> List[str]:`\n\n**Input**\n- The input `config_file` (1 <= len(config_file) <= 1000) is a string representing the configuration file. The file contains URLs associated with keys in the format shown in the code snippet.\n\n**Output**\n- The function should return a list of URLs extracted from the configuration file.\n\n**Example**\n```\nconfig_file = \"\"\"\n _cfg(\n url=\n 'https:\/\/dl.fbaipublicfiles.com\/dino\/dino_xcit_medium_24_p16_pretrain\/dino_xcit_medium_24_p16_pretrain.pth' # noqa\n ),\n 'xcit_medium_24_p8_dino':\n _cfg(\n url=\n 'https:\/\/dl.fbaipublicfiles.com\/dino\/dino_xcit_medium_24_p8_pretrain\/dino_xcit_medium_24_p8_pretrain.pth' # noqa\n ),\n\"\"\"\nextract_urls(config_file)\nOutput: [\n 'https:\/\/dl.fbaipublicfiles.com\/dino\/dino_xcit_medium_24_p16_pretrain\/dino_xcit_medium_24_p16_pretrain.pth',\n 'https:\/\/dl.fbaipublicfiles.com\/dino\/dino_xcit_medium_24_p8_pretrain\/dino_xcit_medium_24_p8_pretrain.pth'\n]\n```","solution":"```python\nfrom typing import List\nimport re\n\ndef extract_urls(config_file: str) -> List[str]:\n urls = re.findall(r\"'(https?:\/\/\\S+)'\", config_file)\n return urls\n```\n\nThe `extract_urls` function uses the `re.findall` method to extract all the URLs from the given configuration file. The regular expression `r\"'(https?:\/\/\\S+)'\"` is used to match the URLs enclosed within single quotes. The function then returns the list of extracted URLs."} {"lang":"cpp","raw_index":7371,"index":1285,"seed":"*\/\n#include \"buffer.h\"\n\n#include \"support\/check.h\"\n#include \"support\/safeformat.h\"\n\n#include \n#include \n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a C++ class that simulates a circular buffer with a fixed capacity. The circular buffer should support the following operations:\n1. `CircularBuffer(int capacity)`: Constructor that initializes the circular buffer with the given capacity.\n2. `bool isEmpty()`: Returns true if the circular buffer is empty, false otherwise.\n3. `bool isFull()`: Returns true if the circular buffer is full, false otherwise.\n4. `void enqueue(int value)`: Adds an element to the circular buffer. If the buffer is full, the oldest element should be overwritten.\n5. `int dequeue()`: Removes and returns the oldest element from the circular buffer. If the buffer is empty, return -1.\n\nYou need to implement the `CircularBuffer` class and its member functions to achieve the specified behavior.","solution":"```cpp\n#include \n\nclass CircularBuffer {\nprivate:\n std::vector buffer;\n int capacity;\n int front;\n int rear;\n int size;\n\npublic:\n CircularBuffer(int capacity) : capacity(capacity), front(0), rear(0), size(0) {\n buffer.resize(capacity, -1);\n }\n\n bool isEmpty() {\n return size == 0;\n }\n\n bool isFull() {\n return size == capacity;\n }\n\n void enqueue(int value) {\n if (isFull()) {\n front = (front + 1) % capacity; \/\/ Overwrite the oldest element\n } else {\n size++;\n }\n buffer[rear] = value;\n rear = (rear + 1) % capacity;\n }\n\n int dequeue() {\n if (isEmpty()) {\n return -1;\n } else {\n int value = buffer[front];\n front = (front + 1) % capacity;\n size--;\n return value;\n }\n }\n};\n```"} {"lang":"python","raw_index":117038,"index":12502,"seed":"\nclass UnavailableRobot(Exception):\n pass\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a robot management system that can allocate and deallocate robots to various tasks. The system should be able to handle situations where a robot is requested for a task, but is currently unavailable. To handle this scenario, an `UnavailableRobot` exception class needs to be defined. \n\nYour task is to create a Python class `RobotManager` with the following methods:\n1. `__init__(self, num_robots)`: Initializes the `RobotManager` with a given number of robots.\n2. `allocate_robot(self)`: Allocates a robot for a task. If all robots are currently allocated, raise the `UnavailableRobot` exception.\n3. `deallocate_robot(self)`: Deallocates a robot that has completed its task, making it available for reallocation.\n\nYour implementation should raise the `UnavailableRobot` exception when attempting to allocate a robot if all robots are currently allocated.\n\nExample:\n```python\nrobot_manager = RobotManager(3)\nrobot_manager.allocate_robot() # Allocates robot 1\nrobot_manager.allocate_robot() # Allocates robot 2\nrobot_manager.allocate_robot() # Allocates robot 3\nrobot_manager.allocate_robot() # Raises UnavailableRobot exception\nrobot_manager.deallocate_robot() # Deallocates robot 3\nrobot_manager.allocate_robot() # Allocates robot 3\n```","solution":"```python\nclass UnavailableRobot(Exception):\n pass\n\nclass RobotManager:\n def __init__(self, num_robots):\n self.num_robots = num_robots\n self.available_robots = list(range(1, num_robots + 1))\n\n def allocate_robot(self):\n if not self.available_robots:\n raise UnavailableRobot(\"All robots are currently allocated\")\n return self.available_robots.pop(0)\n\n def deallocate_robot(self, robot_id):\n if robot_id not in self.available_robots:\n self.available_robots.append(robot_id)\n```\nIn this solution, the `RobotManager` class is initialized with a given number of robots. The `allocate_robot` method checks if there are any available robots and raises the `UnavailableRobot` exception if none are available. The `deallocate_robot` method makes a robot available for reallocation by adding its ID back to the list of available robots."} {"lang":"java","raw_index":83942,"index":666,"seed":" throw new IOException(\"class not found exception\", e);\n }\n }\n}\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom exception class and handling it within a Java program. Your task is to create a custom exception called `ClassNotFoundException` that extends the `Exception` class. Additionally, you need to modify the given code snippet to handle this custom exception appropriately.\n\nYour custom exception class should have a constructor that accepts a `String` message and a `Throwable` cause, and passes them to the superclass constructor. The given code snippet should be modified to catch the `ClassNotFoundException` and rethrow it as an `IOException` with the message \"class not found exception\".\n\nYour task is to complete the implementation of the custom exception class and modify the given code snippet to handle the custom exception as described.","solution":"```java\n\/\/ Custom exception class\nclass ClassNotFoundException extends Exception {\n public ClassNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n}\n\n\/\/ Modified code snippet\npublic class Main {\n public static void main(String[] args) {\n try {\n \/\/ Some code that may throw ClassNotFoundException\n throw new ClassNotFoundException(\"class not found exception\", e);\n } catch (ClassNotFoundException e) {\n throw new IOException(\"class not found exception\", e);\n }\n }\n}\n```\n\nIn the solution, the custom exception class `ClassNotFoundException` is defined to extend the `Exception` class. It has a constructor that accepts a `String` message and a `Throwable` cause, passing them to the superclass constructor.\n\nThe given code snippet is modified to catch the `ClassNotFoundException` and rethrow it as an `IOException` with the message \"class not found exception\". This ensures that the custom exception is handled appropriately within the program."} {"lang":"python","raw_index":137156,"index":33458,"seed":"# 1\/5\t= \t0.2\n# 1\/6\t= \t0.1(6)\n# 1\/7\t= \t0.(142857)\n# 1\/8\t= \t0.125\n# 1\/9\t= \t0.(1)\n# 1\/10\t= \t0.1\n# Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1\/7 has a 6-digit recurring cycle.\n#\n# Find the value of d < 1000 for which 1\/d contains the longest recurring cycle in its decimal fraction part.\nfrom util.repeats import unit_fraction_cycle\n\nmax_precision = 4096\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a code snippet that attempts to find the value of d less than 1000 for which 1\/d contains the longest recurring cycle in its decimal fraction part. The code snippet uses a function `unit_fraction_cycle` from a module `util.repeats` to find the recurring cycle in the decimal fraction of 1\/d. The variable `max_precision` is set to 4096.\n\nYour task is to implement the logic to find the value of d that produces the longest recurring cycle in its decimal fraction part, without using the `unit_fraction_cycle` function or any external modules. You should write a function that takes an integer n as input and returns the value of d less than n for which 1\/d contains the longest recurring cycle in its decimal fraction part.\n\nFor example, if n is 10, the function should return 7, as 1\/7 has a 6-digit recurring cycle, which is the longest among the fractions less than 10.\n\nWrite a function `longest_recurring_cycle` to solve this problem.\n\nFunction Signature: `def longest_recurring_cycle(n: int) -> int:`","solution":"```python\ndef longest_recurring_cycle(n: int) -> int:\n def recurring_cycle_length(denominator):\n remainders = {}\n remainder = 1 % denominator\n position = 0\n while remainder not in remainders and remainder != 0:\n remainders[remainder] = position\n remainder = (remainder * 10) % denominator\n position += 1\n return position - remainders.get(remainder, 0)\n\n max_cycle_length = 0\n result = 0\n for d in range(2, n):\n cycle_length = recurring_cycle_length(d)\n if cycle_length > max_cycle_length:\n max_cycle_length = cycle_length\n result = d\n return result\n```\n\nThe `longest_recurring_cycle` function first defines a helper function `recurring_cycle_length` to calculate the length of the recurring cycle for a given denominator. It then iterates through all denominators from 2 to n-1, calculates the recurring cycle length for each denominator, and keeps track of the maximum cycle length and the corresponding denominator. Finally, it returns the denominator that produces the longest recurring cycle in its decimal fraction part."} {"lang":"swift","raw_index":7379,"index":3183,"seed":"\/\/\n\/\/ PreworkTests.swift\n\/\/ PreworkTests\n\/\/\n\/\/ Created by Riyad Sarsour on 8\/9\/21.\n\/\/\n\nimport XCTest\n@testable import Prework\n\nclass PreworkTests: XCTestCase {\n\n override func setUpWithError() throws {\n \/\/ Put setup code here. This method is called before the invocation of each test method in the class.\n }\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a function that calculates the average of an array of integers. You need to implement the `average` function that takes an array of integers as input and returns the average of all the integers in the array. The average should be a floating-point number rounded to two decimal places.\n\nFunction Signature: `func average(_ numbers: [Int]) -> Double`\n\nExample:\nInput: `[1, 2, 3, 4, 5]`\nOutput: `3.00`\n\nInput: `[10, 20, 30, 40, 50]`\nOutput: `30.00`\n\nInput: `[5, 5, 5, 5, 5]`\nOutput: `5.00`","solution":"```swift\nfunc average(_ numbers: [Int]) -> Double {\n let sum = numbers.reduce(0, +)\n let count = numbers.count\n return Double(sum) \/ Double(count)\n}\n```"} {"lang":"python","raw_index":131717,"index":7742,"seed":" thread.join()\n\nprint(\"Open ports are: \" + format(open_ports))\n\n\n\n\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program to scan for open ports on a given list of IP addresses. The program should utilize multithreading to improve efficiency in scanning multiple IP addresses simultaneously. The code snippet provided is a part of the program that waits for all the threads to finish and then prints the list of open ports.\n\nYour task is to complete the program by implementing the multithreaded port scanning functionality using Python's `threading` module. You should also handle the logic for scanning the ports and updating the `open_ports` list.\n\nYour program should take a list of IP addresses and a range of ports to scan as input. For each IP address, the program should scan all the ports in the specified range and add the open ports to the `open_ports` list. Once all the threads have finished scanning, the program should print the list of open ports for each IP address.\n\nYou can assume that the `open_ports` list is already defined and accessible to the threads.\n\nYour solution should include the necessary imports, thread function definition, and any additional functions required for port scanning.","solution":"```python\nimport socket\nimport threading\n\nopen_ports = []\n\ndef scan_ports(ip, port_range):\n global open_ports\n for port in port_range:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.settimeout(1)\n result = sock.connect_ex((ip, port))\n if result == 0:\n open_ports.append((ip, port))\n sock.close()\n\ndef port_scan(ip_addresses, port_range):\n threads = []\n for ip in ip_addresses:\n t = threading.Thread(target=scan_ports, args=(ip, port_range))\n threads.append(t)\n t.start()\n\n for t in threads:\n t.join()\n\n for ip in ip_addresses:\n print(f\"Open ports for {ip} are: {[port for addr, port in open_ports if addr == ip]}\")\n\n# Example usage\nip_addresses = ['192.168.1.1', '192.168.1.2']\nport_range = range(1, 1025)\nport_scan(ip_addresses, port_range)\n```\n\nIn this solution, we define the `scan_ports` function to scan the specified range of ports for a given IP address. We use the `socket` module to create a TCP socket and attempt to connect to each port. If the connection is successful, we add the IP address and port to the `open_ports` list.\n\nThe `port_scan` function creates a thread for each IP address and starts the port scanning process. After all threads have finished, it prints the list of open ports for each IP address.\n\nFinally, we demonstrate the usage of the `port_scan` function with example IP addresses and port range."} {"lang":"php","raw_index":129693,"index":28,"seed":"{\n\tpublic function _construct()\n\t{\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class in PHP that represents a simple shopping cart. The class should have the following functionalities:\n1. Add items to the cart with a specified quantity.\n2. Remove items from the cart.\n3. Calculate the total price of all items in the cart.\n4. Apply a discount to the total price if a discount code is provided.\n\nYou need to implement the `ShoppingCart` class with the following methods:\n1. `addItem($item, $quantity)`: Adds the specified quantity of the item to the cart.\n2. `removeItem($item)`: Removes the specified item from the cart.\n3. `calculateTotal()`: Calculates the total price of all items in the cart.\n4. `applyDiscount($code)`: Applies a discount to the total price if the provided discount code is valid.\n\nYou should also implement any necessary properties and constructors for the `ShoppingCart` class.","solution":"```php\nclass ShoppingCart {\n private $items;\n private $discountCodes;\n\n public function __construct() {\n $this->items = [];\n $this->discountCodes = [\n \"SAVE10\" => 0.1, \/\/ 10% discount\n \"SALE20\" => 0.2, \/\/ 20% discount\n \/\/ Add more discount codes as needed\n ];\n }\n\n public function addItem($item, $quantity) {\n if (isset($this->items[$item])) {\n $this->items[$item] += $quantity;\n } else {\n $this->items[$item] = $quantity;\n }\n }\n\n public function removeItem($item) {\n if (isset($this->items[$item])) {\n unset($this->items[$item]);\n }\n }\n\n public function calculateTotal() {\n $total = 0;\n foreach ($this->items as $item => $quantity) {\n \/\/ Replace this with actual price lookup logic\n $price = $this->lookupItemPrice($item);\n $total += $price * $quantity;\n }\n return $total;\n }\n\n public function applyDiscount($code) {\n if (isset($this->discountCodes[$code])) {\n $discount = $this->discountCodes[$code];\n $total = $this->calculateTotal();\n $discountedTotal = $total - ($total * $discount);\n return $discountedTotal;\n } else {\n return \"Invalid discount code\";\n }\n }\n\n \/\/ Replace this with actual price lookup logic\n private function lookupItemPrice($item) {\n \/\/ Example lookup logic\n $prices = [\n \"item1\" => 10,\n \"item2\" => 20,\n \/\/ Add more items and prices as needed\n ];\n return isset($prices[$item]) ? $prices[$item] : 0;\n }\n}\n```"} {"lang":"python","raw_index":123935,"index":22515,"seed":"\ndef g(m1,m2,c2):\n return 100*(-m1+(1-m2)*(1-1\/c2))\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function to calculate the gravitational potential energy between two masses and the distance between them. The gravitational potential energy (U) between two masses (m1 and m2) separated by a distance (c2) is given by the formula:\n\nU = 100 * (-m1 + (1 - m2) * (1 - 1\/c2))\n\nWrite a Python function called `gravitational_potential_energy` that takes in three parameters: m1, m2, and c2, and returns the gravitational potential energy calculated using the given formula.\n\nYour task is to implement the `gravitational_potential_energy` function and ensure that it correctly computes the gravitational potential energy based on the provided formula.\n\nExample:\nInput\nm1 = 5\nm2 = 3\nc2 = 2\n\nOutput\n-200.0","solution":"```python\ndef gravitational_potential_energy(m1, m2, c2):\n return 100 * (-m1 + (1 - m2) * (1 - 1\/c2))\n\n# Test the function\nm1 = 5\nm2 = 3\nc2 = 2\nresult = gravitational_potential_energy(m1, m2, c2)\nprint(result) # Output: -200.0\n```"} {"lang":"shell","raw_index":95260,"index":938,"seed":"\/opt\/redpitaya\/www\/apps\/vna\/vna &\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a script to automate the monitoring and management of a network analyzer application running on a Red Pitaya device. The network analyzer application is located at the specified file path `\/opt\/redpitaya\/www\/apps\/vna\/vna`. Your script should perform the following tasks:\n\n1. Check if the network analyzer application is already running.\n2. If the application is not running, start it.\n3. If the application is already running, stop it and then start it again.\n\nYour script should handle any errors that may occur during the process and provide appropriate feedback to the user.\n\nCreate a Python script named `network_analyzer_manager.py` to accomplish the above tasks.","solution":"```python\nimport subprocess\nimport os\n\ndef is_process_running(process_name):\n try:\n subprocess.check_output([\"pidof\", process_name])\n return True\n except subprocess.CalledProcessError:\n return False\n\ndef start_process(process_path):\n try:\n subprocess.Popen([process_path])\n print(f\"Started {process_path}\")\n except Exception as e:\n print(f\"Error starting {process_path}: {e}\")\n\ndef stop_and_start_process(process_name, process_path):\n try:\n subprocess.run([\"pkill\", process_name])\n print(f\"Stopped {process_name}\")\n start_process(process_path)\n except Exception as e:\n print(f\"Error stopping {process_name} or starting {process_path}: {e}\")\n\nif __name__ == \"__main__\":\n vna_process_name = \"vna\"\n vna_process_path = \"\/opt\/redpitaya\/www\/apps\/vna\/vna\"\n\n if is_process_running(vna_process_name):\n stop_and_start_process(vna_process_name, vna_process_path)\n else:\n start_process(vna_process_path)\n```\n\nIn this solution, we define functions to check if a process is running, start a process, and stop and start a process. The main script then uses these functions to achieve the required tasks. The `subprocess` module is used to interact with system processes, and appropriate error handling is included to provide feedback to the user."} {"lang":"python","raw_index":21753,"index":13581,"seed":"\n def test_render2(self):\n self._test_render('irrad_level : irrad_hole SCLF', 'A:9SCLF')\n\n def test_render3(self):\n self._test_render('irrad_level : irrad_hole SCLF', 'A:9 SCLF')\n\n def _test_render(self, label, expected):\n ct = CommentTemplater()\n ct.label=label\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a CommentTemplater class that processes input strings according to a specific template format. The template format consists of a label followed by a colon and a space, and then a placeholder enclosed in angle brackets. The CommentTemplater class should replace the placeholder with a given value and return the modified string.\n\nYou need to implement the `CommentTemplater` class with the following requirements:\n- The class should have a method `render` that takes two parameters: `label` (a string) and `placeholder_value` (a string).\n- The `render` method should replace the placeholder in the `label` with the `placeholder_value` and return the modified string.\n- The placeholder is enclosed in angle brackets and can contain any characters except angle brackets themselves.\n\nYou should write a Python class `CommentTemplater` with the required method to fulfill the given requirements.","solution":"```python\nclass CommentTemplater:\n def render(self, label, placeholder_value):\n return label.replace('', ' ').replace('<', '').replace('>', placeholder_value)\n\n# Test cases\nct = CommentTemplater()\noutput1 = ct.render('irrad_level : irrad_hole SCLF', 'A:9SCLF')\noutput2 = ct.render('irrad_level : irrad_hole SCLF', 'A:9')\nprint(output1) # Output: 'irrad_level : irrad_hole A:9SCLF'\nprint(output2) # Output: 'irrad_level : irrad_hole A:9 SCLF'\n```"} {"lang":"typescript","raw_index":38381,"index":458,"seed":" totalCalories += mealData.calories!;\n }\n }\n return totalCalories;\n }\n function getDaysCarbs(day: Array) {\n let totalCalories = 0;\n for (const meal of day) {\n const mealData = getMealData(meal);\n if (!mealData || !mealData.carbs) continue;\n totalCalories += mealData.carbs;\n }\n return totalCalories;\n }\n function getDaysProtein(day: Array) {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a nutrition tracking system for a fitness application. The system needs to calculate the total calories, carbs, and protein consumed in a day based on the meals logged by the user. Each meal is represented as an array of strings or objects, where objects contain nutritional information. The nutritional data for each meal includes calories, carbs, and protein. Your task is to implement three functions to calculate the total calories, carbs, and protein for a given day.\n\nYou are provided with a code snippet that includes the implementation of the `getDaysCalories` and `getDaysCarbs` functions. You need to complete the implementation by adding the `getDaysProtein` function, which calculates the total protein consumed in a day.\n\nThe `getDaysCalories` function takes an array of strings or objects representing meals and calculates the total calories consumed in a day.\n\nThe `getDaysCarbs` function takes the same input and calculates the total carbs consumed in a day.\n\nYou need to implement the `getDaysProtein` function to calculate the total protein consumed in a day based on the provided code snippet.\n\nYour task is to complete the implementation of the `getDaysProtein` function and ensure that all three functions work correctly to calculate the total calories, carbs, and protein consumed in a day.\n\n```typescript\nfunction getDaysProtein(day: Array) {\n let totalProtein = 0;\n for (const meal of day) {\n const mealData = getMealData(meal);\n if (!mealData || !mealData.protein) continue;\n totalProtein += mealData.protein;\n }\n return totalProtein;\n}\n```","solution":"```typescript\n\/\/ Define the TableItem type to represent the nutritional data for a meal\ntype TableItem = {\n calories?: number;\n carbs?: number;\n protein?: number;\n};\n\n\/\/ Implement the getMealData function to retrieve the nutritional data for a meal\nfunction getMealData(meal: string | TableItem): TableItem | undefined {\n if (typeof meal === 'string') {\n \/\/ Handle the case where meal is a string (no nutritional data available)\n return undefined;\n } else {\n \/\/ Handle the case where meal is an object containing nutritional data\n return meal;\n }\n}\n\n\/\/ Implement the getDaysCalories function to calculate the total calories consumed in a day\nfunction getDaysCalories(day: Array): number {\n let totalCalories = 0;\n for (const meal of day) {\n const mealData = getMealData(meal);\n if (mealData && mealData.calories) {\n totalCalories += mealData.calories;\n }\n }\n return totalCalories;\n}\n\n\/\/ Implement the getDaysCarbs function to calculate the total carbs consumed in a day\nfunction getDaysCarbs(day: Array): number {\n let totalCarbs = 0;\n for (const meal of day) {\n const mealData = getMealData(meal);\n if (mealData && mealData.carbs) {\n totalCarbs += mealData.carbs;\n }\n }\n return totalCarbs;\n}\n\n\/\/ Implement the getDaysProtein function to calculate the total protein consumed in a day\nfunction getDaysProtein(day: Array): number {\n let totalProtein = 0;\n for (const meal of day) {\n const mealData = getMealData(meal);\n if (mealData && mealData.protein) {\n totalProtein += mealData.protein;\n }\n }\n return totalProtein;\n}\n```\n\nThis solution completes the implementation of the `getDaysProtein` function and ensures that all three functions (`getDaysCalories`, `getDaysCarbs`, and `getDaysProtein`) work correctly to calculate the total calories, carbs, and protein consumed in a day based on the provided meals."} {"lang":"python","raw_index":105752,"index":10849,"seed":"10-100\nfrom .pcap import Pcap","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python class that processes packet capture files and provides statistics on the number of GitHub stars for a given repository. The class should have a method to set the range of GitHub stars to filter repositories and another method to retrieve the repositories within that range from the packet capture file.\n\nYour task is to implement the `GitHubStats` class with the following specifications:\n- The class should have a constructor that takes the file path of the packet capture file as a parameter and initializes an empty list to store the repositories.\n- Implement a method `set_star_range(self, min_stars, max_stars)` that sets the range of GitHub stars to filter repositories.\n- Implement a method `get_repositories(self)` that reads the packet capture file and returns a list of repositories within the specified star range.\n- The packet capture file contains lines of text in the format `:`.\n\nExample:\nIf the packet capture file contains the following lines:\n```\nrepo1:50\nrepo2:120\nrepo3:30\nrepo4:80\n```\nAfter setting the star range to 10-100, calling `get_repositories()` should return `['repo1', 'repo4']`.","solution":"```python\nclass GitHubStats:\n def __init__(self, file_path):\n self.file_path = file_path\n self.repositories = []\n\n def set_star_range(self, min_stars, max_stars):\n self.min_stars = min_stars\n self.max_stars = max_stars\n\n def get_repositories(self):\n with open(self.file_path, 'r') as file:\n for line in file:\n repo_name, stars = line.strip().split(':')\n stars_count = int(stars)\n if self.min_stars <= stars_count <= self.max_stars:\n self.repositories.append(repo_name)\n return self.repositories\n```\n\nUsage:\n```python\n# Create an instance of GitHubStats\ngh_stats = GitHubStats('path_to_packet_capture_file')\n\n# Set the star range\ngh_stats.set_star_range(10, 100)\n\n# Get repositories within the specified star range\nrepos_within_range = gh_stats.get_repositories()\nprint(repos_within_range) # Output: ['repo1', 'repo4']\n```"} {"lang":"rust","raw_index":46038,"index":2474,"seed":"use diesel::table;\n\ntable! {\n questions (sort_order) {\n sort_order -> Integer,\n question -> Text,\n }\n}\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Rust program that interacts with a database table using the Diesel ORM. The given code snippet defines a table named `questions` with two columns: `sort_order` of type Integer and `question` of type Text. Your task is to write a Rust function that retrieves all the questions from the database table and prints them in ascending order based on the `sort_order` column.\n\nYou are provided with the following Diesel model for the `questions` table:\n```rust\nuse diesel::table;\n\ntable! {\n questions (sort_order) {\n sort_order -> Integer,\n question -> Text,\n }\n}\n```\n\nYour function signature should be:\n```rust\nfn retrieve_and_print_questions() -> Result<(), diesel::result::Error> {\n \/\/ Your implementation here\n}\n```\n\nEnsure that your function:\n1. Establishes a connection to the database using the Diesel framework.\n2. Retrieves all the questions from the `questions` table, sorted in ascending order based on the `sort_order` column.\n3. Prints each question to the console.","solution":"```rust\nuse diesel::prelude::*;\nuse diesel::pg::PgConnection;\nuse dotenv::dotenv;\nuse std::env;\n\n\/\/ Define the Diesel model for the `questions` table\ntable! {\n questions (sort_order) {\n sort_order -> Integer,\n question -> Text,\n }\n}\n\n\/\/ Define the struct representing the `questions` table\n#[derive(Queryable)]\nstruct Question {\n sort_order: i32,\n question: String,\n}\n\n\/\/ Establish a connection to the database\nfn establish_connection() -> Result {\n dotenv().ok();\n let database_url = env::var(\"DATABASE_URL\")?;\n PgConnection::establish(&database_url)\n}\n\n\/\/ Retrieve and print questions from the database\nfn retrieve_and_print_questions() -> Result<(), diesel::result::Error> {\n let connection = establish_connection()?;\n let results = questions::table\n .order(questions::sort_order)\n .load::(&connection)?;\n\n for question in results {\n println!(\"Sort Order: {}, Question: {}\", question.sort_order, question.question);\n }\n\n Ok(())\n}\n```\n\nIn this solution, we first establish a connection to the database using the `establish_connection` function. Then, we retrieve all the questions from the `questions` table, sorted in ascending order based on the `sort_order` column, and print each question to the console. The `retrieve_and_print_questions` function returns a `Result` indicating success or failure in retrieving and printing the questions."} {"lang":"csharp","raw_index":133324,"index":3325,"seed":" public static FilterApplicationDetails CommunityOrganizationIdToCommunityOrganizationId\n => _communityOrganizationIdToCommunityOrganizationId.Value;\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a lazy-loaded singleton pattern in C#. A lazy-loaded singleton ensures that a class has only one instance and provides a global point of access to that instance, while the instance is created only when it is first requested. The code snippet provided is an example of a lazy-loaded singleton implementation using a static property.\n\nYour task is to create a class `FilterApplicationDetails` that follows the lazy-loaded singleton pattern. The class should have a private static field `_instance` of type `FilterApplicationDetails` and a public static property `Instance` that returns the singleton instance. The singleton instance should be created and initialized only when the `Instance` property is first accessed.\n\nYour implementation should adhere to the following requirements:\n- The `FilterApplicationDetails` class should have a private constructor to prevent direct instantiation.\n- The `Instance` property should use a thread-safe lazy initialization technique to ensure that the singleton instance is created only once, even in a multi-threaded environment.\n- The lazy initialization should be performed using the `Lazy` class provided by the .NET framework.\n\nImplement the `FilterApplicationDetails` class to satisfy the requirements of a lazy-loaded singleton pattern.","solution":"```csharp\npublic class FilterApplicationDetails\n{\n private static readonly Lazy _instance = new Lazy(() => new FilterApplicationDetails());\n\n private FilterApplicationDetails()\n {\n \/\/ Private constructor to prevent direct instantiation\n }\n\n public static FilterApplicationDetails Instance => _instance.Value;\n}\n```"} {"lang":"python","raw_index":17510,"index":39177,"seed":" gen_options: GenTaskOptions,\n ) -> None:\n \"\"\"\n Initialize a new builder.\n\n :param resmoke_proxy: Proxy to access resmoke data.\n :param suite_split_service: Service to split suites into sub-suites.\n :param evg_config_gen_service: Service to generate evergreen configuration.\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python class that initializes a builder for a test suite management system. The class should take in several services as parameters and provide a method to generate task options. The task options are used to configure and manage test tasks within the system.\n\nYour task is to complete the implementation of the `Builder` class by adding a method `generate_task_options` that takes in a `GenTaskOptions` object and returns `None`. The `Builder` class should be initialized with the following parameters:\n- `resmoke_proxy`: Proxy to access resmoke data.\n- `suite_split_service`: Service to split suites into sub-suites.\n- `evg_config_gen_service`: Service to generate evergreen configuration.\n\nYou should ensure that the `generate_task_options` method is implemented to accept a `GenTaskOptions` object and perform the necessary operations to configure and manage test tasks within the system.\n\nYour implementation should adhere to the following method signature:\n```python\nclass Builder:\n def __init__(self, resmoke_proxy, suite_split_service, evg_config_gen_service):\n # Initialize the builder with the provided services\n\n def generate_task_options(self, gen_options):\n # Implement the method to generate task options\n```","solution":"```python\nclass Builder:\n def __init__(self, resmoke_proxy, suite_split_service, evg_config_gen_service):\n self.resmoke_proxy = resmoke_proxy\n self.suite_split_service = suite_split_service\n self.evg_config_gen_service = evg_config_gen_service\n\n def generate_task_options(self, gen_options):\n # Implement the method to generate task options\n # Perform necessary operations using the provided services\n # Example:\n # task_options = gen_options.get_task_options()\n # # Perform configuration and management of test tasks using the services\n # # ...\n # return None # Placeholder return statement\n```\n\nIn the solution, the `Builder` class is initialized with the provided services, and the `generate_task_options` method is implemented to accept `gen_options` and perform the necessary operations using the initialized services. The specific operations within the `generate_task_options` method will depend on the requirements of the test suite management system."} {"lang":"python","raw_index":137298,"index":13280,"seed":"\n # Input-space coordinates. Calculate the inverse mapping such that 0.5\n # in output space maps to 0.5 in input space, and 0.5 + scale in output\n # space maps to 1.5 in input space.\n u = x \/ scale + 0.5 * (1 - 1 \/ scale)\n\n # What is the left-most pixel that can be involved in the computation?\n left = torch.floor(u - kernel_width \/ 2)\n\n # What is the maximum number of pixels that can be involved in the\n # computation? Note: it's OK to use an extra pixel here; if the\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a computer vision project and need to implement a function that calculates the range of pixels involved in a computation based on input-space coordinates and kernel width. The input-space coordinates are transformed using a formula, and then the left-most pixel and the maximum number of pixels involved in the computation need to be determined.\n\nGiven the following code snippet as a reference:\n```\n# Input-space coordinates. Calculate the inverse mapping such that 0.5\n# in output space maps to 0.5 in input space, and 0.5 + scale in output\n# space maps to 1.5 in input space.\nu = x \/ scale + 0.5 * (1 - 1 \/ scale)\n\n# What is the left-most pixel that can be involved in the computation?\nleft = torch.floor(u - kernel_width \/ 2)\n\n# What is the maximum number of pixels that can be involved in the\n# computation? Note: it's OK to use an extra pixel here; if the\n```\n\nWrite a function `compute_pixel_range(x, scale, kernel_width)` that takes in the input-space coordinate `x`, the scale factor `scale`, and the width of the kernel `kernel_width`, and returns the left-most pixel and the maximum number of pixels involved in the computation.\n\nAssume that `torch.floor()` is a function that rounds each element of the input tensor to the largest integer less than or equal to that element.\n\nFor example, if `x = 3.0`, `scale = 2.0`, and `kernel_width = 3.0`, the function should return `(0.0, 4.0)`.","solution":"```python\nimport torch\n\ndef compute_pixel_range(x, scale, kernel_width):\n # Input-space coordinates. Calculate the inverse mapping such that 0.5\n # in output space maps to 0.5 in input space, and 0.5 + scale in output\n # space maps to 1.5 in input space.\n u = x \/ scale + 0.5 * (1 - 1 \/ scale)\n\n # What is the left-most pixel that can be involved in the computation?\n left = torch.floor(u - kernel_width \/ 2)\n\n # What is the maximum number of pixels that can be involved in the\n # computation? Note: it's OK to use an extra pixel here; if the\n max_pixels = torch.ceil(u + kernel_width \/ 2) - left\n\n return left, max_pixels\n```\n\nThe `compute_pixel_range` function first calculates the input-space coordinate `u` using the given formula. Then, it computes the left-most pixel involved in the computation by subtracting half of the kernel width from `u` and taking the floor value. Finally, it calculates the maximum number of pixels involved in the computation by adding half of the kernel width to `u`, taking the ceiling value, and subtracting the left-most pixel. The function returns the left-most pixel and the maximum number of pixels involved in the computation."} {"lang":"python","raw_index":118085,"index":12957,"seed":" else:\n curl.setopt(pycurl.POSTFIELDSIZE, 0)\n elif test_obj.method == u'PUT':\n curl.setopt(pycurl.UPLOAD, 1)\n # Required for some servers\n if _body is not None:\n curl.setopt(pycurl.INFILESIZE, len(_body))\n else:\n curl.setopt(pycurl.INFILESIZE, 0)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a project that involves making HTTP requests using the `pycurl` library in Python. You need to implement a function that sets the appropriate options for the `pycurl.Curl` object based on the HTTP method specified in the input.\n\nYou are given a partial code snippet that shows how the `pycurl` options are set for the `POST` and `PUT` methods. Your task is to complete the function `set_curl_options` that takes in a `pycurl.Curl` object `curl` and a `test_obj` object representing the HTTP request, and sets the necessary options for the given HTTP method.\n\nThe `test_obj` object has the following attributes:\n- `method`: A string representing the HTTP method (e.g., 'GET', 'POST', 'PUT', 'DELETE').\n- `_body`: A string representing the request body. It may be `None` if the request does not have a body.\n\nYou need to complete the `set_curl_options` function to set the appropriate `pycurl` options for the given HTTP method based on the provided code snippet.\n\nComplete the function `set_curl_options`:\n```python\nimport pycurl\n\ndef set_curl_options(curl, test_obj):\n if test_obj.method == u'POST':\n # Set pycurl options for POST method\n # If _body is not None, set pycurl.POSTFIELDSIZE to the length of _body\n # Otherwise, set pycurl.POSTFIELDSIZE to 0\n if test_obj._body is not None:\n curl.setopt(pycurl.POSTFIELDSIZE, len(test_obj._body))\n else:\n curl.setopt(pycurl.POSTFIELDSIZE, 0)\n elif test_obj.method == u'PUT':\n # Set pycurl options for PUT method\n # Set pycurl.UPLOAD to 1\n # If _body is not None, set pycurl.INFILESIZE to the length of _body\n # Otherwise, set pycurl.INFILESIZE to 0\n curl.setopt(pycurl.UPLOAD, 1)\n if test_obj._body is not None:\n curl.setopt(pycurl.INFILESIZE, len(test_obj._body))\n else:\n curl.setopt(pycurl.INFILESIZE, 0)\n```","solution":"```python\nimport pycurl\n\ndef set_curl_options(curl, test_obj):\n if test_obj.method == u'POST':\n if test_obj._body is not None:\n curl.setopt(pycurl.POSTFIELDSIZE, len(test_obj._body))\n else:\n curl.setopt(pycurl.POSTFIELDSIZE, 0)\n elif test_obj.method == u'PUT':\n curl.setopt(pycurl.UPLOAD, 1)\n if test_obj._body is not None:\n curl.setopt(pycurl.INFILESIZE, len(test_obj._body))\n else:\n curl.setopt(pycurl.INFILESIZE, 0)\n```\n\nThe `set_curl_options` function takes a `pycurl.Curl` object `curl` and a `test_obj` object representing the HTTP request. It sets the appropriate `pycurl` options for the given HTTP method based on the provided code snippet. If the method is `POST`, it sets the `pycurl.POSTFIELDSIZE` option based on the length of the request body. If the method is `PUT`, it sets the `pycurl.UPLOAD` and `pycurl.INFILESIZE` options based on the request body length."} {"lang":"csharp","raw_index":128468,"index":2710,"seed":"using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Epam.Task6.BackupSystem\n{\n public class InnerChange\n {\n private DateTime dateTime;\n private string currentVerFilePath;\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a backup system for a file management application. The system should track changes made to files and store the previous versions of the files for recovery purposes. Your task is to create a class that represents an individual change made to a file, and implement methods to manage these changes.\n\nYou are provided with a code snippet for the `InnerChange` class, which represents a single change made to a file. The class has two private fields: `dateTime` of type `DateTime` representing the time of the change, and `currentVerFilePath` of type `string` representing the file path of the current version of the file.\n\nYour task is to complete the `InnerChange` class by adding the following functionalities:\n1. Implement a constructor that takes the `dateTime` and `currentVerFilePath` as parameters and initializes the fields.\n2. Implement a method `GetChangeInfo` that returns a string containing the change information in the format \"Change made on {dateTime} for file {currentVerFilePath}\".\n3. Implement a method `Rollback` that takes a file path as a parameter and returns the file path of the previous version of the file if it matches the `currentVerFilePath`, otherwise returns null.\n\nYou should also ensure that the class is properly encapsulated and follows best practices for data manipulation and error handling.","solution":"```csharp\nusing System;\n\nnamespace Epam.Task6.BackupSystem\n{\n public class InnerChange\n {\n private DateTime dateTime;\n private string currentVerFilePath;\n\n public InnerChange(DateTime dateTime, string currentVerFilePath)\n {\n this.dateTime = dateTime;\n this.currentVerFilePath = currentVerFilePath;\n }\n\n public string GetChangeInfo()\n {\n return $\"Change made on {dateTime} for file {currentVerFilePath}\";\n }\n\n public string Rollback(string filePath)\n {\n if (filePath == currentVerFilePath)\n {\n \/\/ Perform rollback logic here, for example, retrieving the previous version file path\n string previousVersionFilePath = GetPreviousVersionFilePath(filePath);\n return previousVersionFilePath;\n }\n else\n {\n return null;\n }\n }\n\n private string GetPreviousVersionFilePath(string currentFilePath)\n {\n \/\/ Implement logic to retrieve the previous version file path based on the current file path\n \/\/ Example logic: if file path is versioned, extract the previous version number and construct the previous version file path\n \/\/ Example: if currentFilePath = \"file_v2.txt\", return \"file_v1.txt\"\n \/\/ If no previous version exists, return null\n \/\/ Replace this logic with actual implementation based on the file versioning system used\n return null;\n }\n }\n}\n```"} {"lang":"php","raw_index":85423,"index":2479,"seed":" if ($date < new DateTime()) {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program that determines whether a given date is in the past or the future. You are given a code snippet that compares a date variable `$date` with the current date using the `DateTime` class. Your task is to complete the program by implementing the necessary logic to determine if the given date is in the past or the future.\n\nYour program should take a date as input and output a message indicating whether the date is in the past or the future.\n\nFor example, given the input date \"2022-12-31\", the program should output \"Future\", and for the input date \"2020-01-01\", the program should output \"Past\".\n\nYou can assume that the input date will be in the format \"YYYY-MM-DD\".","solution":"```php\n\n```"} {"lang":"python","raw_index":37471,"index":30141,"seed":" continue\n\n if min_n_parts <= nparts_dict[name] <= max_n_parts:\n filtered_shape_names.append(name)\n\n return filtered_shape_names\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that filters a list of shape names based on the number of parts each shape has. The function should take in a dictionary containing the names of shapes as keys and the corresponding number of parts as values, along with minimum and maximum thresholds for the number of parts. The function should return a list of shape names that have a number of parts within the specified range.\n\nWrite a function `filter_shapes_by_parts` that takes in the following parameters:\n- `nparts_dict`: a dictionary where the keys are shape names (strings) and the values are the number of parts (integers) for each shape.\n- `min_n_parts`: an integer representing the minimum number of parts a shape should have to be included in the filtered list.\n- `max_n_parts`: an integer representing the maximum number of parts a shape should have to be included in the filtered list.\n\nThe function should return a list of shape names whose number of parts falls within the specified range (inclusive of the minimum and maximum thresholds).\n\nFunction signature: `def filter_shapes_by_parts(nparts_dict: Dict[str, int], min_n_parts: int, max_n_parts: int) -> List[str]:`\n\nExample:\n```python\nnparts_dict = {\n \"circle\": 1,\n \"triangle\": 3,\n \"square\": 4,\n \"pentagon\": 5,\n \"hexagon\": 6\n}\n\nmin_n_parts = 3\nmax_n_parts = 5\n\nfiltered_shapes = filter_shapes_by_parts(nparts_dict, min_n_parts, max_n_parts)\nprint(filtered_shapes) # Output: [\"triangle\", \"square\", \"pentagon\"]\n```","solution":"```python\nfrom typing import Dict, List\n\ndef filter_shapes_by_parts(nparts_dict: Dict[str, int], min_n_parts: int, max_n_parts: int) -> List[str]:\n filtered_shape_names = []\n for name in nparts_dict:\n if min_n_parts <= nparts_dict[name] <= max_n_parts:\n filtered_shape_names.append(name)\n return filtered_shape_names\n```"} {"lang":"python","raw_index":9292,"index":31385,"seed":" elif group.isdigit():\n lim = int(group)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program that simulates a simple game of dice rolling. The program should prompt the user to input the number of dice to roll and then simulate the rolling of that many dice. The sum of the values obtained from rolling the dice should be displayed as the output.\n\nYour task is to complete the function `roll_dice_sum` which takes an integer `num_dice` as input and returns the sum of the values obtained from rolling `num_dice` dice. The function should use the `random` module to simulate the rolling of the dice.\n\nThe provided code snippet is a part of the function that checks if the input for the number of dice is a digit and then converts it to an integer.\n\n```python\nimport random\n\ndef roll_dice_sum(num_dice):\n total_sum = 0\n for _ in range(num_dice):\n roll_value = random.randint(1, 6) # Simulate rolling a single dice\n total_sum += roll_value\n return total_sum\n\n# Example usage\nnum_dice = int(input(\"Enter the number of dice to roll: \"))\nprint(\"Sum of the dice values:\", roll_dice_sum(num_dice))\n```","solution":"```python\nimport random\n\ndef roll_dice_sum(num_dice):\n total_sum = 0\n for _ in range(num_dice):\n roll_value = random.randint(1, 6) # Simulate rolling a single dice\n total_sum += roll_value\n return total_sum\n\n# Example usage\nnum_dice = int(input(\"Enter the number of dice to roll: \"))\nprint(\"Sum of the dice values:\", roll_dice_sum(num_dice))\n```\n\nThe `roll_dice_sum` function simulates rolling the specified number of dice and calculates the sum of the values obtained. It uses a loop to roll each dice and adds the value to the total sum. Finally, it returns the total sum of the dice values."} {"lang":"python","raw_index":148791,"index":35343,"seed":"import shlex\nfrom subprocess import run, Popen, PIPE\n\n\ndef run_shell(cmd: str) -> str:\n \"\"\"Run a shell command using the subprocess module.\"\"\"\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that securely runs shell commands and returns the output. The function should handle potential security risks associated with executing shell commands and ensure that the command's output is captured and returned as a string.\n\nYou need to implement a function `run_secure_shell` that takes a single argument:\n- `cmd` (string): A shell command to be executed.\n\nThe function should:\n1. Use the `subprocess` module to securely run the provided shell command.\n2. Capture the output of the command and return it as a string.\n3. Ensure that the function handles potential security risks associated with shell command execution.\n\nYour task is to implement the `run_secure_shell` function according to the given specifications.\n\nFunction signature: `def run_secure_shell(cmd: str) -> str`\n\nExample:\n```python\noutput = run_secure_shell(\"ls -l\")\nprint(output)\n```\n\nExpected Output:\n```\ntotal 8\n-rw-r--r-- 1 user user 0 Jan 1 00:00 file1.txt\n-rw-r--r-- 1 user user 0 Jan 1 00:00 file2.txt\n```","solution":"```python\nimport shlex\nfrom subprocess import run, PIPE\n\ndef run_secure_shell(cmd: str) -> str:\n \"\"\"Run a shell command securely using the subprocess module.\"\"\"\n try:\n args = shlex.split(cmd)\n result = run(args, stdout=PIPE, stderr=PIPE, text=True, check=True)\n return result.stdout\n except Exception as e:\n return f\"Error executing command: {e}\"\n```\n\nThe `run_secure_shell` function uses `shlex.split` to safely parse the shell command and then uses `subprocess.run` to securely execute the command. It captures the output and returns it as a string. If any error occurs during command execution, it returns an error message."} {"lang":"python","raw_index":59402,"index":15582,"seed":"\n def setup_physics_scene(self, sim_char_file, char_info, ref_motion_scale, self_collision, actuation):\n self._pb_client.resetSimulation()\n \n self.create_ground()\n \n self._agent = []\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a physics simulation setup function for a character animation system. The function `setup_physics_scene` takes several parameters and is responsible for initializing a physics scene for simulating character movements. The function resets the simulation, creates a ground, and initializes an agent. Your task is to complete the implementation of the `setup_physics_scene` function by adding the necessary code to create the agent based on the provided parameters.\n\nThe function signature and parameters are as follows:\n```python\ndef setup_physics_scene(self, sim_char_file, char_info, ref_motion_scale, self_collision, actuation):\n \"\"\"\n Initialize the physics scene for character animation simulation.\n\n Parameters:\n - sim_char_file: A string representing the file path for the character model.\n - char_info: A dictionary containing information about the character.\n - ref_motion_scale: A float representing the scale for reference motion.\n - self_collision: A boolean indicating whether self-collision is enabled.\n - actuation: A string specifying the type of actuation for the agent.\n\n Returns:\n None\n \"\"\"\n```\n\nYour task is to complete the `setup_physics_scene` function by adding the necessary code to create the agent based on the provided parameters. The agent should be initialized using the `sim_char_file`, `char_info`, `ref_motion_scale`, `self_collision`, and `actuation` parameters.\n\nComplete the function `setup_physics_scene` to create the agent based on the provided parameters and initialize the physics scene for character animation simulation.","solution":"```python\ndef setup_physics_scene(self, sim_char_file, char_info, ref_motion_scale, self_collision, actuation):\n \"\"\"\n Initialize the physics scene for character animation simulation.\n\n Parameters:\n - sim_char_file: A string representing the file path for the character model.\n - char_info: A dictionary containing information about the character.\n - ref_motion_scale: A float representing the scale for reference motion.\n - self_collision: A boolean indicating whether self-collision is enabled.\n - actuation: A string specifying the type of actuation for the agent.\n\n Returns:\n None\n \"\"\"\n self._pb_client.resetSimulation()\n self.create_ground()\n \n # Create the agent based on the provided parameters\n agent_id = self._pb_client.loadURDF(sim_char_file, char_info['base_pos'], char_info['base_orn'])\n self._agent.append(agent_id)\n \n # Set agent properties based on parameters\n self._pb_client.changeDynamics(agent_id, -1, lateralFriction=char_info['lateral_friction'])\n self._pb_client.changeDynamics(agent_id, -1, rollingFriction=char_info['rolling_friction'])\n self._pb_client.changeDynamics(agent_id, -1, restitution=char_info['restitution'])\n \n if self_collision:\n self._pb_client.setCollisionFilterGroupMask(agent_id, -1, 0, 0)\n \n if actuation == 'torque':\n self._pb_client.setJointMotorControlArray(agent_id, range(self._num_joints), controlMode=self._pb_client.TORQUE_CONTROL, forces=[0] * self._num_joints)\n elif actuation == 'position':\n self._pb_client.setJointMotorControlArray(agent_id, range(self._num_joints), controlMode=self._pb_client.POSITION_CONTROL, targetPositions=[0] * self._num_joints, positionGains=[0.1] * self._num_joints, velocityGains=[1] * self._num_joints)\n```"} {"lang":"swift","raw_index":26192,"index":1040,"seed":"\/\/\n\/\/ ViewController.swift\n\/\/ glowing-umbrella\n\/\/\n\/\/ Created by vijayvir on 05\/24\/2017.\n\/\/ Copyright (c) 2017 vijayvir. All rights reserved.\n\/\/\n\nimport UIKit\n\nclass ViewController: UIViewController {\n\n override func viewDidLoad() {\n super.viewDidLoad()\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should take two integer parameters, `start` and `end`, representing the inclusive range within which to find prime numbers. The function should return the sum of all prime numbers within the specified range.\n\nFor example, given the range [1, 10], the prime numbers are 2, 3, 5, and 7, and their sum is 17.\n\nWrite a function `sumOfPrimes` in the language of your choice to solve this problem.","solution":"Here's a Python solution to the problem:\n\n```python\ndef is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef sum_of_primes(start, end):\n prime_sum = 0\n for num in range(start, end + 1):\n if is_prime(num):\n prime_sum += num\n return prime_sum\n\n# Test the function\nstart_range = 1\nend_range = 10\nprint(sum_of_primes(start_range, end_range)) # Output: 17\n```\n\nThe `is_prime` function checks if a number is prime, and the `sum_of_primes` function iterates through the range and accumulates the sum of prime numbers. The provided test case demonstrates the usage of the `sum_of_primes` function."} {"lang":"python","raw_index":33477,"index":9953,"seed":" # Extracts the filepath else sets logs to current working directory\n filepath = self.CMConfig.get(\"LogFilePath\", \".\/\")\n fqname = filepath + \\\n self.CMConfig.get(\"CtrlLogFileName\", \"ctrl.log\")\n if not os.path.isdir(filepath):\n os.mkdir(filepath)\n self.logger = logging.getLogger(\"IPOP Rotating Log\")\n self.logger.setLevel(level)\n # Creates rotating filehandler\n handler = lh.RotatingFileHandler(filename=fqname, maxBytes=self.CMConfig[\"LogFileSize\"],\n backupCount=self.CMConfig[\"BackupLogFileCount\"])\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python class that manages logging for a system. The class should handle the configuration of log files, including setting the file path, log file name, log level, log file size, and the number of backup log files to retain. Additionally, the class should create a rotating file handler for the log files.\n\nYour task is to implement the `LogManager` class with the following requirements:\n- The class should have a method `configure_logging` that takes in a configuration dictionary `CMConfig` and sets up the logging based on the provided configuration.\n- The `configure_logging` method should extract the log file path from the `CMConfig` dictionary. If the path is not specified, it should default to the current working directory.\n- The log file name should be obtained from the `CMConfig` dictionary. If not specified, it should default to \"ctrl.log\".\n- If the specified log file path does not exist, the `configure_logging` method should create the directory.\n- The log level should be set based on the value provided in the `CMConfig` dictionary.\n- The log file size and the number of backup log files to retain should be obtained from the `CMConfig` dictionary.\n- The `configure_logging` method should create a rotating file handler for the log files using the obtained file path, log file name, log file size, and backup log file count.\n\nYour implementation should adhere to the following class structure:\n```python\nimport os\nimport logging\nimport logging.handlers as lh\n\nclass LogManager:\n def __init__(self):\n self.logger = None\n\n def configure_logging(self, CMConfig):\n # Your implementation here\n pass\n```","solution":"```python\nimport os\nimport logging\nimport logging.handlers as lh\n\nclass LogManager:\n def __init__(self):\n self.logger = None\n\n def configure_logging(self, CMConfig):\n filepath = CMConfig.get(\"LogFilePath\", \".\/\")\n fqname = filepath + CMConfig.get(\"CtrlLogFileName\", \"ctrl.log\")\n \n if not os.path.isdir(filepath):\n os.mkdir(filepath)\n \n level = CMConfig.get(\"LogLevel\", \"INFO\")\n self.logger = logging.getLogger(\"IPOP Rotating Log\")\n self.logger.setLevel(level)\n \n handler = lh.RotatingFileHandler(filename=fqname, maxBytes=CMConfig[\"LogFileSize\"],\n backupCount=CMConfig[\"BackupLogFileCount\"])\n self.logger.addHandler(handler)\n```\n\nIn the solution, the `LogManager` class is implemented with the `configure_logging` method that fulfills the specified requirements. The method extracts the log file path, creates the directory if it does not exist, sets the log level, and creates a rotating file handler for the log files based on the provided configuration."} {"lang":"php","raw_index":135431,"index":413,"seed":" 'poll_variants' => PollVariantResource::collection($this->whenLoaded('poll_variants')),\n 'created_at' => $this->created_at?\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a function that processes data from a poll and its variants. The poll data is represented in a JSON format, and you need to extract specific information from it. The provided code snippet is part of a Laravel API resource class that formats the poll data for a response. The 'poll_variants' key contains a collection of poll variants, and the 'created_at' key holds the creation timestamp of the poll. However, there is a syntax error in the code snippet that needs to be fixed.\n\nYour task is to create a function that takes the poll data as input and returns the formatted information in a specific structure. The function should handle the extraction of poll variants and the creation timestamp, and it should also handle the syntax error present in the code snippet.\n\nWrite a function `processPollData($pollData)` that takes a JSON object representing the poll data as input and returns an array with the following structure:\n```\n[\n 'pollVariants' => [\/* array of poll variants *\/],\n 'createdAt' => '\/* creation timestamp in a specific format *\/'\n]\n```\nThe 'pollVariants' key should contain an array of poll variants, and the 'createdAt' key should hold the creation timestamp in a specific format. Additionally, ensure that the function handles any potential errors related to the input data.","solution":"```php\nfunction processPollData($pollData) {\n try {\n $poll = json_decode($pollData, true);\n $pollVariants = isset($poll['poll_variants']) ? $poll['poll_variants'] : [];\n $createdAt = isset($poll['created_at']) ? date('Y-m-d H:i:s', strtotime($poll['created_at'])) : null;\n\n return [\n 'pollVariants' => $pollVariants,\n 'createdAt' => $createdAt\n ];\n } catch (Exception $e) {\n \/\/ Handle any potential errors related to the input data\n return [\n 'pollVariants' => [],\n 'createdAt' => null\n ];\n }\n}\n```\n\nThe `processPollData` function first attempts to decode the input JSON data. It then extracts the poll variants and creation timestamp from the decoded data, handling potential errors using a try-catch block. The function returns the formatted information as an array, ensuring that any errors related to the input data are appropriately handled."} {"lang":"csharp","raw_index":48632,"index":1049,"seed":" {\n migrationBuilder.AddColumn(\n name: \"OptionA\",\n table: \"Question_Banks\",\n type: \"nvarchar(max)\",\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a migration script for a database schema using Entity Framework Core. The database contains a table named \"Question_Banks\" which needs to have a new column added to it. The new column is named \"OptionA\" and its data type is \"nvarchar(max)\".\n\nWrite a C# migration script using Entity Framework Core's migration API to add the \"OptionA\" column to the \"Question_Banks\" table.","solution":"```csharp\n\/\/ Assuming you have a DbContext class named YourDbContext representing the database context\n\nusing Microsoft.EntityFrameworkCore.Migrations;\n\npublic partial class AddOptionAColumnToQuestionBanks : Migration\n{\n protected override void Up(MigrationBuilder migrationBuilder)\n {\n migrationBuilder.AddColumn(\n name: \"OptionA\",\n table: \"Question_Banks\",\n type: \"nvarchar(max)\",\n nullable: true); \/\/ or false based on your requirement\n }\n\n protected override void Down(MigrationBuilder migrationBuilder)\n {\n migrationBuilder.DropColumn(\n name: \"OptionA\",\n table: \"Question_Banks\");\n }\n}\n```\n\nIn this solution, a new migration script named \"AddOptionAColumnToQuestionBanks\" is created. The `Up` method uses the `AddColumn` method of `migrationBuilder` to add the \"OptionA\" column to the \"Question_Banks\" table with the specified data type. The `Down` method is used to revert the changes made in the `Up` method."} {"lang":"java","raw_index":1680,"index":1795,"seed":" this.userID = userID;\n return this;\n }\n \n @ApiModelProperty(example = \"null\", value = \"User ID.\")\n @JsonProperty(\"userID\")\n public String getUserID() {\n return userID;\n }\n public void setUserID(String userID) {\n this.userID = userID;\n }\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simple User class in Java that encapsulates the user's ID and provides getter and setter methods for accessing and modifying the user ID. Additionally, you need to ensure that the user ID is properly documented using the Swagger `@ApiModelProperty` annotation.\n\nYour task is to complete the User class by adding the necessary code to encapsulate the user's ID and provide the required getter, setter, and documentation methods.\n\n```java\nimport io.swagger.annotations.ApiModelProperty;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n\npublic class User {\n private String userID;\n\n \/\/ TODO: Add the necessary code to encapsulate the user's ID and provide getter, setter, and documentation methods\n\n \/\/ TODO: Add the necessary code to encapsulate the user's ID and provide getter, setter, and documentation methods\n}\n```\n\nYour implementation should include the following:\n1. Encapsulate the user's ID using a private field.\n2. Provide a getter method named `getUserID` that returns the user's ID.\n3. Provide a setter method named `setUserID` that sets the user's ID.\n4. Document the user's ID using the Swagger `@ApiModelProperty` annotation with an example value of \"null\" and a description of \"User ID.\"","solution":"```java\nimport io.swagger.annotations.ApiModelProperty;\nimport com.fasterxml.jackson.annotation.JsonProperty;\n\npublic class User {\n private String userID;\n\n @ApiModelProperty(example = \"null\", value = \"User ID.\")\n @JsonProperty(\"userID\")\n public String getUserID() {\n return userID;\n }\n\n public void setUserID(String userID) {\n this.userID = userID;\n }\n}\n```\n\nIn the solution, the User class encapsulates the user's ID using a private field `userID`. The `getUserID` method returns the user's ID and is annotated with `@ApiModelProperty` and `@JsonProperty` to provide documentation and serialization information. The `setUserID` method sets the user's ID. This implementation fulfills the requirements specified in the problem description."} {"lang":"python","raw_index":61684,"index":17940,"seed":" '-DPBL_SMARTSTRAP_POWER',\n '-DPBL_MICROPHONE',\n '-D_TIME_H_',\n ],\n 'do_cache': True,\n }}\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python function that processes a given dictionary containing build configuration options and returns a list of unique preprocessor directives present in the configuration.\n\nYou are given a dictionary `build_config` with the following structure:\n```python\nbuild_config = {\n 'defines': [\n '-DPBL_SDK_2',\n '-DPBL_COLOR',\n '-DPBL_SMARTSTRAP_POWER',\n '-DPBL_MICROPHONE',\n '-D_TIME_H_',\n ],\n 'do_cache': True,\n}\n```\n\nYour task is to implement the function `extract_directives(build_config)` that takes in the `build_config` dictionary and returns a list of unique preprocessor directives present in the `defines` list.\n\nFunction signature: \n```python\ndef extract_directives(build_config: dict) -> list:\n pass\n```\n\nExample:\n```python\nbuild_config = {\n 'defines': [\n '-DPBL_SDK_2',\n '-DPBL_COLOR',\n '-DPBL_SMARTSTRAP_POWER',\n '-DPBL_MICROPHONE',\n '-D_TIME_H_',\n ],\n 'do_cache': True,\n}\n\nprint(extract_directives(build_config))\n```\n\nOutput:\n```\n['-DPBL_SDK_2', '-DPBL_COLOR', '-DPBL_SMARTSTRAP_POWER', '-DPBL_MICROPHONE', '-D_TIME_H_']\n```","solution":"```python\ndef extract_directives(build_config: dict) -> list:\n return build_config.get('defines', [])\n```\n\nThe `extract_directives` function simply retrieves the 'defines' list from the `build_config` dictionary and returns it. Since the task is to extract the unique preprocessor directives, the function directly returns the 'defines' list as it already contains the unique preprocessor directives."} {"lang":"python","raw_index":110436,"index":6729,"seed":"js_complied = execjs.compile(js_code)\n\ndef rsa_enc(content): \n js_func = js_complied.call(\"strEnc\", content, \"1\", \"2\", \"3\")\n return js_func\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python function to decrypt a message that has been encrypted using a JavaScript RSA encryption function. The JavaScript encryption function is provided by the `js_complied` object, which is created using the `execjs.compile(js_code)` method. The `rsa_enc` function takes a message `content` as input and returns the encrypted message using the JavaScript RSA encryption function.\n\nYour task is to implement a Python function `rsa_dec` that takes the encrypted message as input and decrypts it using the corresponding decryption algorithm. You are provided with the JavaScript code for the encryption function, but you need to implement the decryption logic in Python.\n\nThe JavaScript encryption function `strEnc` takes four parameters: the content to be encrypted, and three additional parameters \"1\", \"2\", and \"3\". The exact details of the encryption algorithm are not provided, but you need to reverse engineer the encryption process to decrypt the message in Python.\n\nYour task is to implement the `rsa_dec` function to decrypt the message encrypted using the `rsa_enc` function.\n\n```python\nimport execjs\n\n# Assume js_code contains the JavaScript RSA encryption function\njs_code = \"\"\"\nfunction strEnc(content, param1, param2, param3) {\n \/\/ JavaScript RSA encryption logic\n \/\/ ...\n return encryptedContent;\n}\n\"\"\"\n\njs_complied = execjs.compile(js_code)\n\ndef rsa_enc(content): \n js_func = js_complied.call(\"strEnc\", content, \"1\", \"2\", \"3\")\n return js_func\n\ndef rsa_dec(encrypted_content):\n # Your implementation of the decryption logic here\n # Decrypt the encrypted_content using the corresponding decryption algorithm\n # Return the decrypted message\n pass\n```","solution":"```python\nimport execjs\n\n# Assume js_code contains the JavaScript RSA encryption function\njs_code = \"\"\"\nfunction strEnc(content, param1, param2, param3) {\n \/\/ JavaScript RSA encryption logic\n \/\/ ...\n return encryptedContent;\n}\n\"\"\"\n\njs_complied = execjs.compile(js_code)\n\ndef rsa_enc(content): \n js_func = js_complied.call(\"strEnc\", content, \"1\", \"2\", \"3\")\n return js_func\n\ndef rsa_dec(encrypted_content):\n # Your implementation of the decryption logic here\n # Decrypt the encrypted_content using the corresponding decryption algorithm\n # Return the decrypted message\n # Since the exact details of the encryption algorithm are not provided, the decryption logic would depend on the specific encryption algorithm used in the JavaScript function.\n # This solution assumes a hypothetical decryption algorithm for demonstration purposes.\n decrypted_content = encrypted_content # Placeholder for decryption logic\n return decrypted_content\n```\n\nThe `rsa_dec` function provided in the solution is a placeholder and would need to be replaced with the actual decryption logic based on the specific encryption algorithm used in the JavaScript function."} {"lang":"python","raw_index":121723,"index":23544,"seed":"print(f\"part 1: \", anyone)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program that simulates a simple game of dice rolling. The game involves two players taking turns to roll a six-sided die. The player with the highest total score after a certain number of rounds wins the game. Your task is to implement the game logic and display the winner at the end.\n\nYour program should include the following components:\n1. A function to simulate the rolling of a six-sided die and return the result.\n2. A function to calculate the total score for a player based on a specified number of rounds.\n3. A function to determine the winner based on the total scores of the two players.\n\nYour program should output the winner of the game along with their total score.\n\nExample:\nPlayer 1 total score: 18\nPlayer 2 total score: 20\nPlayer 2 wins!","solution":"```python\nimport random\n\ndef roll_die():\n return random.randint(1, 6)\n\ndef calculate_total_score(player, rounds):\n total_score = 0\n for _ in range(rounds):\n total_score += roll_die()\n return total_score\n\ndef determine_winner(player1_score, player2_score):\n if player1_score > player2_score:\n return \"Player 1\"\n elif player2_score > player1_score:\n return \"Player 2\"\n else:\n return \"It's a tie\"\n\ndef main():\n rounds = 3\n player1_score = calculate_total_score(1, rounds)\n player2_score = calculate_total_score(2, rounds)\n \n print(f\"Player 1 total score: {player1_score}\")\n print(f\"Player 2 total score: {player2_score}\")\n \n winner = determine_winner(player1_score, player2_score)\n print(f\"{winner} wins!\")\n\nif __name__ == \"__main__\":\n main()\n```"} {"lang":"shell","raw_index":105741,"index":4380,"seed":"# Initialize the S3 buckets\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with writing a Python script to automate the process of creating and initializing Amazon S3 buckets. Your script should utilize the Boto3 library to interact with the AWS S3 service. The script should be able to create a new S3 bucket and set up the necessary configurations.\n\nYour script should perform the following tasks:\n1. Import the necessary Boto3 library to interact with AWS services.\n2. Initialize the AWS S3 client using the default credentials.\n3. Create a new S3 bucket with a unique name.\n4. Set the bucket's access control to private.\n5. Enable versioning for the newly created bucket.\n\nWrite a Python function `initialize_s3_bucket()` that accomplishes the above tasks. The function should take the bucket name as a parameter and return the name of the newly created bucket.\n\nExample:\n```python\nbucket_name = initialize_s3_bucket('my-unique-bucket')\nprint(f\"New S3 bucket created: {bucket_name}\")\n```","solution":"```python\nimport boto3\n\ndef initialize_s3_bucket(bucket_name):\n # Initialize the S3 client\n s3 = boto3.client('s3')\n\n # Create a new S3 bucket\n s3.create_bucket(Bucket=bucket_name)\n\n # Set the bucket's access control to private\n s3.put_bucket_acl(Bucket=bucket_name, ACL='private')\n\n # Enable versioning for the bucket\n s3.put_bucket_versioning(Bucket=bucket_name, VersioningConfiguration={'Status': 'Enabled'})\n\n return bucket_name\n```\n\nThe `initialize_s3_bucket()` function initializes the AWS S3 client, creates a new S3 bucket with the specified name, sets the access control to private, and enables versioning for the bucket. The function then returns the name of the newly created bucket."} {"lang":"cpp","raw_index":141132,"index":3123,"seed":"#include \"ph\/Sema\/Sema.h\"\n#include \"ph\/Sema\/Type.h\"\n\nusing namespace phaeton;\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom type system for a programming language. The type system should support basic data types such as integers, floats, and strings, as well as user-defined types. Additionally, the type system should be able to handle type inference and type checking during compilation.\n\nYour task is to create a class `Type` that represents a data type in the custom type system. The `Type` class should have the following functionalities:\n1. Ability to store and retrieve the name of the type.\n2. Support for basic data types (integers, floats, strings) and user-defined types.\n3. Type inference capabilities to determine the type of an expression based on its operands.\n4. Type checking to ensure compatibility of types in expressions and assignments.\n\nUse the provided code snippet as a starting point and implement the `Type` class with the specified functionalities.","solution":"```cpp\n#include \n#include \n#include \n\nnamespace phaeton {\n\n \/\/ Enum for basic data types\n enum BasicType {\n INT,\n FLOAT,\n STRING\n };\n\n class Type {\n private:\n std::string typeName;\n BasicType basicType;\n std::vector userDefinedTypes;\n\n public:\n Type(const std::string& name, BasicType type) : typeName(name), basicType(type) {}\n\n \/\/ Method to retrieve the name of the type\n std::string getTypeName() const {\n return typeName;\n }\n\n \/\/ Method to add user-defined types\n void addUserDefinedType(const Type& type) {\n userDefinedTypes.push_back(type);\n }\n\n \/\/ Method for type inference based on operands\n Type inferType(const Type& operand1, const Type& operand2) {\n \/\/ Logic for type inference based on operands\n \/\/ Example: If operand1 is INT and operand2 is FLOAT, return FLOAT\n }\n\n \/\/ Method for type checking in expressions and assignments\n bool checkTypeCompatibility(const Type& operand1, const Type& operand2) {\n \/\/ Logic for type checking\n \/\/ Example: Check if operand1 and operand2 are compatible for addition\n }\n };\n\n} \/\/ namespace phaeton\n```\n\nIn the solution, the `Type` class is implemented with the specified functionalities. It includes support for basic data types using an enum `BasicType`, storage for user-defined types using a vector, and methods for type inference and type checking. The `inferType` method can be implemented with logic to determine the resulting type based on the types of operands, and the `checkTypeCompatibility` method can be implemented to verify compatibility of types in expressions and assignments."} {"lang":"python","raw_index":12760,"index":19105,"seed":" 'class_targets': p_dict['patient_class_targets'][b][targ]}\n for name in self.cf.roi_items:\n gt_box.update({name: p_dict[\"patient_\"+name][b][targ]})\n results_dict['boxes'][b].append(gt_box)\n\n results_per_patient.append([results_dict, pid])\n\n out_string = 'pred_results_held_out' if self.cf.hold_out_test_set else 'pred_results'\n with open(os.path.join(self.cf.fold_dir, '{}.pkl'.format(out_string)), 'wb') as handle:\n pickle.dump(results_per_patient, handle)\n\n if return_results:\n # -------------- results processing, clustering, etc. -----------------\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a medical imaging project where you need to process and analyze the results of a machine learning model's predictions on patient data. The given code snippet is a part of the result processing and saving logic. Your task is to create a Python function that processes the saved results and performs a specific analysis on the data.\n\nYou are provided with a list of patient results, where each result is a dictionary containing patient-specific information and predicted boxes for different regions of interest (ROIs). Each patient's result dictionary has the following structure:\n- `pid`: Patient ID\n- `boxes`: A list of dictionaries, each representing predicted boxes for different ROIs. Each ROI dictionary contains the predicted box coordinates and class targets.\n\nYour task is to implement a function `process_results` that takes the list of patient results as input and performs the following analysis:\n1. Calculate the average number of predicted boxes per patient across all ROIs.\n2. Identify the patient with the highest number of predicted boxes and return their `pid`.\n3. Calculate the total number of unique class targets across all predicted boxes.\n\nYour function should return a tuple containing the average number of predicted boxes per patient, the `pid` of the patient with the highest number of predicted boxes, and the total number of unique class targets.\n\n```python\ndef process_results(results_per_patient):\n total_predicted_boxes = 0\n max_boxes_patient_pid = None\n max_boxes_count = 0\n unique_class_targets = set()\n\n for result, pid in results_per_patient:\n total_predicted_boxes += sum(len(box) for box in result['boxes'])\n unique_class_targets.update(target for patient_boxes in result['boxes'] for box in patient_boxes for target in box['class_targets'])\n \n if sum(len(box) for box in result['boxes']) > max_boxes_count:\n max_boxes_count = sum(len(box) for box in result['boxes'])\n max_boxes_patient_pid = pid\n\n average_boxes_per_patient = total_predicted_boxes \/ len(results_per_patient)\n return average_boxes_per_patient, max_boxes_patient_pid, len(unique_class_targets)\n```","solution":"The `process_results` function iterates through the list of patient results, calculating the average number of predicted boxes per patient, identifying the patient with the highest number of predicted boxes, and calculating the total number of unique class targets across all predicted boxes. It returns a tuple containing the average number of predicted boxes per patient, the `pid` of the patient with the highest number of predicted boxes, and the total number of unique class targets."} {"lang":"php","raw_index":37564,"index":1852,"seed":"use Illuminate\\Support\\Facades\\Lang;\n\nclass ResetPassword extends ResetPasswordNotification\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a custom notification class for resetting passwords in a Laravel application. The notification class should extend the `Illuminate\\Notifications\\Notification` class and override the `toMail` method to send a reset password email to the user. Additionally, the notification class should utilize the `Lang` facade to retrieve the email content from language files.\n\nYour task is to complete the `ResetPassword` class by implementing the `toMail` method and using the `Lang` facade to retrieve the email content.\n\n```php\nuse Illuminate\\Notifications\\Notification;\nuse Illuminate\\Support\\Facades\\Lang;\n\nclass ResetPassword extends Notification\n{\n public function toMail($notifiable)\n {\n return (new \\Illuminate\\Notifications\\Messages\\MailMessage)\n ->line(Lang::get('password.reset.email_line1'))\n ->action(Lang::get('password.reset.email_action'), url('password\/reset', $this->token))\n ->line(Lang::get('password.reset.email_line2'));\n }\n}\n```","solution":"The `ResetPassword` class extends the `Illuminate\\Notifications\\Notification` class and overrides the `toMail` method to send a reset password email to the user. Inside the `toMail` method, the `Lang` facade is used to retrieve the email content from language files. The `Lang::get` method is used to fetch the email content for the subject, action, and additional lines of the email. The `url` function is used to generate the password reset URL, and the `MailMessage` class is used to construct the email with the retrieved content.\n\nThis solution demonstrates how to create a custom notification class for resetting passwords in a Laravel application, utilizing the `Lang` facade to retrieve email content from language files."} {"lang":"python","raw_index":32350,"index":2810,"seed":"\n\ndef get_username(web_handler):\n data = web_handler.get_current_user()\n if data == DEFAULT_USERNAME:\n return data\n return data['name']\n\n\ndef convert_template_to_relative_path(absolute_path, root_dirs):\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function to convert an absolute file path to a relative path based on a set of root directories. The function should take an absolute path and a list of root directories as input and return the corresponding relative path. If the absolute path is not within any of the root directories, the function should return None.\n\nThe function signature is:\n```python\ndef convert_template_to_relative_path(absolute_path: str, root_dirs: List[str]) -> Optional[str]:\n pass\n```\n\nFor example, given the absolute path \"\/home\/user\/documents\/report.txt\" and the root directories [\"\/home\/user\", \"\/var\/www\"], the function should return \"documents\/report.txt\". If the absolute path is \"\/var\/log\/syslog\" and the root directories are [\"\/home\/user\", \"\/var\/www\"], the function should return None.\n\nYou can assume that the input absolute path will always be a valid absolute path and that the root directories will be non-empty and valid absolute paths.","solution":"```python\nfrom typing import List, Optional\nimport os\n\ndef convert_template_to_relative_path(absolute_path: str, root_dirs: List[str]) -> Optional[str]:\n for root_dir in root_dirs:\n if absolute_path.startswith(root_dir):\n return os.path.relpath(absolute_path, root_dir)\n return None\n```\nThe function iterates through the list of root directories and checks if the absolute path starts with any of the root directories. If a match is found, it uses the `os.path.relpath` function to compute the relative path from the root directory to the absolute path. If no match is found, it returns None."} {"lang":"python","raw_index":15601,"index":25157,"seed":" self.assertIsNone(sot.resource_key)\n self.assertIsNone(sot.resources_key)\n self.assertEqual('\/meters\/%(meter)s', sot.base_path)\n self.assertEqual('metering', sot.service.service_type)\n self.assertTrue(sot.allow_create)\n self.assertFalse(sot.allow_retrieve)\n self.assertFalse(sot.allow_update)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python class that represents a resource in a cloud computing environment. The class, named `Resource`, should have specific attributes and methods to manage the resource. Your task is to complete the implementation of the `Resource` class based on the given requirements and code snippet.\n\nThe `Resource` class should have the following attributes:\n- `resource_key`: A string representing the key for the resource, initially set to `None`.\n- `resources_key`: A string representing the key for multiple resources, initially set to `None`.\n- `base_path`: A string representing the base path for the resource, initially set to `'\/meters\/%(meter)s'`.\n- `service`: An object representing the service associated with the resource, with a `service_type` attribute.\n\nThe `Resource` class should have the following methods:\n- `allow_create()`: Returns a boolean indicating whether the resource allows creation.\n- `allow_retrieve()`: Returns a boolean indicating whether the resource allows retrieval.\n- `allow_update()`: Returns a boolean indicating whether the resource allows updating.\n\nYou are provided with a partial test snippet that asserts certain attributes and methods of the `Resource` class. Your task is to complete the implementation of the `Resource` class to satisfy the given test assertions.\n\nComplete the implementation of the `Resource` class to pass the provided test assertions.\n\n```python\nclass Resource:\n def __init__(self, service_type, allow_create, allow_retrieve, allow_update):\n self.resource_key = None\n self.resources_key = None\n self.base_path = '\/meters\/%(meter)s'\n self.service = Service(service_type)\n self.allow_create = allow_create\n self.allow_retrieve = allow_retrieve\n self.allow_update = allow_update\n\n def allow_create(self):\n return self.allow_create\n\n def allow_retrieve(self):\n return self.allow_retrieve\n\n def allow_update(self):\n return self.allow_update\n\nclass Service:\n def __init__(self, service_type):\n self.service_type = service_type\n\n# Test assertions\nsot = Resource('metering', True, False, False)\nassert sot.resource_key is None\nassert sot.resources_key is None\nassert sot.base_path == '\/meters\/%(meter)s'\nassert sot.service.service_type == 'metering'\nassert sot.allow_create() is True\nassert sot.allow_retrieve() is False\nassert sot.allow_update() is False\n```","solution":"```python\nclass Resource:\n def __init__(self, service_type, allow_create, allow_retrieve, allow_update):\n self.resource_key = None\n self.resources_key = None\n self.base_path = '\/meters\/%(meter)s'\n self.service = Service(service_type)\n self.allow_create = allow_create\n self.allow_retrieve = allow_retrieve\n self.allow_update = allow_update\n\n def allow_create(self):\n return self.allow_create\n\n def allow_retrieve(self):\n return self.allow_retrieve\n\n def allow_update(self):\n return self.allow_update\n\nclass Service:\n def __init__(self, service_type):\n self.service_type = service_type\n\n# Test assertions\nsot = Resource('metering', True, False, False)\nassert sot.resource_key is None\nassert sot.resources_key is None\nassert sot.base_path == '\/meters\/%(meter)s'\nassert sot.service.service_type == 'metering'\nassert sot.allow_create() is True\nassert sot.allow_retrieve() is False\nassert sot.allow_update() is False\n```"} {"lang":"python","raw_index":79212,"index":33069,"seed":" name: str,\n value: typing.Any,\n type_: str = None,\n value_info: typing.Mapping = None\n ) -> None:\n \"\"\"Add a variable for the evaluation of the conditions.\n\n :param name: Name of the variable.\n :param value: Value of the variable.\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python class that represents a condition evaluator. The class should allow the user to add variables and evaluate conditions based on these variables.\n\nYour task is to implement the `ConditionEvaluator` class with the following requirements:\n- The class should have a method `add_variable` to add a variable for the evaluation of conditions.\n- The `add_variable` method should take the following parameters:\n - `name` (str): Name of the variable.\n - `value` (any): Value of the variable.\n - `type_` (str, optional): Type of the variable.\n - `value_info` (mapping, optional): Additional information about the value.\n- The class should have a method `evaluate` to evaluate a condition based on the added variables.\n- The `evaluate` method should take a string parameter `condition` representing the condition to be evaluated.\n- The `evaluate` method should return `True` if the condition is satisfied based on the added variables, and `False` otherwise.\n\nYour implementation should adhere to the following constraints:\n- Variable names are unique.\n- Conditions can involve basic comparisons (e.g., `==`, `!=`, `<`, `>`, `<=`, `>=`) and logical operators (`and`, `or`, `not`).\n- The variables and conditions will only involve integer and string types.\n\nExample:\n```python\nevaluator = ConditionEvaluator()\nevaluator.add_variable(\"x\", 10, \"int\")\nevaluator.add_variable(\"y\", 20, \"int\")\nevaluator.add_variable(\"name\", \"John\", \"str\")\nprint(evaluator.evaluate(\"x < y and name == 'John'\")) # Output: True\nprint(evaluator.evaluate(\"x > y or name != 'Jane'\")) # Output: True\n```","solution":"```python\nimport typing\n\nclass ConditionEvaluator:\n def __init__(self):\n self.variables = {}\n\n def add_variable(self, name: str, value: typing.Any, type_: str = None, value_info: typing.Mapping = None) -> None:\n if name in self.variables:\n raise ValueError(f\"Variable '{name}' already exists.\")\n self.variables[name] = (value, type_, value_info)\n\n def evaluate(self, condition: str) -> bool:\n local_vars = self.variables.copy()\n for var_name, (value, _, _) in local_vars.items():\n exec(f\"{var_name} = {repr(value)}\")\n return eval(condition, {}, local_vars)\n```\n\nThe `ConditionEvaluator` class is implemented with an `add_variable` method to add variables and an `evaluate` method to evaluate conditions based on the added variables. The `add_variable` method stores the variables in a dictionary, and the `evaluate` method uses the `eval` function to evaluate the condition based on the stored variables."} {"lang":"swift","raw_index":31009,"index":2725,"seed":" isDecideDissmiss = true\n\n UIView.animate(withDuration: SlideLeafConst.imageTransitionDuration, animations: {\n self.rotationBlackImageView.alpha = 0\n let isScrollUp = velocityY < 0\n let height = self.view.frame.height\n self.selectedCell.frame.origin.y = isScrollUp ? -height : height\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that simulates a decision-making process for dismissing a view in a mobile application. The provided code snippet is part of an animation block that handles the dismissal of a view by animating its movement and opacity. Your task is to create a function that determines whether the view should be dismissed based on the velocity of the user's gesture.\n\nYou are given the following information:\n- The variable `isDecideDissmiss` is a boolean flag that indicates whether the decision to dismiss the view has been made.\n- The `UIView.animate` block animates the dismissal of a view by adjusting the alpha value of an image view and the position of a selected cell.\n- The variable `velocityY` represents the vertical velocity of the user's gesture.\n- The `height` variable represents the height of the view's container.\n\nYour task is to implement a function `shouldDismissView(velocityY: CGFloat, isDecideDissmiss: Bool) -> Bool` that determines whether the view should be dismissed based on the given velocity and the current dismissal decision flag.\n\nFunction Signature: \n```swift\nfunc shouldDismissView(velocityY: CGFloat, isDecideDissmiss: Bool) -> Bool\n```","solution":"```swift\nfunc shouldDismissView(velocityY: CGFloat, isDecideDissmiss: Bool) -> Bool {\n if isDecideDissmiss {\n \/\/ If the decision to dismiss has already been made, return true to dismiss the view\n return true\n } else {\n \/\/ If the decision to dismiss has not been made, determine based on the velocity\n let isScrollUp = velocityY < 0\n return isScrollUp ? true : false\n }\n}\n```\n\nThe `shouldDismissView` function first checks if the decision to dismiss has already been made. If `isDecideDissmiss` is true, it returns true to dismiss the view. If the decision has not been made, it determines whether to dismiss the view based on the direction of the gesture's velocity. If the velocity is negative (indicating a scroll up), the function returns true to dismiss the view; otherwise, it returns false."} {"lang":"python","raw_index":116027,"index":28914,"seed":"\n\n\n# import os\n# import shutil\n# file=open(\"\/media\/ubuntu\/\u65b0\u52a0\u5377\/xiangmu\/dataset\/ImageSets\/Main\/test.txt\",'r')\n# list_=[]\n# for line in file.readlines():\n# \tlist_.append(line.strip()+'.jpg')\n# \tprint(line)\n# print(list_)\n# img=os.listdir(\"\/media\/ubuntu\/\u65b0\u52a0\u5377\/xiangmu\/dataset\/JPEGImages\")\n# print(len(img))\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a project that involves processing image files and their corresponding labels. You have a text file containing a list of image filenames without extensions, and you need to create a Python script to append the \".jpg\" extension to each filename and then check if the corresponding image files exist in a specific directory. If the image files exist, you need to count the total number of images in that directory.\n\nWrite a Python function `process_images` that takes the path to the text file and the directory containing the image files as input. The function should read the text file, append the \".jpg\" extension to each filename, check for the existence of the corresponding image files in the specified directory, and return the total count of existing image files.\n\nThe function signature is:\n```python\ndef process_images(text_file_path: str, image_directory: str) -> int:\n pass\n```\n\nFor example, given the following text file `test.txt`:\n```\nimage1\nimage2\nimage3\n```\nand the image directory containing the files:\n```\nimage1.jpg\nimage2.jpg\nimage4.jpg\n```\nthe function call `process_images('test.txt', 'image_directory')` should return `2`, as only `image1.jpg` and `image2.jpg` exist in the specified directory.\n\nAssume that the text file contains one image filename per line, and the image filenames in the text file do not have any file extensions.","solution":"```python\nimport os\n\ndef process_images(text_file_path: str, image_directory: str) -> int:\n image_count = 0\n with open(text_file_path, 'r') as file:\n image_filenames = [line.strip() + '.jpg' for line in file.readlines()]\n \n for filename in image_filenames:\n if os.path.exists(os.path.join(image_directory, filename)):\n image_count += 1\n \n return image_count\n```\nThe `process_images` function first reads the text file and appends the \".jpg\" extension to each filename. Then, it iterates through the modified filenames, checks for the existence of the corresponding image files in the specified directory using `os.path.exists`, and increments the `image_count` if the file exists. Finally, it returns the total count of existing image files."} {"lang":"python","raw_index":103576,"index":15736,"seed":"1-10\nfrom collections import Counter\nclass Solution(object):\n def largestOverlap(self, A, B):\n \"\"\"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: int\n \"\"\"\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given two square matrices A and B of the same size. Each matrix contains only 0s and 1s. Your task is to find the largest possible overlap between the two matrices by sliding A over B, or B over A, in any direction. The overlap is defined as the number of 1s that are common in the overlapping regions of A and B.\n\nYou need to implement the `largestOverlap` function in the `Solution` class, which takes in two parameters:\n- A: A List of Lists representing the first matrix A (n x n, 1 <= n <= 100)\n- B: A List of Lists representing the second matrix B (n x n, 1 <= n <= 100)\n\nThe function should return an integer representing the largest possible overlap between the two matrices.\n\nFor example, given A and B as follows:\nA = [[1, 1, 0],\n [0, 1, 0],\n [0, 1, 0]]\nB = [[0, 0, 0],\n [0, 1, 1],\n [0, 0, 1]]\n\nThe largest overlap is 3, as A can be overlapped with B as follows:\n[[0, 1, 1],\n [0, 1, 0],\n [0, 1, 0]]\n\nEnsure that your solution efficiently handles large input matrices.","solution":"```python\nfrom collections import Counter\n\nclass Solution(object):\n def largestOverlap(self, A, B):\n n = len(A)\n count = Counter()\n max_overlap = 0\n\n for i in range(n):\n for j in range(n):\n if A[i][j] == 1:\n for x in range(n):\n for y in range(n):\n if B[x][y] == 1:\n count[(i - x, j - y)] += 1\n max_overlap = max(max_overlap, count[(i - x, j - y)])\n\n return max_overlap\n```\nThe solution uses a Counter to keep track of the number of overlaps for each relative position of A and B. It iterates through each cell of A and B, and for each pair of 1s, it calculates the relative position and increments the count in the Counter. Finally, it returns the maximum overlap count found. This solution has a time complexity of O(n^4) where n is the size of the matrices, and it efficiently handles large input matrices."} {"lang":"rust","raw_index":17379,"index":3991,"seed":" targ.operating_system() == mtarg.operating_system()\n }\n\n __check\n }};\n\n (*-*-*) => {{\n fn __check(_: &$crate::Target) -> bool {\n true\n }\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom testing framework for a software development company. The framework should support the creation of test cases for various components of the company's software products. Your task is to create a function that checks whether two target objects have the same operating system.\n\nYou are provided with a code snippet that includes a partial implementation of the testing framework. The snippet contains a macro definition and a function that checks the operating system of a target object. Your task is to complete the implementation by writing the missing parts of the code.\n\nYour task is to complete the implementation of the testing framework by filling in the missing parts of the code snippet. Specifically, you need to implement the missing parts of the macro and the function to compare the operating systems of two target objects.\n\nComplete the implementation of the macro `__check` and the function `operating_system` to compare the operating systems of two target objects. The `operating_system` function should return the operating system of a target object, and the `__check` macro should compare the operating systems of two target objects and return true if they are the same.","solution":"```rust\n\/\/ Complete the implementation of the testing framework\nmacro_rules! check {\n ($targ:expr, $mtarg:expr) => {{\n __check(&$targ, &$mtarg)\n }};\n}\n\nfn operating_system(target: &Target) -> &str {\n \/\/ Implement the logic to retrieve the operating system of the target object\n \/\/ For example, if the operating system is stored in a field named \"os\", the implementation would be:\n \/\/ target.os\n}\n\nfn __check(targ: &Target, mtarg: &Target) -> bool {\n operating_system(targ) == operating_system(mtarg)\n}\n```\n\nIn the solution, the `check!` macro is completed to call the `__check` function with the provided target objects. The `operating_system` function is implemented to retrieve the operating system of a target object, and the `__check` function compares the operating systems of two target objects and returns true if they are the same."} {"lang":"python","raw_index":26677,"index":33302,"seed":" self.history = word_data[3]\n self.time_h = word_data[4]\n self.seen = word_data[5]\n self.right = word_data[6]\n self.wrong = word_data[7]\n self.streak = word_data[8]\n self.reported = word_data[9]\n\n def show(self):\n \"\"\"\n shows the previously selected word and react to the input\n\n :return:\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python class for managing word history and statistics in a language learning application. The class should have attributes for word history, time history, seen count, correct count, incorrect count, streak count, and reported count. Additionally, the class should have a method `show` that displays the previously selected word and reacts to user input.\n\nYour task is to complete the implementation of the `WordStats` class by adding the `show` method. The method should display the previously selected word and react to the user's input. The method should take no arguments and should return nothing.\n\nThe `WordStats` class has the following attributes:\n- `history`: a list containing the word history\n- `time_h`: a list containing the time history\n- `seen`: an integer representing the count of how many times the word has been seen\n- `right`: an integer representing the count of how many times the word has been answered correctly\n- `wrong`: an integer representing the count of how many times the word has been answered incorrectly\n- `streak`: an integer representing the current streak of correct answers\n- `reported`: an integer representing how many times the word has been reported\n\nYou need to implement the `show` method to display the previously selected word and react to the user's input. The method should perform the following actions:\n- Display the previously selected word from the `history` list.\n- Prompt the user for input (e.g., \"Did you remember the word? (yes\/no): \").\n- Update the statistics based on the user's input:\n - If the user's input is \"yes\", increment the `seen`, `right`, and `streak` attributes by 1, and reset the `wrong` attribute to 0.\n - If the user's input is \"no\", increment the `seen` and `wrong` attributes by 1, reset the `streak` attribute to 0, and increment the `reported` attribute by 1.\n\nYou should assume that the `history` list always contains at least one word, and the user's input will always be either \"yes\" or \"no\".\n\nComplete the implementation of the `show` method to meet the requirements outlined above.","solution":"```python\nclass WordStats:\n def __init__(self, word_data):\n self.history = word_data[3]\n self.time_h = word_data[4]\n self.seen = word_data[5]\n self.right = word_data[6]\n self.wrong = word_data[7]\n self.streak = word_data[8]\n self.reported = word_data[9]\n\n def show(self):\n \"\"\"\n shows the previously selected word and reacts to the input\n\n :return:\n \"\"\"\n print(\"Previously selected word:\", self.history[-1])\n user_input = input(\"Did you remember the word? (yes\/no): \")\n if user_input == \"yes\":\n self.seen += 1\n self.right += 1\n self.streak += 1\n self.wrong = 0\n elif user_input == \"no\":\n self.seen += 1\n self.wrong += 1\n self.streak = 0\n self.reported += 1\n```\nThis solution completes the implementation of the `WordStats` class by adding the `show` method. The method displays the previously selected word and reacts to the user's input as per the specified requirements."} {"lang":"cpp","raw_index":112663,"index":1202,"seed":"\n#include \n\n#define EOS_SYMBOL S(4, EOS)\n\ntypedef double real_type;\n\nusing eosio::asset;\nusing eosio::symbol_type;\nusing eosio::action;\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a C++ program that calculates the area of a circle using the given code snippet as a starting point. The program should prompt the user to input the radius of the circle and then use the provided `real_type` and `cmath` library to calculate and output the area of the circle.\n\nYour program should follow these requirements:\n- Use the `real_type` defined as `double` for precision in the calculations.\n- Prompt the user to input the radius of the circle.\n- Calculate the area of the circle using the formula: `area = \u03c0 * radius * radius`, where \u03c0 is a constant defined in the `cmath` library.\n- Output the calculated area of the circle with an appropriate message.\n\nYour program should not include any additional libraries or headers beyond those already provided in the code snippet.","solution":"```cpp\n#include \n#include \n\n#define EOS_SYMBOL S(4, EOS)\n\ntypedef double real_type;\n\nusing eosio::asset;\nusing eosio::symbol_type;\nusing eosio::action;\n\nint main() {\n real_type radius, area;\n \n std::cout << \"Enter the radius of the circle: \";\n std::cin >> radius;\n \n area = M_PI * radius * radius; \/\/ Using M_PI constant from cmath for \u03c0\n \n std::cout << \"The area of the circle with radius \" << radius << \" is: \" << area << std::endl;\n \n return 0;\n}\n```\n\nThis program prompts the user to input the radius of a circle, calculates the area using the provided `real_type` and `cmath` library, and then outputs the calculated area of the circle."} {"lang":"typescript","raw_index":102780,"index":3900,"seed":" baseName: \"logs\",\n type: \"Array\",\n format: \"\",\n },\n nextLogId: {\n baseName: \"nextLogId\",\n type: \"string\",\n format: \"\",\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a function that processes a given data structure representing a set of properties for a logging system. The data structure is represented as a JavaScript object with properties and their corresponding metadata. Your goal is to extract specific information from this data structure and perform a transformation on it.\n\nThe data structure has the following format:\n```javascript\nconst loggingSystem = {\n logs: {\n baseName: \"logs\",\n type: \"Array\",\n format: \"\",\n },\n nextLogId: {\n baseName: \"nextLogId\",\n type: \"string\",\n format: \"\",\n },\n \/\/ ... other properties\n};\n```\n\nYou need to create a function `processLoggingSystem` that takes in the `loggingSystem` object and returns an array of objects containing the baseName and type of each property in the logging system. The output should be in the following format:\n```javascript\n[\n { baseName: \"logs\", type: \"Array\" },\n { baseName: \"nextLogId\", type: \"string\" },\n \/\/ ... other properties\n]\n```\n\nWrite the `processLoggingSystem` function to achieve this transformation.","solution":"```javascript\nfunction processLoggingSystem(loggingSystem) {\n const processedProperties = [];\n for (const property in loggingSystem) {\n if (loggingSystem.hasOwnProperty(property)) {\n const { baseName, type } = loggingSystem[property];\n processedProperties.push({ baseName, type });\n }\n }\n return processedProperties;\n}\n\n\/\/ Example usage\nconst loggingSystem = {\n logs: {\n baseName: \"logs\",\n type: \"Array\",\n format: \"\",\n },\n nextLogId: {\n baseName: \"nextLogId\",\n type: \"string\",\n format: \"\",\n },\n \/\/ ... other properties\n};\n\nconst processedData = processLoggingSystem(loggingSystem);\nconsole.log(processedData);\n```\n\nWhen the `processLoggingSystem` function is called with the provided `loggingSystem` object, it will return an array of objects containing the baseName and type of each property in the logging system. This solution iterates through the properties of the `loggingSystem` object, extracts the required information, and constructs the output array accordingly."} {"lang":"cpp","raw_index":74243,"index":4508,"seed":" vector best(nums.size());\n pq.push({0, -days});\n for (int i = 0; i < nums.size(); ++i) {\n while (pq.top().second < i - days) pq.pop();\n best[i] = pq.top().first;\n \/\/ cerr << pq.top().first << \" \" << pq.top().second << \"\\n\";\n if (i - days - 1 >= 0)\n best[i] = best[i - days - 1] + nums[i] > best[i]\n ? best[i - days - 1] + nums[i]\n : best[i];\n else\n best[i] = nums[i] > best[i] ? nums[i] : best[i];\n if (i - 1 > 0) best[i] = best[i - 1] > best[i] ? best[i - 1] : best[i];\n pq.push({best[i], i});\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given an array `nums` of length `n` and an integer `days`. Your task is to implement a function `maxSumAfterPartitioning` to find the maximum sum of a non-overlapping subarray after partitioning the array into at most `days` non-overlapping subarrays.\n\nThe function signature is:\n```cpp\nint maxSumAfterPartitioning(vector& nums, int days);\n```\n\nThe function should return an integer representing the maximum sum of non-overlapping subarrays after partitioning the array.\n\nFor example, given `nums = [1, 15, 7, 9, 2, 5, 10]` and `days = 3`, the maximum sum after partitioning the array into at most 3 non-overlapping subarrays is 84, achieved by partitioning the array into `[15]`, `[7, 9, 2]`, and `[5, 10]` and then summing the maximum value in each subarray (15, 9, and 10).","solution":"```cpp\n#include \n#include \n#include \nusing namespace std;\n\nint maxSumAfterPartitioning(vector& nums, int days) {\n int n = nums.size();\n vector best(n);\n priority_queue> pq;\n pq.push({0, -days});\n\n for (int i = 0; i < n; ++i) {\n while (pq.top().second < i - days) pq.pop();\n best[i] = pq.top().first;\n\n if (i - days - 1 >= 0)\n best[i] = best[i - days - 1] + nums[i] > best[i] ? best[i - days - 1] + nums[i] : best[i];\n else\n best[i] = nums[i] > best[i] ? nums[i] : best[i];\n\n if (i - 1 > 0) best[i] = best[i - 1] > best[i] ? best[i - 1] : best[i];\n pq.push({best[i], i});\n }\n\n return best[n - 1];\n}\n```\n\nThe `maxSumAfterPartitioning` function initializes a priority queue `pq` to store pairs of integers representing the maximum sum and the end index of the subarray. It then iterates through the input array `nums`, updating the `best` array to store the maximum sum of non-overlapping subarrays. Finally, it returns the maximum sum of non-overlapping subarrays after partitioning the array."} {"lang":"java","raw_index":110575,"index":910,"seed":" queue.add(neighbor);\n unvisitedVertices.remove(neighbor);\n cluster.add(neighbor);\n }\n }\n }\n clusterSet.add(cluster);\n }\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function to find the number of clusters in a given undirected graph. A cluster is defined as a group of connected vertices within the graph. The graph is represented using an adjacency list, and the function should return the total number of clusters present in the graph.\n\nThe graph is represented as a list of vertices, where each vertex is associated with a list of its neighboring vertices. The function should take this adjacency list as input and return the number of clusters present in the graph.\n\nFor example, given the following adjacency list:\n```\ngraph = {\n 0: [1, 2],\n 1: [0, 2],\n 2: [0, 1],\n 3: [4],\n 4: [3]\n}\n```\nThe function should return 2, as there are two clusters in the graph: {0, 1, 2} and {3, 4}.\n\nWrite a function `countClusters(graph)` that takes in the adjacency list of the graph and returns the number of clusters present in the graph.","solution":"```python\ndef countClusters(graph):\n def dfs(vertex, visited, cluster):\n visited.add(vertex)\n cluster.append(vertex)\n for neighbor in graph[vertex]:\n if neighbor not in visited:\n dfs(neighbor, visited, cluster)\n\n num_clusters = 0\n visited_vertices = set()\n for vertex in graph:\n if vertex not in visited_vertices:\n cluster = []\n dfs(vertex, visited_vertices, cluster)\n num_clusters += 1\n return num_clusters\n```\n\nThe `countClusters` function initializes a set to keep track of visited vertices and iterates through each vertex in the graph. For each unvisited vertex, it initiates a depth-first search (DFS) to explore all connected vertices and form a cluster. The function increments the cluster count for each new cluster found and returns the total number of clusters in the graph."} {"lang":"cpp","raw_index":39397,"index":1167,"seed":"#include \"log.h\"\n\nnamespace chrono = std::chrono;\nstatic auto start_tp = chrono::steady_clock::now();\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a logging system that records the time elapsed since the program started. The provided code snippet includes the necessary header file and initializes a static variable `start_tp` with the current time using the `std::chrono` library.\n\nYour task is to create a `Logger` class with a method `logElapsedTime()` that logs the elapsed time in milliseconds since the program started. The `logElapsedTime()` method should use the `start_tp` variable to calculate the elapsed time and then output the result using the provided `log.h` library.\n\nYour implementation should adhere to the following requirements:\n- The `Logger` class should have a constructor that initializes the `start_tp` variable with the current time.\n- The `logElapsedTime()` method should calculate the elapsed time in milliseconds and log it using the provided `log.h` library.\n\nYou are not required to implement the `log.h` library or the `start_tp` initialization; assume they are provided and functional.","solution":"```cpp\n#include \"log.h\"\n#include \n\nclass Logger {\nprivate:\n std::chrono::time_point start_tp;\n\npublic:\n Logger() : start_tp(std::chrono::steady_clock::now()) {}\n\n void logElapsedTime() {\n auto current_tp = std::chrono::steady_clock::now();\n auto elapsed_ms = std::chrono::duration_cast(current_tp - start_tp).count();\n log(\"Elapsed time since program start: \" + std::to_string(elapsed_ms) + \" ms\");\n }\n};\n\n\/\/ Usage example\nint main() {\n Logger logger;\n \/\/ Perform some operations\n \/\/ ...\n logger.logElapsedTime();\n \/\/ Perform more operations\n \/\/ ...\n logger.logElapsedTime();\n return 0;\n}\n```\n\nIn the solution, a `Logger` class is defined with a constructor that initializes the `start_tp` variable with the current time using `std::chrono::steady_clock::now()`. The `logElapsedTime()` method calculates the elapsed time in milliseconds by subtracting the `start_tp` from the current time and then logs the result using the provided `log.h` library. The usage example demonstrates how to create a `Logger` instance and log the elapsed time at different points in the program."} {"lang":"python","raw_index":54849,"index":10539,"seed":" if i <= pre:\n return False\n pre = i\n return True\n\nundefined\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a Python function that is supposed to check if a given list of integers is in strictly increasing order. However, the function contains a bug that causes it to return an incorrect result in some cases. Your task is to identify the bug and fix the function to ensure it correctly determines whether the input list is strictly increasing.\n\nThe original function is as follows:\n```python\ndef is_increasing(arr):\n pre = float('-inf')\n for i in arr:\n if i <= pre:\n return False\n pre = i\n return True\n```\n\nYour task is to:\n1. Identify the bug in the given function.\n2. Modify the function to fix the bug and ensure it correctly determines whether the input list is in strictly increasing order.","solution":"The bug in the given function is that it returns `False` when encountering an element that is equal to the previous element, rather than strictly less than the previous element. To fix this, the comparison should be modified to check for strict inequality.\n\nHere's the corrected function:\n```python\ndef is_increasing(arr):\n pre = float('-inf')\n for i in arr:\n if i <= pre: # Bug: should be i <= pre, not i < pre\n return False\n pre = i\n return True\n```\n\nBy making this change, the function will now correctly determine whether the input list is in strictly increasing order."} {"lang":"python","raw_index":4520,"index":8882,"seed":" # type: (List[T.TColumnType]) -> List[Description]\n \"\"\"\n Return a tuple of (name, type_code, display_size, internal_size,\n precision, scale, null_ok)\n\n https:\/\/www.python.org\/dev\/peps\/pep-0249\/#description\n \"\"\"\n return [Description(col.col_name, col.col_type.type,\n None, None, None, None,\n col.col_type.nullable)\n for col in row_desc]\n\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that processes a list of column descriptions and returns a list of tuples containing specific information about each column. The function should adhere to the provided type hint and documentation.\n\nWrite a Python function `process_column_descriptions` that takes a list of column descriptions and returns a list of tuples containing the following information for each column:\n- Column name\n- Type code\n- Display size\n- Internal size\n- Precision\n- Scale\n- Nullability\n\nThe function signature and documentation are as follows:\n```python\nfrom typing import List, Tuple\n\nclass ColumnType:\n def __init__(self, type: str, nullable: bool):\n self.type = type\n self.nullable = nullable\n\nclass ColumnDescription:\n def __init__(self, col_name: str, col_type: ColumnType):\n self.col_name = col_name\n self.col_type = col_type\n\ndef process_column_descriptions(row_desc: List[ColumnDescription]) -> List[Tuple[str, str, int, int, int, int, bool]]:\n \"\"\"\n Return a list of tuples containing column information for each column description.\n\n Each tuple contains (name, type_code, display_size, internal_size, precision, scale, null_ok).\n\n Args:\n row_desc (List[ColumnDescription]): List of column descriptions\n\n Returns:\n List[Tuple[str, str, int, int, int, int, bool]]: List of tuples containing column information\n \"\"\"\n # Your implementation here\n```\n\nFor example, given the input `row_desc` as a list of `ColumnDescription` objects:\n```python\nrow_desc = [\n ColumnDescription(\"id\", ColumnType(\"int\", False)),\n ColumnDescription(\"name\", ColumnType(\"varchar\", True)),\n ColumnDescription(\"age\", ColumnType(\"int\", True))\n]\n```\nThe function `process_column_descriptions(row_desc)` should return a list of tuples as follows:\n```python\n[(\"id\", \"int\", None, None, None, None, False),\n (\"name\", \"varchar\", None, None, None, None, True),\n (\"age\", \"int\", None, None, None, None, True)]\n```","solution":"```python\ndef process_column_descriptions(row_desc: List[ColumnDescription]) -> List[Tuple[str, str, int, int, int, int, bool]]:\n column_info = []\n for col in row_desc:\n column_info.append((col.col_name, col.col_type.type, None, None, None, None, col.col_type.nullable))\n return column_info\n```\n\nThe `process_column_descriptions` function iterates through the list of `ColumnDescription` objects and constructs a list of tuples containing the required column information. The function returns this list as the output."} {"lang":"csharp","raw_index":39332,"index":1668,"seed":" {\n public WxPayException(string msg) : base(msg)\n {\n\n }\n }\n}\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom exception class for a payment processing system. The custom exception class, named `WxPayException`, should be designed to handle errors specific to the WeChat Pay integration. The class should inherit from the base `Exception` class and have a constructor that accepts a message as a parameter.\n\nYour task is to complete the implementation of the `WxPayException` class by providing the missing code for the constructor.\n\nComplete the following code snippet to implement the `WxPayException` class:\n\n```csharp\nusing System;\n\npublic class WxPayException : Exception\n{\n \/\/ Complete the constructor for the WxPayException class\n public WxPayException(string msg) : base(msg)\n {\n \/\/ Your code here\n }\n}\n```\n\nYour implementation should ensure that the `WxPayException` class can be instantiated with a custom error message and that the base `Exception` class is properly initialized with the provided message.","solution":"```csharp\nusing System;\n\npublic class WxPayException : Exception\n{\n public WxPayException(string msg) : base(msg)\n {\n \/\/ The constructor for the WxPayException class is already complete\n \/\/ No additional code is required here\n }\n}\n```\n\nThe provided solution completes the implementation of the `WxPayException` class by defining the constructor that accepts a message parameter and passes it to the base `Exception` class using the `base` keyword. This ensures that the custom exception class can be instantiated with a custom error message and properly handles errors specific to the WeChat Pay integration."} {"lang":"shell","raw_index":96667,"index":1932,"seed":"\nif wmii9rc; then\n\tWMIIRC=`PATH=\"$WMII_CONFPATH:$PATH\" which rc.wmii`\nelse\n\tWMIIRC=`PATH=\"$WMII_CONFPATH:$PATH\" which wmiirc`\nfi\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with writing a script to determine the value of the variable `WMIIRC` based on the conditions provided in the given code snippet. The script should handle the cases where the `wmii9rc` variable is true and false, and set the `WMIIRC` variable accordingly.\n\nThe script should follow these rules:\n- If `wmii9rc` is true, set `WMIIRC` to the result of the command `PATH=\"$WMII_CONFPATH:$PATH\" which rc.wmii`.\n- If `wmii9rc` is false, set `WMIIRC` to the result of the command `PATH=\"$WMII_CONFPATH:$PATH\" which wmiirc`.\n\nWrite a script that accomplishes this task and outputs the value of `WMIIRC` based on the given conditions.","solution":"```bash\n#!\/bin\/bash\n\n# Set the value of wmii9rc (true or false)\nwmii9rc=true\n\n# Set the value of WMII_CONFPATH\nWMII_CONFPATH=\"\/path\/to\/conf\"\n\nif [ \"$wmii9rc\" = true ]; then\n WMIIRC=$(PATH=\"$WMII_CONFPATH:$PATH\" which rc.wmii)\nelse\n WMIIRC=$(PATH=\"$WMII_CONFPATH:$PATH\" which wmiirc)\nfi\n\necho \"WMIIRC value: $WMIIRC\"\n```\n\nWhen the script is executed, it will output the value of `WMIIRC` based on the conditions specified in the problem description."} {"lang":"python","raw_index":56427,"index":14547,"seed":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\nimport sys, os\nimport tracking\n\nsetup(\n name='django-tracking',\n version=tracking.get_version(),\n description=\"Basic visitor tracking and blacklisting for Django\",\n long_description=open('README.rst', 'r').read(),\n keywords='django, tracking, visitors',\n author='',\n author_email='',\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python package that tracks and logs user interactions on a website. The package should be able to capture and store information about the visitors, such as their IP addresses, user agents, and the pages they visit. Additionally, it should provide functionality to blacklist certain visitors based on predefined criteria.\n\nYour task is to implement the core functionality of the tracking package by creating a class called `VisitorTracker`. This class should have the following methods:\n\n1. `__init__(self)`: A constructor method that initializes an empty list to store visitor information.\n\n2. `track_visit(self, ip_address, user_agent, page_visited)`: A method that takes in the visitor's IP address, user agent, and the page they visited, and stores this information in a suitable data structure.\n\n3. `get_visitors(self)`: A method that returns the list of all visitors along with their information.\n\n4. `blacklist_visitor(self, ip_address)`: A method that takes in an IP address and adds it to a blacklist of visitors.\n\n5. `get_blacklisted_visitors(self)`: A method that returns the list of all blacklisted visitors.\n\nYou should also create a module-level function called `get_version()` that returns the version of the tracking package.\n\nYour implementation should be able to handle multiple visitors and blacklisted visitors, and should provide the necessary functionality to track and manage visitor information effectively.","solution":"```python\nclass VisitorTracker:\n def __init__(self):\n self.visitors = []\n\n def track_visit(self, ip_address, user_agent, page_visited):\n self.visitors.append({'ip_address': ip_address, 'user_agent': user_agent, 'page_visited': page_visited})\n\n def get_visitors(self):\n return self.visitors\n\n def blacklist_visitor(self, ip_address):\n for visitor in self.visitors:\n if visitor['ip_address'] == ip_address:\n visitor['blacklisted'] = True\n\n def get_blacklisted_visitors(self):\n return [visitor for visitor in self.visitors if visitor.get('blacklisted')]\n\ndef get_version():\n return '1.0.0'\n```\n\nThis solution provides a `VisitorTracker` class with methods to track visits, retrieve visitors, blacklist visitors, and retrieve blacklisted visitors. The `get_version()` function returns the version of the tracking package."} {"lang":"python","raw_index":147839,"index":39135,"seed":" assert not request.is_valid()\n assert len(request.errors) == 1\n error = request.errors[0]\n assert error.parameter == 'task_id'\n assert error.message == 'is required'\n\n\ndef test_cancel_task_bad_request():\n task_id = 'abc'\n request = CancelTaskRequest(task_id)\n\n assert request.task_id == task_id\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class to handle cancellation requests for tasks. The provided code snippet contains a test case for a `CancelTaskRequest` class, which is expected to validate the request and handle any errors. Your task is to create the `CancelTaskRequest` class and ensure that it correctly handles the validation and error messages as per the assertions in the code snippet.\n\nThe `CancelTaskRequest` class should have the following requirements:\n- It should have a constructor that takes a `task_id` as a parameter.\n- It should have a method `is_valid()` that returns `True` if the request is valid and `False` otherwise.\n- If the request is invalid, it should have a property `errors` that contains a list of error objects.\n- Each error object should have `parameter` and `message` attributes.\n\nYour task is to implement the `CancelTaskRequest` class to satisfy the assertions in the provided code snippet.","solution":"```python\nclass CancelTaskRequest:\n def __init__(self, task_id):\n self.task_id = task_id\n self.errors = []\n\n def is_valid(self):\n if not self.task_id:\n self.errors.append(Error('task_id', 'is required'))\n return False\n return True\n\n\nclass Error:\n def __init__(self, parameter, message):\n self.parameter = parameter\n self.message = message\n```\n\nIn the solution, the `CancelTaskRequest` class is implemented with a constructor that takes a `task_id` parameter. It also contains the `is_valid()` method that checks if the `task_id` is present and appends an error object to the `errors` list if it is not. The `Error` class is also defined to represent the error objects with `parameter` and `message` attributes."} {"lang":"php","raw_index":136976,"index":1240,"seed":" Schema::dropIfExists('receivables');\n }\n}\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a database migration script for a fictional accounting application. The application needs to manage receivables, which are records of money owed to the company. The database schema includes a table named \"receivables\" that needs to be modified. The existing \"receivables\" table should be dropped to accommodate changes in the application's requirements. Your task is to write a database migration script using Laravel's Schema Builder to drop the \"receivables\" table.\n\nYour script should use Laravel's Schema class and its methods to perform the necessary database operation. Specifically, you need to use the \"dropIfExists\" method provided by the Schema class to drop the \"receivables\" table.\n\nWrite a migration script that accomplishes this task.","solution":"```php\nid();\n \/\/ $table->string('customer_name');\n \/\/ $table->decimal('amount', 10, 2);\n \/\/ $table->timestamps();\n \/\/ });\n }\n}\n```\n\nIn the provided solution, a Laravel migration script named \"DropReceivablesTable\" is created. The \"up\" method uses the Schema class's \"dropIfExists\" method to drop the \"receivables\" table. The \"down\" method is left empty, but it can be used to recreate the \"receivables\" table if needed. This script can be executed to drop the \"receivables\" table from the database."} {"lang":"rust","raw_index":43140,"index":3759,"seed":"\/\/ this isn't a tremendously useful size limiter, as it controls the number of chunks that can be in\n\/\/ flight before applying backpressure, as opposed to the size of data in those chunks\nconst STREAMING_CHANNEL_SIZE: usize = 128;\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a size-limited streaming channel in Rust. The streaming channel should allow a maximum of `STREAMING_CHANNEL_SIZE` chunks to be in flight before applying backpressure. The chunks represent data being streamed through the channel.\n\nYour task is to implement the `StreamingChannel` struct with the following methods:\n1. `new()`: Creates a new instance of `StreamingChannel`.\n2. `send(&self, data: Vec) -> Result<(), String>`: Sends a chunk of data through the channel. If the number of chunks in flight exceeds `STREAMING_CHANNEL_SIZE`, this method should return an error with the message \"Backpressure applied, too many chunks in flight\".\n3. `receive(&self) -> Option>`: Receives a chunk of data from the channel. If there is no data available, this method should return `None`.\n\nYou should also write a test to verify the behavior of the `StreamingChannel` struct.\n\nUse the provided `STREAMING_CHANNEL_SIZE` constant to limit the number of chunks in flight.\n\n```rust\n\/\/ this isn't a tremendously useful size limiter, as it controls the number of chunks that can be in\n\/\/ flight before applying backpressure, as opposed to the size of data in those chunks\nconst STREAMING_CHANNEL_SIZE: usize = 128;\n\nstruct StreamingChannel {\n \/\/ Implement the necessary fields here\n}\n\nimpl StreamingChannel {\n fn new() -> Self {\n \/\/ Implement the new method here\n }\n\n fn send(&self, data: Vec) -> Result<(), String> {\n \/\/ Implement the send method here\n }\n\n fn receive(&self) -> Option> {\n \/\/ Implement the receive method here\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_streaming_channel() {\n \/\/ Write your test case here\n }\n}\n```","solution":"```rust\nconst STREAMING_CHANNEL_SIZE: usize = 128;\n\nstruct StreamingChannel {\n in_flight: usize,\n}\n\nimpl StreamingChannel {\n fn new() -> Self {\n StreamingChannel { in_flight: 0 }\n }\n\n fn send(&mut self, data: Vec) -> Result<(), String> {\n if self.in_flight >= STREAMING_CHANNEL_SIZE {\n return Err(\"Backpressure applied, too many chunks in flight\".to_string());\n }\n self.in_flight += 1;\n \/\/ Simulate sending data\n \/\/ ...\n Ok(())\n }\n\n fn receive(&mut self) -> Option> {\n if self.in_flight > 0 {\n self.in_flight -= 1;\n \/\/ Simulate receiving data\n \/\/ ...\n Some(vec![0; 10]) \/\/ Placeholder for received data\n } else {\n None\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_streaming_channel() {\n let mut channel = StreamingChannel::new();\n assert_eq!(channel.send(vec![0; 10]), Ok(()));\n assert_eq!(channel.send(vec![0; 10]), Ok(()));\n assert_eq!(channel.send(vec![0; 10]), Err(\"Backpressure applied, too many chunks in flight\".to_string()));\n assert_eq!(channel.receive(), Some(vec![0; 10]));\n assert_eq!(channel.receive(), Some(vec![0; 10]));\n assert_eq!(channel.receive(), None);\n }\n}\n```\n\nIn this solution, the `StreamingChannel` struct maintains the number of chunks in flight and applies backpressure when the limit is reached. The `send` method returns an error if the limit is exceeded, and the `receive` method returns `None` if there is no data available. The test case verifies the behavior of the `StreamingChannel` struct."} {"lang":"typescript","raw_index":99732,"index":3235,"seed":" render () {}\n\n \/**\n * get form inputs and validate\n *\/\n getInputs(): {name: string, description: string} | void{\n const heroName: string = this.heroNameEl.value;\n if(!validator({value: heroName, minLength: 3, maxLength: 20})) {\n alert(\"Hero name must be greater than 3 and less than 20 charaters\");\n return\n }\n const description: string = this.descriptionEl.value;\n if(!validator({value: description, minLength: 5, maxLength: 100})) {\n alert(\"Hero Description must be greater than 5 and less than 100 charaters\");\n return\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a form validation function for a superhero creation application. The application has a method `getInputs` that retrieves and validates the user input for the superhero's name and description. The `getInputs` method returns an object containing the name and description if the input is valid, or `void` if the input is invalid. The `validator` function is used to check the input against specified length constraints.\n\nYour task is to implement the `validator` function and ensure that the `getInputs` method correctly validates the input according to the given constraints.\n\nThe `validator` function takes an object with the following properties:\n- `value`: The input value to be validated (string).\n- `minLength`: The minimum length allowed for the input value (number).\n- `maxLength`: The maximum length allowed for the input value (number).\n\nThe `getInputs` method retrieves the superhero's name and description from input elements (`heroNameEl` and `descriptionEl`) and validates them using the `validator` function. If the input is valid, it returns an object with the name and description; otherwise, it displays an alert message and returns `void`.\n\nYour task is to implement the `validator` function and ensure that the `getInputs` method correctly validates the input according to the given constraints.","solution":"```typescript\n\/**\n * Validates the input value based on the specified length constraints.\n * @param {Object} options - The options for validation.\n * @param {string} options.value - The input value to be validated.\n * @param {number} options.minLength - The minimum length allowed for the input value.\n * @param {number} options.maxLength - The maximum length allowed for the input value.\n * @returns {boolean} - True if the input value is valid, false otherwise.\n *\/\nfunction validator({ value, minLength, maxLength }: { value: string, minLength: number, maxLength: number }): boolean {\n return value.length >= minLength && value.length <= maxLength;\n}\n\nclass SuperheroForm {\n heroNameEl: HTMLInputElement;\n descriptionEl: HTMLInputElement;\n\n constructor(heroNameEl: HTMLInputElement, descriptionEl: HTMLInputElement) {\n this.heroNameEl = heroNameEl;\n this.descriptionEl = descriptionEl;\n }\n\n \/**\n * Retrieves and validates the superhero's name and description.\n * @returns {Object | void} - An object containing the name and description if the input is valid, or void if the input is invalid.\n *\/\n getInputs(): { name: string, description: string } | void {\n const heroName: string = this.heroNameEl.value;\n if (!validator({ value: heroName, minLength: 3, maxLength: 20 })) {\n alert(\"Hero name must be greater than 3 and less than 20 characters\");\n return;\n }\n const description: string = this.descriptionEl.value;\n if (!validator({ value: description, minLength: 5, maxLength: 100 })) {\n alert(\"Hero Description must be greater than 5 and less than 100 characters\");\n return;\n }\n return { name: heroName, description: description };\n }\n}\n\n\/\/ Example usage\nconst heroNameInput = document.getElementById('heroName') as HTMLInputElement;\nconst descriptionInput = document.getElementById('description') as HTMLInputElement;\nconst superheroForm = new SuperheroForm(heroNameInput, descriptionInput);\nconst inputs = superheroForm.getInputs();\nif (inputs) {\n console.log(\"Valid inputs:\", inputs);\n} else {\n console.log(\"Invalid inputs\");\n}\n```"} {"lang":"shell","raw_index":105666,"index":1818,"seed":"plugin\/trino-oracle\/src\/test\/resources\/restart.sh\n#!\/usr\/bin\/env bash\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a script to automate the restart of a Trino (formerly known as PrestoSQL) server running on a Linux system. The script should stop the Trino server, perform any necessary cleanup or maintenance tasks, and then start the server again. Your task is to write a Bash script that accomplishes this restart process.\n\nYour script should perform the following steps:\n1. Stop the Trino server by sending a signal to the Trino process.\n2. Wait for the Trino server process to terminate gracefully.\n3. Perform any necessary cleanup or maintenance tasks, such as clearing temporary files or logs.\n4. Start the Trino server again.\n\nYour script should be named `restart_trino.sh` and should be executable.","solution":"```bash\n#!\/usr\/bin\/env bash\n\n# Step 1: Stop the Trino server\necho \"Stopping Trino server...\"\nkill -15 $(pgrep -f trino-server) # Send SIGTERM to the Trino server process\n\n# Step 2: Wait for the Trino server process to terminate gracefully\nwait_time=30 # Maximum time to wait for the process to terminate (in seconds)\nif pgrep -f trino-server > \/dev\/null; then\n echo \"Waiting for Trino server to stop...\"\n sleep $wait_time\n if pgrep -f trino-server > \/dev\/null; then\n echo \"Trino server did not stop gracefully. Sending SIGKILL...\"\n kill -9 $(pgrep -f trino-server) # Send SIGKILL if the process did not terminate\n fi\nfi\n\n# Step 3: Perform cleanup or maintenance tasks (if any)\necho \"Performing cleanup tasks...\"\n\n# Step 4: Start the Trino server again\necho \"Starting Trino server...\"\n# Replace the following command with the actual command to start the Trino server\n# Example: \/path\/to\/trino-server start\n\necho \"Trino server restarted successfully.\"\n```\n\nIn the solution, the Bash script `restart_trino.sh` follows the specified steps to stop, perform maintenance, and start the Trino server. It uses signals to stop the Trino server process, waits for the process to terminate gracefully, performs cleanup tasks, and then starts the Trino server again. The script also includes error handling to ensure the Trino server is stopped and restarted properly."} {"lang":"rust","raw_index":23431,"index":674,"seed":" path.extend_from_slice(b\"\/change_events_count\/\");\n path\n});\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that processes a given path and extracts the count of change events from it. The path is represented as a byte string and follows a specific format. The function should parse the path and return the count of change events.\n\nThe path format is as follows:\n- The path starts with a forward slash (\"\/\").\n- It contains the substring \"\/change_events_count\/\" followed by a number representing the count of change events.\n- The number representing the count of change events is a non-negative integer.\n\nYou need to implement a function `extract_change_events_count` that takes a byte string `path` as input and returns the count of change events as an integer.\n\nFunction signature: \n```rust\nfn extract_change_events_count(path: &[u8]) -> Option {\n \/\/ Your implementation here\n}\n```\n\nExample:\n```rust\nassert_eq!(extract_change_events_count(b\"\/change_events_count\/10\"), Some(10));\nassert_eq!(extract_change_events_count(b\"\/change_events_count\/0\"), Some(0));\nassert_eq!(extract_change_events_count(b\"\/change_events_count\/100\"), Some(100));\nassert_eq!(extract_change_events_count(b\"\/change_events_count\/abc\"), None);\nassert_eq!(extract_change_events_count(b\"\/change_events_count\/-5\"), None);\nassert_eq!(extract_change_events_count(b\"\/change_events_count\/\"), None);\nassert_eq!(extract_change_events_count(b\"\/change_events_count\"), None);\nassert_eq!(extract_change_events_count(b\"\/change_events_count\/10\/extra\"), None);\n```","solution":"```rust\nfn extract_change_events_count(path: &[u8]) -> Option {\n let prefix = b\"\/change_events_count\/\";\n if path.starts_with(prefix) {\n let remaining_path = &path[prefix.len()..];\n if let Ok(count) = std::str::from_utf8(remaining_path).unwrap().parse::() {\n return Some(count);\n }\n }\n None\n}\n```\n\nThe `extract_change_events_count` function first checks if the given `path` starts with the expected prefix \"\/change_events_count\/\". If it does, it extracts the remaining part of the path and attempts to parse it as a valid non-negative integer. If successful, it returns the count of change events as `Some(count)`, otherwise, it returns `None`."} {"lang":"python","raw_index":98447,"index":30646,"seed":" create_pipe.return_value = (mock_tarpipe_out, mock_tarpipe_in)\n image_cmd = vdi_handler.GenerateImageStream(\n self.context, self.session, self.instance,\n self.host_url, ['vdi_uuid'])\n mock_tarpipe_out.read.side_effect = ['chunk1', 'chunk2', '']\n\n image_chunks = []\n for chunk in image_cmd.get_image_data():\n image_chunks.append(chunk)\n\n create_pipe.assert_called_once_with()\n mock_spawn.assert_called_once_with(mock_start, mock_tarpipe_in)\n self.assertEqual(image_chunks, ['chunk1', 'chunk2'])\n\n @mock.patch.object(vdi_handler, 'VdisToTarStream')\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that simulates a data pipeline for processing and transforming chunks of data. The function should take a list of input data chunks and apply a series of transformations to each chunk. The transformations include reading the data from a mock pipe, processing the data, and then returning the processed data chunks.\n\nThe function should adhere to the following specifications:\n- The function should be named `data_pipeline` and should take two parameters: `input_chunks` (a list of input data chunks) and `transformations` (a list of transformation functions).\n- Each transformation function in the `transformations` list should take a single input parameter representing a data chunk and return the transformed data chunk.\n- The `data_pipeline` function should iterate through each input chunk and apply the transformations sequentially to each chunk.\n- The function should return a list of transformed data chunks in the same order as the input chunks.\n\nYou are provided with a code snippet that sets up a mock data pipeline and reads chunks of data from a mock pipe. Use this as inspiration to create the `data_pipeline` function.","solution":"```python\ndef data_pipeline(input_chunks, transformations):\n transformed_chunks = []\n for chunk in input_chunks:\n for transform_func in transformations:\n chunk = transform_func(chunk)\n transformed_chunks.append(chunk)\n return transformed_chunks\n```\n\nExample usage:\n```python\n# Define transformation functions\ndef uppercase_transform(data):\n return data.upper()\n\ndef reverse_transform(data):\n return data[::-1]\n\n# Input data chunks\ninput_data = ['hello', 'world', 'python']\n\n# Define transformations\ntransforms = [uppercase_transform, reverse_transform]\n\n# Apply data pipeline\nresult = data_pipeline(input_data, transforms)\nprint(result)\n# Output: ['OLLEH', 'DLROW', 'NOHTYP']\n```"} {"lang":"python","raw_index":144561,"index":4361,"seed":"\n #extract message\n jmsg = body.decode(\"utf8\")\n msg = json.loads(jmsg)\n meter_id = msg['id']\n\n try:\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that processes incoming messages from IoT devices. The function should extract the message, parse it as JSON, and then retrieve the meter ID from the message. Additionally, the function should handle potential exceptions that may occur during this process.\n\nWrite a Python function `process_iot_message` that takes in a `body` parameter, which is a byte string representing the incoming message. The function should perform the following tasks:\n1. Decode the byte string `body` using UTF-8 encoding to obtain the JSON message.\n2. Parse the JSON message to extract the meter ID.\n3. Return the extracted meter ID as a string.\n\nIf any exceptions occur during the decoding, JSON parsing, or extraction of the meter ID, the function should catch and handle these exceptions. Specifically, the function should handle `UnicodeDecodeError` and `json.JSONDecodeError` by returning the string \"Error: Invalid message format\". If the meter ID cannot be extracted from the message, the function should return \"Error: Missing meter ID\".\n\nYour task is to implement the `process_iot_message` function according to the given requirements.","solution":"```python\nimport json\n\ndef process_iot_message(body):\n try:\n # Decode the byte string using UTF-8 encoding to obtain the JSON message\n jmsg = body.decode(\"utf8\")\n # Parse the JSON message to extract the meter ID\n msg = json.loads(jmsg)\n meter_id = msg['id']\n return str(meter_id)\n except UnicodeDecodeError:\n return \"Error: Invalid message format\"\n except json.JSONDecodeError:\n return \"Error: Invalid message format\"\n except KeyError:\n return \"Error: Missing meter ID\"\n```\nThe `process_iot_message` function first attempts to decode the byte string using UTF-8 encoding and then parse the JSON message to extract the meter ID. If any exceptions occur during these operations, the function catches and handles them by returning the appropriate error messages. If the meter ID cannot be extracted from the message, the function returns \"Error: Missing meter ID\"."} {"lang":"shell","raw_index":50306,"index":1179,"seed":"#\n\n#\n# Simple, file based tests for copyright script\n# script return non-zero error code if something went wrong.\n# diff output is printed\n#\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simple file-based testing framework for a copyright script. The copyright script is expected to return a non-zero error code if something goes wrong, and the diff output is printed in case of any discrepancies.\n\nYour task is to write a Python function that performs the file-based tests for the copyright script. The function should take two file paths as input: the expected output file and the actual output file. It should compare the contents of these files and return a boolean value indicating whether the files match or not.\n\nWrite a function called `perform_file_based_test` that takes two parameters:\n1. `expected_output_file_path` (string) - the file path to the expected output file.\n2. `actual_output_file_path` (string) - the file path to the actual output file.\n\nThe function should compare the contents of the expected and actual output files. If the contents match exactly, the function should return `True`; otherwise, it should return `False`.\n\nAssume that the contents of the files are plain text.\n\nExample:\nIf the expected output file contains:\n```\nCopyright (c) 2022. All rights reserved.\n```\nand the actual output file contains:\n```\nCopyright (c) 2022. All rights reserved.\n```\nthen the function should return `True`.\n\nIf the expected output file contains:\n```\nCopyright (c) 2022. All rights reserved.\n```\nand the actual output file contains:\n```\nCopyright (c) 2021. All rights reserved.\n```\nthen the function should return `False`.","solution":"```python\ndef perform_file_based_test(expected_output_file_path, actual_output_file_path):\n with open(expected_output_file_path, 'r') as expected_file:\n expected_content = expected_file.read()\n with open(actual_output_file_path, 'r') as actual_file:\n actual_content = actual_file.read()\n \n return expected_content == actual_content\n```\n\nThe `perform_file_based_test` function opens the expected and actual output files, reads their contents, and then compares the contents. If the contents match exactly, it returns `True`; otherwise, it returns `False`. This solution assumes that the files contain plain text and performs a simple string comparison to determine if the files match."} {"lang":"cpp","raw_index":92957,"index":2079,"seed":"\n\n\n\/\/\/ Block until timeout or if there is new data to be received.\nHarpoon::Battling Harpoon::Heave(std::vector& data) {\n \/\/Erase any previous data from the last Monitor()\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class that simulates a data monitoring system. The class, `Harpoon`, has a method `Heave` which blocks until a timeout or new data is received. Your task is to implement the `Heave` method to handle the data monitoring logic.\n\nThe `Heave` method takes a reference to a `std::vector` as a parameter, representing the data to be received. The method should block until either a timeout occurs or new data is received. If new data is received, it should be stored in the `data` vector. If a timeout occurs, the method should return a `Battling` object.\n\nYou need to implement the `Heave` method to fulfill the following requirements:\n1. Block until either a timeout occurs or new data is received.\n2. If new data is received, store it in the `data` vector.\n3. If a timeout occurs, return a `Battling` object.\n\nYou can assume that the `Harpoon` class and the `Battling` class have been properly defined and accessible.\n\nYour task is to implement the `Heave` method to meet the specified requirements.","solution":"```cpp\n#include \n#include \n#include \n#include \n\nclass Battling {\n \/\/ Define Battling class members\n};\n\nclass Harpoon {\npublic:\n \/\/ Implement the Heave method\n Battling Heave(std::vector& data) {\n \/\/ Simulate a timeout duration of 5 seconds\n std::chrono::seconds timeoutDuration(5);\n\n \/\/ Simulate monitoring for new data\n bool newDataReceived = false; \/\/ Replace with actual logic to monitor for new data\n\n \/\/ Simulate blocking until timeout or new data received\n auto start = std::chrono::steady_clock::now();\n while (!newDataReceived) {\n auto now = std::chrono::steady_clock::now();\n if (now - start >= timeoutDuration) {\n return Battling(); \/\/ Return a Battling object on timeout\n }\n \/\/ Replace this condition with actual logic to check for new data\n if (\/* Condition to check for new data *\/) {\n \/\/ Simulate receiving new data\n data.push_back( \/* New data received *\/ ); \/\/ Store new data in the data vector\n newDataReceived = true;\n }\n \/\/ Simulate a short delay before checking again\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n }\n \/\/ Return a default-constructed Battling object if new data is received\n return Battling();\n }\n};\n```\n\nIn the solution, the `Heave` method is implemented to simulate blocking until a timeout or new data is received. It uses a simulated timeout duration of 5 seconds and checks for new data in a loop. If a timeout occurs, it returns a default-constructed `Battling` object. If new data is received, it stores the data in the `data` vector and returns a default-constructed `Battling` object. This solution demonstrates the logic for monitoring and handling new data or timeouts within the `Heave` method."} {"lang":"python","raw_index":78552,"index":14798,"seed":"\n return -- the final fitness.\n \"\"\"\n solution_rot = np.roll(solution, -1)\n return np.sum([cost[pair] for pair in zip(solution, solution_rot)])\n\n\ndef fitness(solution, cost):\n \"\"\"\n Return the fitness evaluation. It is the quicker implementation.\n\n Time for 1000 cities: 1.5ms\n\n Parameters\n ----------\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function to calculate the fitness evaluation for a given solution to the traveling salesman problem. The traveling salesman problem involves finding the shortest possible route that visits each city exactly once and returns to the original city. The fitness evaluation is based on the total cost of the solution, where the cost represents the distance or some other metric associated with traveling between cities.\n\nYou are given a Python function `fitness(solution, cost)` that takes in a solution (represented as a list of cities) and a dictionary of costs for traveling between pairs of cities. The function calculates the fitness evaluation by summing the costs of traveling between adjacent cities in the solution.\n\nYour task is to implement the `fitness` function to efficiently calculate the fitness evaluation for the given solution based on the provided cost dictionary.\n\nFor example, given a solution `[1, 2, 3, 4]` and a cost dictionary `{(1, 2): 10, (2, 3): 15, (3, 4): 12, (4, 1): 8}`, the fitness evaluation would be `10 + 15 + 12 + 8 = 45`.\n\nYou should assume that the cost dictionary contains entries for all pairs of cities in the solution.\n\nWrite a Python function `fitness(solution, cost)` that efficiently calculates the fitness evaluation for the given solution based on the provided cost dictionary.","solution":"```python\ndef fitness(solution, cost):\n \"\"\"\n Return the fitness evaluation based on the given solution and cost dictionary.\n\n Parameters\n ----------\n solution : list\n A list representing the solution, where each element is a city.\n cost : dict\n A dictionary containing the costs for traveling between pairs of cities.\n\n Returns\n -------\n int\n The fitness evaluation based on the total cost of the solution.\n\n \"\"\"\n # Initialize the total cost to 0\n total_cost = 0\n \n # Iterate through the solution and calculate the total cost\n for i in range(len(solution) - 1):\n # Get the current city and the next city in the solution\n current_city = solution[i]\n next_city = solution[i + 1]\n \n # Add the cost of traveling from the current city to the next city to the total cost\n total_cost += cost[(current_city, next_city)]\n \n # Add the cost of traveling from the last city back to the first city\n total_cost += cost[(solution[-1], solution[0])]\n \n return total_cost\n```\n\nThe provided solution defines the `fitness` function, which efficiently calculates the fitness evaluation for the given solution based on the provided cost dictionary. It iterates through the solution, retrieving the cost of traveling between adjacent cities from the cost dictionary and summing these costs to obtain the total fitness evaluation. Finally, it adds the cost of traveling from the last city back to the first city to complete the evaluation."} {"lang":"python","raw_index":141511,"index":12152,"seed":" k : integer\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a code snippet that declares a variable `k` of type integer. Your task is to write a program that takes an integer input `n` and calculates the sum of all multiples of `k` that are less than `n`.\n\nFor example, if `k` is 3 and `n` is 10, the multiples of 3 less than 10 are 3, 6, and 9, and their sum is 18.\n\nWrite a program that takes `k` and `n` as input and outputs the sum of all multiples of `k` less than `n`.","solution":"```python\ndef sum_of_multiples(k, n):\n # Initialize the sum\n total_sum = 0\n \n # Iterate through numbers less than n\n for i in range(k, n, k):\n total_sum += i\n \n return total_sum\n\n# Example usage\nk = 3\nn = 10\nresult = sum_of_multiples(k, n)\nprint(result) # Output: 18\n```"} {"lang":"cpp","raw_index":137399,"index":2638,"seed":" .TypeConstraint(\"T\") \\\n .TypeConstraint(\"out_idx\"), \\\n UniqueAliOp)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a generic function that performs a unique operation on a given type. The function should enforce type constraints and ensure that the output index is of type int64. Your task is to complete the implementation of the UniqueAliOp function by adding the necessary code to enforce the type constraints and ensure the correct output index type.\n\nThe function UniqueAliOp has the following signature:\n```cpp\ntemplate \nint64 UniqueAliOp(int64 out_idx);\n```\n\nYour task is to complete the implementation of UniqueAliOp by adding the necessary code to enforce the type constraints for the input type T and ensure that the output index is of type int64. You should use the TypeConstraint function to enforce the type constraint for the input type T and ensure that the output index is of type int64.\n\nYour implementation should ensure that the function can be called with different types and output indices, and it should enforce the type constraints at compile time.\n\nComplete the UniqueAliOp function to enforce the type constraints and ensure the correct output index type.","solution":"```cpp\ntemplate \nint64 UniqueAliOp(int64 out_idx) {\n static_assert(std::is_same::value, \"T must be of type 'type'\");\n static_assert(std::is_same::value, \"out_idx must be of type 'int64'\");\n \n \/\/ Rest of the function implementation goes here\n \n return out_idx;\n}\n```\n\nIn the solution, the static_assert statements are used to enforce the type constraints at compile time. The first static_assert ensures that the input type T is of type 'type', and the second static_assert ensures that the output index is of type int64. This ensures that the type constraints are enforced at compile time, and any violation will result in a compilation error. The rest of the function implementation can then proceed with the assurance that the type constraints have been satisfied."} {"lang":"typescript","raw_index":127809,"index":2404,"seed":"\n\n\n\n console.log('to miniProgram...' + type);\n\n switch (parseInt(type)) {\n case 1:\n WxMiniGameApi.imgSecCheck('\/Users\/Javen\/Documents\/pic\/test.jpeg')\n .then((data) => {\n res.send(data);\n }).catch((error) => console.log(error))\n break;\n case 2:\n WxMiniGameApi.mediaCheckAsync('\/Users\/Javen\/Documents\/pic\/test.jpeg', WxMiniGameMediaType.IMG)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a function that simulates a content moderation system for a mini-program platform. The function should take in two parameters: `type` (an integer representing the type of content) and `filePath` (a string representing the file path of the content to be checked). The function should then perform content moderation based on the given type and file path, and return the result of the moderation process.\n\nThe content moderation system supports two types of content checks:\n1. Image content check: If the `type` is 1, the function should use the `WxMiniGameApi.imgSecCheck` method to perform an image content check on the file located at the specified `filePath`. The result of the check should be returned.\n2. Media content check: If the `type` is 2, the function should use the `WxMiniGameApi.mediaCheckAsync` method to perform a media content check on the file located at the specified `filePath`. The result of the check should be returned.\n\nYour task is to implement the `contentModeration` function that takes in `type` and `filePath` as parameters and performs the appropriate content check based on the given type, returning the result of the moderation process.\n\n```javascript\nfunction contentModeration(type, filePath) {\n \/\/ Your implementation here\n}\n```","solution":"```javascript\nfunction contentModeration(type, filePath) {\n return new Promise((resolve, reject) => {\n switch (parseInt(type)) {\n case 1:\n WxMiniGameApi.imgSecCheck(filePath)\n .then((data) => {\n resolve(data);\n }).catch((error) => reject(error));\n break;\n case 2:\n WxMiniGameApi.mediaCheckAsync(filePath, WxMiniGameMediaType.IMG)\n .then((data) => {\n resolve(data);\n }).catch((error) => reject(error));\n break;\n default:\n reject(\"Invalid content type\");\n }\n });\n}\n```\n\nIn the solution, the `contentModeration` function takes in the `type` and `filePath` parameters and uses a `switch` statement to determine the type of content check to perform. For type 1, it uses the `WxMiniGameApi.imgSecCheck` method to perform an image content check, and for type 2, it uses the `WxMiniGameApi.mediaCheckAsync` method to perform a media content check. The function returns a `Promise` that resolves with the result of the content check or rejects with an error message if the content type is invalid or if an error occurs during the content check."} {"lang":"java","raw_index":89596,"index":1722,"seed":" * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage ro.lmn.maven.dmn.impl;\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program that analyzes the distribution of package licenses in a Maven project. Maven is a popular build automation tool used primarily for Java projects. Maven projects typically contain a `pom.xml` file, which specifies project information and configuration details, including dependencies and their associated licenses.\n\nYour task is to write a function that takes the content of a `pom.xml` file as input and returns a summary of the licenses used in the project. The function should parse the XML content and extract information about the licenses of the project's dependencies.\n\nThe `pom.xml` file follows the standard XML structure and contains `` and `` tags, each specifying a dependency used in the project. Each `` tag may contain a `` tag, which specifies the license of the dependency. The license information may be in various formats, such as a URL, a license name, or a license identifier.\n\nYour function should return a summary of the licenses used in the project, including the count of each unique license and the list of dependencies associated with each license.\n\nWrite a function with the following signature:\n```java\npublic Map>> analyzePackageLicenses(String pomXmlContent) {\n \/\/ Your implementation here\n}\n```\n\nFor example, given the following `pom.xml` content:\n```xml\n\n \n \n org.springframework<\/groupId>\n spring-core<\/artifactId>\n 5.2.8.RELEASE<\/version>\n Apache License, Version 2.0<\/license>\n <\/dependency>\n \n junit<\/groupId>\n junit<\/artifactId>\n 4.12<\/version>\n Eclipse Public License - v 1.0<\/license>\n <\/dependency>\n \n com.google.guava<\/groupId>\n guava<\/artifactId>\n 29.0-jre<\/version>\n Apache-2.0<\/license>\n <\/dependency>\n \n org.apache.commons<\/groupId>\n commons-lang3<\/artifactId>\n 3.11<\/version>\n <\/dependency>\n <\/dependencies>\n<\/project>\n```\n\nThe function should return a map with the following structure:\n```java\n{\n \"Apache License, Version 2.0\": {\n \"org.springframework:spring-core:5.2.8.RELEASE\"\n },\n \"Eclipse Public License - v 1.0\": {\n \"junit:junit:4.12\"\n },\n \"Apache-2.0\": {\n \"com.google.guava:guava:29.0-jre\"\n },\n \"Unknown\": {\n \"org.apache.commons:commons-lang3:3.11\"\n }\n}\n```\nThe keys of the outer map represent the unique licenses found in the project, and the values are inner maps. The keys of the inner maps represent the dependencies associated with the corresponding license, and the values are lists of dependency identifiers in the format `groupId:artifactId:version`.","solution":"```java\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NodeList;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport java.io.StringReader;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class PackageLicenseAnalyzer {\n\n public Map>> analyzePackageLicenses(String pomXmlContent) {\n Map>> licenseSummary = new HashMap<>();\n\n try {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n DocumentBuilder builder = factory.newDocumentBuilder();\n Document document = builder.parse(new InputSource(new StringReader(pomXmlContent)));\n\n NodeList dependencyNodes = document.getElementsByTagName(\"dependency\");\n for (int i = 0; i < dependencyNodes.getLength(); i++) {\n Element dependencyElement = (Element) dependencyNodes.item(i);\n String groupId = dependencyElement.getElementsByTagName(\"groupId\").item(0).getTextContent();\n String artifactId = dependencyElement.getElementsByTagName(\"artifactId\").item(0).getTextContent();\n String version = dependencyElement.getElementsByTagName(\"version\").item(0).getTextContent();\n String license = \"Unknown\";\n if (dependencyElement.getElementsByTagName(\"license\").getLength() > 0) {\n license = dependencyElement.getElementsByTagName(\"license\").item(0).getTextContent();\n }\n\n licenseSummary.computeIfAbsent(license, k -> new HashMap<>())\n .computeIfAbsent(groupId + \":\" + artifactId + \":\" + version, k -> List.of())\n .add(groupId + \":\" + artifactId + \":\" + version);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return licenseSummary;\n }\n\n public static void main(String[] args) {\n String pomXmlContent = \"\\n\" +\n \" \\n\" +\n \" \\n\" +\n \" org.springframework<\/groupId>\\n\" +\n \" spring-core<\/artifactId>\\n\" +\n \" 5.2.8.RELEASE<\/version>\\n\" +\n \" Apache License, Version 2.0<\/license>\\n\" +\n \" <\/dependency>\\n\" +\n \" \\n\" +\n \" junit<\/groupId>\\n\" +\n \" junit<\/artifactId>\\n\" +\n \" 4.12<\/version>\\n\" +\n \" Eclipse Public License - v 1.0<\/license>\\n\" +\n \" <\/dependency>\\n\" +\n \" \\n\" +\n \" com.google.guava<\/groupId>\\n\" +\n \" guava<\/artifactId>\\n\" +\n \" 29.0-jre<\/version>\\n\" +\n \" Apache-2.0<\/license>\\n\" +\n \" <\/dependency>\\n\" +\n \" \\n\" +\n \" org.apache.commons<\/groupId>\\n\" +\n \" commons-lang3<\/artifactId>\\n\" +\n \" 3.11<\/version>\\n\" +\n \" <\/dependency>\\n\" +\n \" <\/dependencies>\\n\" +\n \"<\/project>\";\n\n PackageLicenseAnalyzer analyzer = new PackageLicenseAnalyzer();\n Map>> result = analyzer.analyzePackageLicenses(pomXmlContent);\n result.forEach((license, dependencies) -> {\n System.out.println(license + \":\");\n dependencies.forEach((dependency, versions) -> {\n System.out.println(\"\\t\" + dependency + \" - \" + versions.stream().collect(Collectors.joining(\", \")));\n });\n });\n }\n}\n```"} {"lang":"python","raw_index":73612,"index":33728,"seed":"\n def test_task_setter(self):\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python class that manages tasks for a project. The class should have methods to add, remove, and retrieve tasks, as well as mark tasks as completed. Additionally, the class should be able to return the number of incomplete tasks and the percentage of completed tasks.\n\nCreate a class `TaskManager` with the following methods:\n- `__init__(self)`: Initializes an empty list to store tasks.\n- `add_task(self, task_description)`: Adds a new task with the given description to the list.\n- `remove_task(self, task_description)`: Removes the task with the given description from the list.\n- `get_tasks(self)`: Returns a list of all tasks.\n- `complete_task(self, task_description)`: Marks the task with the given description as completed.\n- `incomplete_tasks_count(self)`: Returns the number of incomplete tasks.\n- `completed_tasks_percentage(self)`: Returns the percentage of completed tasks as a float value.\n\nYour task is to implement the `TaskManager` class with the specified methods.","solution":"```python\nclass TaskManager:\n def __init__(self):\n self.tasks = []\n\n def add_task(self, task_description):\n self.tasks.append({\"description\": task_description, \"completed\": False})\n\n def remove_task(self, task_description):\n for task in self.tasks:\n if task[\"description\"] == task_description:\n self.tasks.remove(task)\n break\n\n def get_tasks(self):\n return [task[\"description\"] for task in self.tasks]\n\n def complete_task(self, task_description):\n for task in self.tasks:\n if task[\"description\"] == task_description:\n task[\"completed\"] = True\n break\n\n def incomplete_tasks_count(self):\n return sum(1 for task in self.tasks if not task[\"completed\"])\n\n def completed_tasks_percentage(self):\n if not self.tasks:\n return 0.0\n completed_count = sum(1 for task in self.tasks if task[\"completed\"])\n return (completed_count \/ len(self.tasks)) * 100\n```"} {"lang":"php","raw_index":59324,"index":4992,"seed":" <\/div>\n
\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that will parse a given HTML string and extract all the class names from the `div` elements. The function should return a list of unique class names found in the HTML string.\n\nYou are given the following code snippet as an example of the HTML structure:\n```html\n
\n```\n\nWrite a function `extractClassNames(html)` that takes a string `html` representing the HTML content and returns a list of unique class names found within the `div` elements.\n\nFunction signature: `def extractClassNames(html: str) -> List[str]`\n\nExample:\n```python\nhtml = '''\n
\n
\n
\n
\n'''\nprint(extractClassNames(html)) # Output: ['form-group', 'input-group']\n```","solution":"```python\nfrom bs4 import BeautifulSoup\n\ndef extractClassNames(html: str) -> List[str]:\n class_names = set()\n soup = BeautifulSoup(html, 'html.parser')\n div_elements = soup.find_all('div')\n for div in div_elements:\n classes = div.get('class')\n if classes:\n class_names.update(classes)\n return list(class_names)\n```"} {"lang":"typescript","raw_index":148037,"index":1748,"seed":" )}\n <\/Paper>\n <\/div>\n );\n};\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that will parse a given JSX (JavaScript XML) code and count the number of closing tags for a specific HTML element. JSX is a syntax extension for JavaScript often used with React for defining the structure of UI components. The function should take two parameters: the JSX code as a string and the HTML element tag to count. The function should return the total count of closing tags for the specified HTML element within the JSX code.\n\nFor example, given the following JSX code snippet:\n```jsx\nconst jsxCode = `\n
\n

Hello<\/p>\n

World<\/p>\n <\/div>\n );\n};\n```\nIf the specified HTML element tag is \"p\", the function should return 2, as there are two closing tags for the \"p\" element.\n\nWrite a function `countClosingTags` that takes the following parameters:\n- `jsxCode` (string): A string representing the JSX code.\n- `elementTag` (string): The HTML element tag for which the closing tags need to be counted.\n\nThe function should return the count of closing tags for the specified HTML element within the given JSX code.","solution":"```javascript\nfunction countClosingTags(jsxCode, elementTag) {\n const regex = new RegExp(`<${elementTag}\\\\s*\\\\\/?>`, 'g');\n const openingTags = jsxCode.match(regex);\n if (openingTags) {\n return openingTags.length;\n } else {\n return 0;\n }\n}\n\n\/\/ Example usage\nconst jsxCode = `\n

\n

Hello<\/p>\n

World<\/p>\n <\/div>\n );\n};\nconst elementTag = \"p\";\nconsole.log(countClosingTags(jsxCode, elementTag)); \/\/ Output: 2\n```"} {"lang":"rust","raw_index":12819,"index":2427,"seed":" tags: Vec::from(tags),\n notify,\n cookie: cookie.to_string(),\n };\n\n let tags = Self::build_notify_tags(&self.tags, &subscr.tags);\n let msg = Message {\n message: MessageVariant::NotifySubscribeTag(tags.into()),\n client_cookie: subscr.cookie.clone(),\n };\n self.subscriptions.insert(cookie.into(), subscr);\n\n msg\n }\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function to process subscription notifications in a messaging system. The function takes in a set of tags, a notification flag, and a client cookie, and returns a message to be sent to the client. The function also updates a subscription map with the new subscription information.\n\nYou are given the following code snippet as a starting point:\n\n```rust\ntags: Vec::from(tags),\nnotify,\ncookie: cookie.to_string(),\n};\n\nlet tags = Self::build_notify_tags(&self.tags, &subscr.tags);\nlet msg = Message {\n message: MessageVariant::NotifySubscribeTag(tags.into()),\n client_cookie: subscr.cookie.clone(),\n};\nself.subscriptions.insert(cookie.into(), subscr);\n\nmsg\n```\n\nYour task is to implement the `process_subscription_notification` function that takes in the following parameters:\n- `tags`: A vector of strings representing the tags to be subscribed to.\n- `notify`: A boolean flag indicating whether to send notifications for the subscription.\n- `cookie`: A string representing the client's cookie.\n\nThe function should perform the following steps:\n1. Create a new subscription with the provided `tags`, `notify`, and `cookie`.\n2. Build the notification tags using the `build_notify_tags` method, which takes the system's tags and the subscription's tags as input.\n3. Create a message of type `MessageVariant::NotifySubscribeTag` with the built notification tags and the client's cookie.\n4. Insert the new subscription into the `subscriptions` map using the `cookie` as the key.\n\nThe function should then return the created message.\n\nYour task is to complete the implementation of the `process_subscription_notification` function based on the given requirements and code snippet.","solution":"```rust\nfn process_subscription_notification(tags: Vec, notify: bool, cookie: &str) -> Message {\n let subscr = Subscription {\n tags: Vec::from(tags),\n notify,\n cookie: cookie.to_string(),\n };\n\n let tags = Self::build_notify_tags(&self.tags, &subscr.tags);\n let msg = Message {\n message: MessageVariant::NotifySubscribeTag(tags.into()),\n client_cookie: subscr.cookie.clone(),\n };\n self.subscriptions.insert(cookie.into(), subscr);\n\n msg\n}\n```"} {"lang":"python","raw_index":33710,"index":35476,"seed":" if not related_source_fields:\n return\n\n html_pieces = []\n for source_field in related_source_fields:\n field = source_field.get_field(obj.__class__)\n field_value = source_field.get_value(obj)\n if isinstance(field, StreamField):\n field_value = ' '.join(field_value)\n\n html_pieces.append(field_value)\n\n text = ' '.join(html_pieces)\n\n text = BeautifulSoup(text, 'html5lib').text\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that processes a list of source fields to generate a clean text output. The function should handle different types of fields and their values, including StreamField, and produce a sanitized text result.\n\nWrite a Python function `process_source_fields` that takes in two parameters:\n1. `related_source_fields` (list): A list of source fields to be processed.\n2. `obj` (object): An object representing the context for the source fields.\n\nThe function should iterate through the `related_source_fields` list and extract the field values based on the object's class. If a field is of type StreamField, the function should concatenate its values into a single string. Then, the function should join all the extracted values into a single text string and use BeautifulSoup to sanitize the HTML content, resulting in a clean text output.\n\nYour task is to implement the `process_source_fields` function according to the given specifications.","solution":"```python\nfrom bs4 import BeautifulSoup\nfrom wagtail.core.fields import StreamField\n\ndef process_source_fields(related_source_fields, obj):\n if not related_source_fields:\n return\n\n html_pieces = []\n for source_field in related_source_fields:\n field = source_field.get_field(obj.__class__)\n field_value = source_field.get_value(obj)\n if isinstance(field, StreamField):\n field_value = ' '.join(field_value)\n\n html_pieces.append(field_value)\n\n text = ' '.join(html_pieces)\n text = BeautifulSoup(text, 'html5lib').text\n\n return text\n```\n\nThe `process_source_fields` function first checks if the `related_source_fields` list is not empty. It then iterates through the fields, extracting their values based on the object's class. If a field is of type StreamField, its values are concatenated into a single string. Finally, the function joins all the extracted values into a single text string and uses BeautifulSoup to sanitize the HTML content, returning the clean text output."} {"lang":"rust","raw_index":15960,"index":42,"seed":" }\n\n pub fn eval_expression(&mut self, expression: Expression) -> Object {\n eval_expression(expression, &self.env)\n }\n}\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simple expression evaluator in Rust. The expression evaluator should be able to handle basic arithmetic operations and variable references.\n\nYou are given a partial implementation of a `Evaluator` struct and its associated method `eval_expression`. The `eval_expression` method takes an `Expression` as input and returns an `Object` as output. The `Expression` type and `Object` type are not explicitly defined in the provided code snippet, but you can assume that they represent the input expression and the result of the evaluation, respectively.\n\nYour task is to complete the implementation of the `eval_expression` method and define the `Expression` and `Object` types to support the following operations:\n1. Addition (+)\n2. Subtraction (-)\n3. Multiplication (*)\n4. Division (\/)\n5. Variable reference (e.g., \"x\")\n\nThe `Expression` type should be able to represent a combination of these operations and variable references, and the `Object` type should represent the result of the evaluation.\n\nYour implementation should handle both binary operations (e.g., \"2 + 3\") and variable references (e.g., \"x * 5\").\n\nComplete the implementation of the `eval_expression` method and define the `Expression` and `Object` types to achieve the desired functionality.","solution":"```rust\n\/\/ Define the Expression and Object types\n#[derive(Debug)]\nenum Expression {\n Number(i32),\n Variable(String),\n BinaryOperation(Box, Operator, Box),\n}\n\n#[derive(Debug)]\nenum Object {\n Number(i32),\n}\n\n#[derive(Debug)]\nenum Operator {\n Add,\n Subtract,\n Multiply,\n Divide,\n}\n\n\/\/ Implement the eval_expression method\nimpl Evaluator {\n pub fn eval_expression(&mut self, expression: Expression) -> Object {\n match expression {\n Expression::Number(num) => Object::Number(num),\n Expression::Variable(var) => {\n \/\/ Implement variable lookup logic here\n \/\/ For example, look up the value of the variable in the environment\n \/\/ and return the corresponding Object\n \/\/ Assuming self.env is a HashMap\n Object::Number(*self.env.get(&var).unwrap_or(&0))\n }\n Expression::BinaryOperation(left, op, right) => {\n let left_val = self.eval_expression(*left);\n let right_val = self.eval_expression(*right);\n match (left_val, op, right_val) {\n (Object::Number(l), Operator::Add, Object::Number(r)) => Object::Number(l + r),\n (Object::Number(l), Operator::Subtract, Object::Number(r)) => Object::Number(l - r),\n (Object::Number(l), Operator::Multiply, Object::Number(r)) => Object::Number(l * r),\n (Object::Number(l), Operator::Divide, Object::Number(r)) => {\n if r != 0 {\n Object::Number(l \/ r)\n } else {\n \/\/ Handle division by zero error\n panic!(\"Division by zero error\");\n }\n }\n _ => {\n \/\/ Handle unsupported operations or invalid expressions\n panic!(\"Unsupported operation or invalid expression\");\n }\n }\n }\n }\n }\n}\n```\n\nThis solution completes the implementation of the `eval_expression` method and defines the `Expression` and `Object` types to support basic arithmetic operations and variable references. The `eval_expression` method recursively evaluates the input expression and returns the corresponding result as an `Object`. The defined types and method enable the expression evaluator to handle various combinations of operations and variable references."} {"lang":"python","raw_index":4159,"index":32247,"seed":"\n \"\"\"\n return {}\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python function that takes a list of integers as input and returns a dictionary containing the count of each unique integer in the input list.\n\nThe function signature is:\n```python\ndef count_unique_integers(arr: List[int]) -> Dict[int, int]:\n pass\n```\n\nYour task is to complete the implementation of the `count_unique_integers` function to achieve the desired functionality. The function should return a dictionary where the keys are unique integers from the input list and the values are the count of each unique integer in the input list.\n\nFor example, given the input list `[1, 2, 2, 3, 3, 3]`, the function should return the dictionary `{1: 1, 2: 2, 3: 3}`.","solution":"```python\nfrom typing import List, Dict\n\ndef count_unique_integers(arr: List[int]) -> Dict[int, int]:\n unique_counts = {}\n for num in arr:\n if num in unique_counts:\n unique_counts[num] += 1\n else:\n unique_counts[num] = 1\n return unique_counts\n```\n\nThe `count_unique_integers` function iterates through the input list and maintains a dictionary `unique_counts` to store the count of each unique integer. For each integer in the input list, it checks if the integer is already a key in the dictionary. If it is, the count for that integer is incremented; otherwise, a new key is added with a count of 1. Finally, the function returns the populated `unique_counts` dictionary."} {"lang":"python","raw_index":45736,"index":6061,"seed":" size = int(os.stat(filepath).st_size)\n percent_complete = (size \/ filesize) * 100\n sys.stdout.write('%.3f %s' % (percent_complete, '% Completed'))\n sys.stdout.flush()\n\n\n# Try to get password\nif len(sys.argv) < 2 and not 'RDAPSWD' in os.environ:\n try:\n import getpass\n\n input = getpass.getpass\n except:\n try:\n input = raw_input\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python script that monitors the progress of a file transfer and prompts the user for a password if it is not provided as a command-line argument or environment variable.\n\nYour script should accomplish the following:\n1. Calculate the percentage completion of a file transfer based on the size of the file being transferred and the current size of the file.\n2. Display the percentage completion to the user in the format \"X.XXX % Completed\" where X.XXX represents the percentage complete with three decimal places.\n3. If the script is not provided with a password as a command-line argument and the environment variable \"RDAPSWD\" is not set, it should prompt the user to enter a password using the `getpass` module. If `getpass` is not available, it should fall back to using `raw_input`.\n\nYour task is to complete the Python script by implementing the file transfer progress monitoring and password prompt functionality.","solution":"```python\nimport os\nimport sys\nimport getpass\n\ndef monitor_file_transfer(filepath, filesize):\n size = os.stat(filepath).st_size\n percent_complete = (size \/ filesize) * 100\n sys.stdout.write('%.3f %s' % (percent_complete, '% Completed'))\n sys.stdout.flush()\n\ndef get_password():\n if len(sys.argv) < 2 and 'RDAPSWD' not in os.environ:\n try:\n input_func = getpass.getpass\n except ImportError:\n input_func = raw_input\n password = input_func(\"Enter password: \")\n return password\n else:\n return sys.argv[1] if len(sys.argv) >= 2 else os.environ.get('RDAPSWD')\n\n# Example usage\nfile_path = \"example_file.txt\"\nfile_size = 1000 # Size of the file being transferred\nmonitor_file_transfer(file_path, file_size)\npassword = get_password()\nprint(\"Password entered:\", password)\n```\n\nIn the solution, the `monitor_file_transfer` function calculates the percentage completion of the file transfer and displays it to the user. The `get_password` function checks if a password is provided as a command-line argument or environment variable. If not, it prompts the user to enter a password using `getpass` or `raw_input` based on availability. Finally, it demonstrates the usage of these functions by monitoring the file transfer progress and obtaining the password."} {"lang":"python","raw_index":87454,"index":22236,"seed":" number = str(number)\n for digit in number:\n digits.append(int(digit))\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a function that takes an integer `number` as input. The function converts the integer into a string and then iterates through each digit of the string, converting it back to an integer and appending it to a list called `digits`. However, the code snippet provided is incomplete and lacks the necessary function structure. Your task is to complete the function and ensure that it correctly converts the input integer into a list of its individual digits.\n\nComplete the function `convert_to_digits` that takes an integer `number` as input and returns a list containing its individual digits.\n\nFunction Signature: `def convert_to_digits(number: int) -> List[int]:`\n\nExample:\nInput:\nconvert_to_digits(12345)\nOutput:\n[1, 2, 3, 4, 5]\n\nInput:\nconvert_to_digits(987654321)\nOutput:\n[9, 8, 7, 6, 5, 4, 3, 2, 1]","solution":"```python\nfrom typing import List\n\ndef convert_to_digits(number: int) -> List[int]:\n number_str = str(number)\n digits = [int(digit) for digit in number_str]\n return digits\n\n# Test cases\nprint(convert_to_digits(12345)) # Output: [1, 2, 3, 4, 5]\nprint(convert_to_digits(987654321)) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]\n```"} {"lang":"swift","raw_index":5836,"index":100,"seed":"\nimport Foundation\n\nenum APIConstants {\n static let baseURL = \"https:\/\/animechan.vercel.app\"\n}\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Swift application that interacts with an anime quote API. The API base URL is provided as a constant in the `APIConstants` enum. Your goal is to implement a function that fetches a random anime quote from the API and prints it to the console.\n\nYou need to create a function named `fetchRandomAnimeQuote` that makes a GET request to the API endpoint `https:\/\/animechan.vercel.app\/api\/random` and then prints the received quote to the console. The function should handle any potential errors that may occur during the network request.\n\nThe `APIConstants` enum is provided with a static constant `baseURL` that holds the base URL for the API.\n\nYour task is to implement the `fetchRandomAnimeQuote` function using Swift's `URLSession` to make the network request and handle the response.","solution":"```swift\nimport Foundation\n\nenum APIConstants {\n static let baseURL = \"https:\/\/animechan.vercel.app\"\n}\n\nfunc fetchRandomAnimeQuote() {\n guard let url = URL(string: \"\\(APIConstants.baseURL)\/api\/random\") else {\n print(\"Invalid URL\")\n return\n }\n\n let task = URLSession.shared.dataTask(with: url) { data, response, error in\n if let error = error {\n print(\"Error: \\(error.localizedDescription)\")\n return\n }\n\n guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {\n print(\"Invalid response\")\n return\n }\n\n if let data = data, let quote = try? JSONDecoder().decode(Quote.self, from: data) {\n print(\"Anime: \\(quote.anime)\")\n print(\"Character: \\(quote.character)\")\n print(\"Quote: \\(quote.quote)\")\n } else {\n print(\"Failed to decode quote\")\n }\n }\n\n task.resume()\n}\n\nstruct Quote: Codable {\n let anime: String\n let character: String\n let quote: String\n}\n\n\/\/ Example usage\nfetchRandomAnimeQuote()\n```\n\nIn this solution, the `fetchRandomAnimeQuote` function constructs a URL using the provided base URL and the `\/api\/random` endpoint. It then creates a data task using `URLSession.shared.dataTask` to make a GET request to the constructed URL. The function handles potential errors, validates the response, and decodes the received JSON data into a `Quote` struct using `JSONDecoder`. Finally, it prints the anime quote details to the console."} {"lang":"java","raw_index":36214,"index":4785,"seed":" *\/\n\npublic class SPRestDivisionOp extends SPBinaryExpression {\n\n\n public SPRestDivisionOp(int line, SPExpression lhs, SPExpression rhs) {\n super(line, lhs, rhs);\n }\n\n public SPExpression analyze(Context context) {\n lhs = lhs.analyze(context);\n rhs = rhs.analyze(context);\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a division operation for a custom programming language. The provided code snippet is a part of the implementation for the division operation in the language. Your task is to complete the implementation of the division operation by writing the necessary code to handle the division of two expressions.\n\nYou are given a class `SPRestDivisionOp` that extends `SPBinaryExpression`. The constructor of `SPRestDivisionOp` takes an integer `line`, representing the line number in the code, and two `SPExpression` objects `lhs` and `rhs`, representing the left-hand side and right-hand side of the division operation, respectively.\n\nYour task is to implement the `analyze` method for the `SPRestDivisionOp` class. The `analyze` method is responsible for performing semantic analysis and type checking of the division operation. You need to ensure that the division operation is valid and handle any potential errors related to division by zero or incompatible types.\n\nYour implementation should handle the following:\n1. Perform semantic analysis and type checking for the left-hand side and right-hand side expressions.\n2. Ensure that the division operation is valid and handle division by zero.\n3. Return the result of the division operation if it is valid.\n\nYour task is to complete the `analyze` method to fulfill the requirements outlined above.","solution":"```java\npublic SPExpression analyze(Context context) {\n \/\/ Perform semantic analysis and type checking for the left-hand side and right-hand side expressions\n lhs = lhs.analyze(context);\n rhs = rhs.analyze(context);\n\n \/\/ Ensure that the division operation is valid and handle division by zero\n if (lhs.getType() != Type.INT || rhs.getType() != Type.INT) {\n \/\/ Handle error: Division operands must be of type INT\n throw new SemanticException(\"Division operands must be of type INT\", line);\n } else if (rhs instanceof SPIntLiteral && ((SPIntLiteral) rhs).getValue() == 0) {\n \/\/ Handle error: Division by zero\n throw new SemanticException(\"Division by zero is not allowed\", line);\n }\n\n \/\/ Return the result of the division operation if it is valid\n return new SPDivisionOp(line, lhs, rhs);\n}\n```\n\nIn the solution, the `analyze` method performs semantic analysis and type checking for the division operation. It ensures that the operands are of type `INT` and handles division by zero. If the division operation is valid, it returns a new `SPDivisionOp` object representing the division expression. If any errors are encountered during the analysis, it throws a `SemanticException` with the corresponding error message and line number."} {"lang":"csharp","raw_index":147212,"index":4970,"seed":" internal abstract class AbstractTaggerEventSource : ITaggerEventSource\n {\n private bool _paused;\n\n protected AbstractTaggerEventSource()\n {\n }\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simple event handling system in C#. Your goal is to create a class that manages event sources and allows other classes to subscribe to and receive notifications when events occur.\n\nYou are provided with a partial code snippet for an abstract class `AbstractTaggerEventSource` that serves as the base for event sources. The class has a private boolean field `_paused` and a constructor that initializes it.\n\nYour task is to complete the implementation of the `AbstractTaggerEventSource` class by adding methods to manage event subscriptions and notifications.\n\nYour implementation should include the following:\n1. A method to subscribe to events, allowing other classes to register to receive notifications when events occur.\n2. A method to unsubscribe from events, allowing registered classes to cancel their subscriptions.\n3. A method to notify all subscribed classes when an event occurs.\n\nYour implementation should adhere to the following requirements:\n1. Use C# language features to manage event subscriptions and notifications.\n2. Ensure that the event source can handle multiple subscribers and notify all of them when an event occurs.\n3. Implement the necessary logic to handle pausing and resuming event notifications.\n\nYour task is to complete the implementation of the `AbstractTaggerEventSource` class according to the given requirements.","solution":"```csharp\ninternal abstract class AbstractTaggerEventSource : ITaggerEventSource\n{\n private bool _paused;\n public event EventHandler EventOccurred;\n\n protected AbstractTaggerEventSource()\n {\n }\n\n public void Subscribe(EventHandler eventHandler)\n {\n EventOccurred += eventHandler;\n }\n\n public void Unsubscribe(EventHandler eventHandler)\n {\n EventOccurred -= eventHandler;\n }\n\n public void NotifyEventOccurred(EventNotificationArgs args)\n {\n if (!_paused)\n {\n EventOccurred?.Invoke(this, args);\n }\n }\n\n public void PauseNotifications()\n {\n _paused = true;\n }\n\n public void ResumeNotifications()\n {\n _paused = false;\n }\n}\n\npublic interface ITaggerEventSource\n{\n \/\/ Interface for event source\n}\n\npublic class EventNotificationArgs : EventArgs\n{\n \/\/ Custom event arguments if needed\n}\n```\n\nIn the solution, the `AbstractTaggerEventSource` class is completed with methods to subscribe, unsubscribe, and notify event occurrences. It also includes methods to pause and resume event notifications. The class implements the `ITaggerEventSource` interface and uses the `EventNotificationArgs` class for custom event arguments if needed."} {"lang":"typescript","raw_index":73497,"index":4933,"seed":"declare let f1: (x: Animal) => void;\ndeclare let f2: (x: Dog) => void;\ndeclare let f3: (x: Cat) => void;\nf1 = f2; \/\/ OK becasue --strictFunctionTypes is false\nf2 = f1; \/\/ Ok\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with understanding and resolving a type compatibility issue in a TypeScript program. Consider the following code snippet:\n\n```typescript\ndeclare let f1: (x: Animal) => void;\ndeclare let f2: (x: Dog) => void;\ndeclare let f3: (x: Cat) => void;\nf1 = f2; \/\/ OK because --strictFunctionTypes is false\nf2 = f1; \/\/ OK\n```\n\nExplain why the assignments `f1 = f2` and `f2 = f1` are allowed, and how the `--strictFunctionTypes` flag affects this behavior. Provide a detailed explanation of the type compatibility rules and the impact of the `--strictFunctionTypes` flag on function type assignments in TypeScript.","solution":"In TypeScript, function type compatibility is determined based on parameter and return type structures. When assigning function types to variables, TypeScript checks the compatibility of the parameter and return types. The `--strictFunctionTypes` flag enforces stricter checking for function type compatibility.\n\nIn the given code snippet, the assignments `f1 = f2` and `f2 = f1` are allowed because the `--strictFunctionTypes` flag is set to false. When `--strictFunctionTypes` is false, TypeScript allows assignment of function types with different parameter types as long as the return type is compatible. This is known as contravariance for parameter types and covariance for return types.\n\nWith `--strictFunctionTypes` off, the assignment `f1 = f2` is allowed because `f2`'s parameter type `Dog` is a subtype of `Animal`, making it compatible with `f1`'s parameter type. Similarly, the assignment `f2 = f1` is allowed because `f1`'s parameter type `Animal` is a supertype of `Dog`, making it compatible with `f2`'s parameter type.\n\nHowever, if the `--strictFunctionTypes` flag were set to true, both assignments would result in type errors. With `--strictFunctionTypes` on, TypeScript enforces strict function type checking, disallowing assignments between function types with different parameter types, even if they are related through inheritance.\n\nIn summary, the `--strictFunctionTypes` flag affects the assignment of function types by enforcing stricter checking for parameter type compatibility. When `--strictFunctionTypes` is false, TypeScript allows assignments between function types with related parameter types, based on contravariance and covariance rules."} {"lang":"java","raw_index":112668,"index":1760,"seed":" return c.writerIndex() - tlvStartIndex;\r\n }\r\n\r\n \/**\r\n * Reads the channel buffer and returns object of AutonomousSystemTlv.\r\n *\r\n * @param c input channel buffer\r\n * @param hLength length of subtlvs.\r\n * @return object of AutonomousSystemTlv\r\n * @throws PcepParseException if mandatory fields are missing\r\n *\/\r\n public static PcepValueType read(ChannelBuffer c, short hLength) throws PcepParseException {\r\n\r\n \/\/ Node Descriptor Sub-TLVs (variable)\r\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a method to parse a specific type of TLV (Type-Length-Value) from a network protocol message. The given code snippet is part of a larger networking library and contains a method for reading a channel buffer and returning an object of type `AutonomousSystemTlv`. The `AutonomousSystemTlv` represents a TLV containing information about an autonomous system in a network.\n\nYour task is to implement the `read` method for parsing the `AutonomousSystemTlv` from the input channel buffer. The method takes two parameters: the input channel buffer `c` and the length of sub-TLVs `hLength`. The method should handle the parsing of the channel buffer and construct an `AutonomousSystemTlv` object. If any mandatory fields are missing in the input, the method should throw a `PcepParseException`.\n\nYou are provided with the method signature and a comment indicating the presence of \"Node Descriptor Sub-TLVs (variable)\" within the code snippet. You should use this information to guide the parsing logic for the `AutonomousSystemTlv`.\n\nYour task is to complete the implementation of the `read` method to parse the channel buffer and construct an `AutonomousSystemTlv` object, ensuring that all mandatory fields are present and handling any potential parsing errors.\n\n```java\npublic static PcepValueType read(ChannelBuffer c, short hLength) throws PcepParseException {\n \/\/ Your implementation here\n}\n```","solution":"```java\npublic static PcepValueType read(ChannelBuffer c, short hLength) throws PcepParseException {\n \/\/ Assuming the structure of AutonomousSystemTlv is as follows:\n \/\/ 1 byte - Type\n \/\/ 1 byte - Length\n \/\/ 4 bytes - Autonomous System Number\n\n if (c.readableBytes() < 6) { \/\/ Minimum length required for the TLV\n throw new PcepParseException(\"Insufficient bytes to parse AutonomousSystemTlv\");\n }\n\n byte type = c.readByte();\n byte length = c.readByte();\n\n if (length != 4) {\n throw new PcepParseException(\"Invalid length for AutonomousSystemTlv\");\n }\n\n int asNumber = c.readInt();\n\n \/\/ Assuming there are additional sub-TLVs within the AutonomousSystemTlv\n \/\/ You can parse the sub-TLVs based on the provided hLength\n\n \/\/ Construct and return the AutonomousSystemTlv object\n return new AutonomousSystemTlv(type, length, asNumber);\n}\n```"} {"lang":"java","raw_index":115367,"index":1272,"seed":" * Test for {@link Earth3D#convertToModel(GeographicPosition, Vector3d)} .\n * This test only ensures that convertToModel and convertToPosition are\n * opposite operations.\n *\/\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a method to convert geographic positions to 3D model coordinates and vice versa. The geographic positions are represented by latitude, longitude, and altitude, while the 3D model coordinates are represented by x, y, and z values. The goal is to ensure that the conversion methods are inverse operations of each other.\n\nYou are given the following method signature for the conversion:\n\n```java\npublic class Earth3D {\n public Vector3d convertToModel(GeographicPosition position, Vector3d modelOrigin) {\n \/\/ Implementation to convert geographic position to 3D model coordinates\n }\n\n public GeographicPosition convertToPosition(Vector3d modelCoordinates, Vector3d modelOrigin) {\n \/\/ Implementation to convert 3D model coordinates to geographic position\n }\n}\n```\n\nYour task is to implement the `convertToModel` and `convertToPosition` methods such that they correctly convert between geographic positions and 3D model coordinates. Additionally, you need to write test cases to ensure that the two methods are indeed inverse operations of each other.","solution":"```java\npublic class Earth3D {\n public Vector3d convertToModel(GeographicPosition position, Vector3d modelOrigin) {\n \/\/ Implementation to convert geographic position to 3D model coordinates\n double x = (position.getLongitude() - modelOrigin.getLongitude()) * Math.cos(position.getLatitude()) * Math.cos(position.getLongitude());\n double y = (position.getLatitude() - modelOrigin.getLatitude()) * Math.cos(position.getLatitude()) * Math.sin(position.getLongitude());\n double z = (position.getAltitude() - modelOrigin.getAltitude());\n return new Vector3d(x, y, z);\n }\n\n public GeographicPosition convertToPosition(Vector3d modelCoordinates, Vector3d modelOrigin) {\n \/\/ Implementation to convert 3D model coordinates to geographic position\n double longitude = Math.atan2(modelCoordinates.getY(), modelCoordinates.getX()) + modelOrigin.getLongitude();\n double latitude = Math.atan2(modelCoordinates.getZ(), Math.sqrt(modelCoordinates.getX() * modelCoordinates.getX() + modelCoordinates.getY() * modelCoordinates.getY())) + modelOrigin.getLatitude();\n double altitude = modelCoordinates.getZ() + modelOrigin.getAltitude();\n return new GeographicPosition(latitude, longitude, altitude);\n }\n}\n```\n\nTo ensure that the `convertToModel` and `convertToPosition` methods are inverse operations of each other, the following test case can be used:\n\n```java\npublic class Earth3DTest {\n @Test\n public void testConversion() {\n Earth3D earth3D = new Earth3D();\n GeographicPosition position = new GeographicPosition(40.7128, -74.0060, 0); \/\/ New York City\n Vector3d modelOrigin = new Vector3d(0, 0, 0); \/\/ Assume model origin at (0, 0, 0)\n\n Vector3d modelCoordinates = earth3D.convertToModel(position, modelOrigin);\n GeographicPosition convertedPosition = earth3D.convertToPosition(modelCoordinates, modelOrigin);\n\n assertEquals(position, convertedPosition);\n }\n}\n```\n\nThis test case ensures that converting a geographic position to 3D model coordinates and then back to a geographic position results in the original geographic position, validating that the conversion methods are indeed inverse operations of each other."} {"lang":"cpp","raw_index":95797,"index":2133,"seed":" static void writeXMLInfo(std::ofstream &xml, const std::string &kernelFileName, const LayerParam ¶m) {\n writeXMLTag(xml, \"kernelName\", param.kernelName);\n writeXMLTag(xml, \"xclbinFileName\", param.xclbinFileName);\n writeXMLTag(xml, \"kernelFileName\", kernelFileName);\n writeXMLOpenTag(xml, \"workGroupSize\");\n for (size_t i = 0; i < sizeof(param.workGroupSize) \/ sizeof(size_t); ++i) {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program to parse and extract information from an XML file. The XML file contains data related to OpenCL kernel parameters and their associated files. Your program needs to read the XML file and extract specific information related to kernel names, xclbin file names, kernel file names, and work group sizes.\n\nYou are given a code snippet that demonstrates the function `writeXMLInfo` which writes specific information to an XML file. The function `writeXMLInfo` takes an `std::ofstream` object `xml`, the `kernelFileName` as a `std::string`, and a `LayerParam` object `param` as input. The `LayerParam` object contains information related to the kernel, including its name, xclbin file name, kernel file name, and work group size.\n\nYour task is to create a program that reads an XML file, extracts the information written by the `writeXMLInfo` function, and stores it in a suitable data structure for further processing.\n\nWrite a function `parseXMLInfo` that takes the file path of the XML file as input and returns a data structure containing the extracted information in a suitable format.\n\nYou should assume that the XML file follows a specific format, and the `writeXMLInfo` function is consistently used to write the information in the XML file.","solution":"```cpp\n#include \n#include \n#include \n#include \n\nstruct LayerParam {\n std::string kernelName;\n std::string xclbinFileName;\n std::string kernelFileName;\n std::vector workGroupSize;\n};\n\nvoid writeXMLTag(std::ofstream &xml, const std::string &tag, const std::string &value) {\n xml << \"<\" << tag << \">\" << value << \"<\/\" << tag << \">\\n\";\n}\n\nvoid writeXMLOpenTag(std::ofstream &xml, const std::string &tag) {\n xml << \"<\" << tag << \">\\n\";\n}\n\nLayerParam parseXMLInfo(const std::string &filePath) {\n LayerParam param;\n std::ifstream file(filePath);\n std::string line;\n while (std::getline(file, line)) {\n if (line.find(\"\") != std::string::npos) {\n param.kernelName = line.substr(line.find(\">\") + 1, line.rfind(\"<\") - line.find(\">\") - 1);\n } else if (line.find(\"\") != std::string::npos) {\n param.xclbinFileName = line.substr(line.find(\">\") + 1, line.rfind(\"<\") - line.find(\">\") - 1);\n } else if (line.find(\"\") != std::string::npos) {\n param.kernelFileName = line.substr(line.find(\">\") + 1, line.rfind(\"<\") - line.find(\">\") - 1);\n } else if (line.find(\"\") != std::string::npos) {\n while (std::getline(file, line)) {\n if (line.find(\"<\/workGroupSize>\") != std::string::npos) {\n break;\n }\n size_t size = std::stoul(line);\n param.workGroupSize.push_back(size);\n }\n }\n }\n return param;\n}\n\nint main() {\n std::string filePath = \"path_to_xml_file.xml\";\n LayerParam extractedInfo = parseXMLInfo(filePath);\n \/\/ Process extractedInfo as needed\n return 0;\n}\n```\n\nIn the solution, the `parseXMLInfo` function reads the XML file line by line and extracts the required information based on the XML tags. It populates a `LayerParam` object with the extracted information and returns it. The `main` function demonstrates how to use the `parseXMLInfo` function to extract information from the XML file and process it further."} {"lang":"python","raw_index":6694,"index":5022,"seed":"\r\n__all__ = [\r\n 'chainOpen'\r\n]","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python function that simulates the behavior of a chain of open operations. The function `chainOpen` takes a list of strings as input, where each string represents an operation. The operations can be of two types: \"open\" and \"close\". The function should return a boolean value indicating whether the list of operations forms a valid chain of open and close operations.\n\nThe rules for a valid chain are as follows:\n1. The chain must start with an \"open\" operation.\n2. For every \"open\" operation, there must be a corresponding \"close\" operation later in the list.\n3. The \"close\" operation must match the most recent unmatched \"open\" operation.\n\nYou need to implement the `chainOpen` function to determine if the input list of operations forms a valid chain.\n\nFunction signature: `def chainOpen(operations: List[str]) -> bool`\n\nExample:\n```python\nchainOpen([\"open\", \"open\", \"close\", \"open\", \"close\", \"close\"]) # Output: True\nchainOpen([\"open\", \"open\", \"close\", \"close\"]) # Output: False\n```","solution":"```python\nfrom typing import List\n\ndef chainOpen(operations: List[str]) -> bool:\n stack = []\n for op in operations:\n if op == \"open\":\n stack.append(op)\n elif op == \"close\":\n if not stack or stack[-1] != \"open\":\n return False\n stack.pop()\n return len(stack) == 0\n```\n\nThe `chainOpen` function uses a stack to keep track of the unmatched \"open\" operations encountered so far. It iterates through the list of operations and pushes \"open\" operations onto the stack. When a \"close\" operation is encountered, it checks if the stack is empty or if the top of the stack does not match the \"close\" operation. If either condition is true, the function returns False. After processing all operations, the function checks if the stack is empty to ensure all \"open\" operations have been matched with \"close\" operations. If the stack is empty, the function returns True; otherwise, it returns False."} {"lang":"csharp","raw_index":92392,"index":920,"seed":"\t\tpublic int Admin { get; set; }\n\t\tpublic List Characters { get; set; }\n\t\tpublic Character SelectedCharacter { get; set; }\n\t}\n}\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a character selection system for a game. The provided code snippet outlines a simplified version of the relevant classes and properties. The `Admin` property represents the administrator's ID, while the `Characters` property is a list of available character objects. The `SelectedCharacter` property holds the currently selected character.\n\nYour task is to create a method within the `Game` class that allows the administrator to assign a character to the `SelectedCharacter` property. The method should perform the following checks:\n1. Verify that the administrator ID matches the `Admin` property.\n2. Ensure that the character being assigned exists in the `Characters` list.\n\nImplement the `AssignCharacter` method in the `Game` class to fulfill these requirements.\n\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic class Character\n{\n public string Name { get; set; }\n public int Level { get; set; }\n}\n\npublic class Game\n{\n public int Admin { get; set; }\n public List Characters { get; set; }\n public Character SelectedCharacter { get; set; }\n\n public void AssignCharacter(int adminId, string characterName)\n {\n \/\/ Your implementation here\n }\n}\n```","solution":"```csharp\npublic void AssignCharacter(int adminId, string characterName)\n{\n if (adminId == Admin)\n {\n Character selected = Characters.Find(c => c.Name == characterName);\n if (selected != null)\n {\n SelectedCharacter = selected;\n Console.WriteLine($\"Character '{characterName}' assigned successfully.\");\n }\n else\n {\n Console.WriteLine($\"Character '{characterName}' does not exist.\");\n }\n }\n else\n {\n Console.WriteLine(\"Unauthorized access. Admin ID does not match.\");\n }\n}\n```\n\nThe `AssignCharacter` method first checks if the provided `adminId` matches the `Admin` property. If the IDs match, it then searches for the character with the specified name in the `Characters` list. If the character is found, it is assigned to the `SelectedCharacter` property. If the character does not exist, an appropriate message is displayed. If the admin ID does not match, an unauthorized access message is shown."} {"lang":"python","raw_index":36837,"index":18561,"seed":" # Total Funds Available\n funds_available = short_term_assets['yr1'] + short_term_liabilities['yr1'] + long_term_liabilities['yr1']\n\n # Start-up Deficit\/Surplus\n net_startup_deficit_surplus = cash_required - funds_available\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a financial management program for a startup company. The program needs to calculate the total funds available and determine the startup's deficit or surplus based on the available funds and the cash required for the startup. The following code snippet provides a glimpse of the calculations involved:\n\n```python\n# Total Funds Available\nfunds_available = short_term_assets['yr1'] + short_term_liabilities['yr1'] + long_term_liabilities['yr1']\n\n# Start-up Deficit\/Surplus\nnet_startup_deficit_surplus = cash_required - funds_available\n```\n\nGiven the above code snippet, you need to implement a function `calculate_deficit_surplus` that takes in the following parameters:\n- `short_term_assets`: A dictionary containing the short-term assets for the startup, with keys representing years and values representing the corresponding amounts.\n- `short_term_liabilities`: A dictionary containing the short-term liabilities for the startup, with keys representing years and values representing the corresponding amounts.\n- `long_term_liabilities`: A dictionary containing the long-term liabilities for the startup, with keys representing years and values representing the corresponding amounts.\n- `cash_required`: The amount of cash required for the startup.\n\nThe function should calculate the total funds available based on the provided dictionaries and then determine the startup's deficit or surplus by subtracting the funds available from the cash required. Finally, the function should return the calculated deficit or surplus.\n\nYour task is to implement the `calculate_deficit_surplus` function to perform the required financial calculations.","solution":"```python\ndef calculate_deficit_surplus(short_term_assets, short_term_liabilities, long_term_liabilities, cash_required):\n # Calculate Total Funds Available\n funds_available = short_term_assets['yr1'] + short_term_liabilities['yr1'] + long_term_liabilities['yr1']\n\n # Calculate Start-up Deficit\/Surplus\n net_startup_deficit_surplus = cash_required - funds_available\n\n return net_startup_deficit_surplus\n```\n\nThe `calculate_deficit_surplus` function takes in the provided parameters, calculates the total funds available by summing the short-term assets, short-term liabilities, and long-term liabilities for the startup. It then determines the startup's deficit or surplus by subtracting the funds available from the cash required and returns the calculated deficit or surplus."} {"lang":"python","raw_index":45999,"index":38190,"seed":" ### SERIAL\n start_time = time.time()\n for req in reqs:\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that calculates the total time taken to process a series of requests. Each request has a specific processing time, and the requests are processed sequentially. Your function should take a list of request processing times as input and return the total time taken to process all the requests.\n\nFor example, given the list of processing times [3, 5, 2, 7], the total time taken to process all the requests sequentially would be 3 + 5 + 2 + 7 = 17 units of time.\n\nWrite a function `calculate_total_time(reqs: List[int]) -> int` to solve this problem.","solution":"```python\nfrom typing import List\n\ndef calculate_total_time(reqs: List[int]) -> int:\n total_time = 0\n for req in reqs:\n total_time += req\n return total_time\n```\nThe `calculate_total_time` function takes a list of request processing times as input and iterates through the list, accumulating the total time taken to process all the requests. It then returns the total time as the output."} {"lang":"python","raw_index":2972,"index":22549,"seed":"\n@app.command()\ndef run(\n targets: Optional[List[str]] = Argument(None),\n handout: bool = True,\n presentation: bool = True,\n print: bool = True,\n deck_path: Path = Path(\".\"),\n) -> None:\n \"\"\"Compile main targets.\"\"\"\n paths = Paths.from_defaults(deck_path)\n running_run(\n paths=paths,\n build_handout=handout,\n build_presentation=presentation,\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a command-line interface (CLI) tool for compiling and building presentation materials. The provided code snippet is a part of the CLI tool, which uses the `click` library for defining commands and options.\n\nYour task is to implement a function that constructs the paths for the presentation materials and then calls another function to initiate the compilation process based on the provided command-line arguments.\n\nThe function `run` takes in several command-line arguments:\n- `targets`: A list of strings representing the targets to be compiled.\n- `handout`: A boolean flag indicating whether to build handout materials.\n- `presentation`: A boolean flag indicating whether to build presentation materials.\n- `print`: A boolean flag indicating whether to print the output.\n- `deck_path`: A Path object representing the path to the deck (defaulting to the current directory).\n\nThe `run` function then constructs the `paths` object using the `Paths.from_defaults` method, passing in the `deck_path`. After constructing the `paths` object, it calls the `running_run` function with the constructed `paths` and the build flags.\n\nYour task is to implement the `running_run` function and the `Paths` class with the `from_defaults` method, and ensure that the CLI tool functions as expected.","solution":"```python\nfrom typing import List, Optional\nfrom pathlib import Path\n\nclass Paths:\n def __init__(self, deck_path: Path):\n self.deck_path = deck_path\n # Other path attributes can be initialized here\n\n @classmethod\n def from_defaults(cls, deck_path: Path) -> 'Paths':\n return cls(deck_path)\n\ndef running_run(paths: Paths, build_handout: bool, build_presentation: bool) -> None:\n # Implement the compilation process based on the paths and build flags\n # Example: \n if build_handout:\n print(f\"Building handout materials from {paths.deck_path}\")\n if build_presentation:\n print(f\"Building presentation materials from {paths.deck_path}\")\n\n# Example usage\nif __name__ == \"__main__\":\n import click\n\n @click.command()\n @click.option('--targets', multiple=True, help='List of targets to compile')\n @click.option('--no-handout', is_flag=True, help='Do not build handout materials')\n @click.option('--no-presentation', is_flag=True, help='Do not build presentation materials')\n @click.option('--no-print', is_flag=True, help='Do not print output')\n @click.option('--deck-path', type=click.Path(exists=True), default='.', help='Path to the deck')\n def run(targets: List[str], no_handout: bool, no_presentation: bool, no_print: bool, deck_path: str) -> None:\n \"\"\"Compile main targets.\"\"\"\n paths = Paths.from_defaults(Path(deck_path))\n running_run(paths=paths, build_handout=not no_handout, build_presentation=not no_presentation)\n\n run()\n```\n\nIn this solution, the `Paths` class is defined with an `__init__` method to initialize path attributes and a `from_defaults` class method to create a `Paths` object with default values. The `running_run` function is implemented to handle the compilation process based on the paths and build flags. Additionally, an example usage of the CLI tool using the `click` library is provided."} {"lang":"python","raw_index":138089,"index":25177,"seed":"\nfrom spack import *\n\n\nclass Henson(CMakePackage):\n \"\"\"Cooperative multitasking for in situ processing.\"\"\"\n\n homepage = \"https:\/\/github.com\/henson-insitu\/henson\"\n git = \"https:\/\/github.com\/henson-insitu\/henson.git\"\n\n version('master', branch='master')\n\n depends_on('mpi')\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python script that automates the process of generating a software package configuration file based on user input. The configuration file will be used to build and install a software package using the Spack package manager.\n\nYour script should prompt the user to input the following details:\n1. Package name\n2. Package description\n3. Homepage URL\n4. Git repository URL\n5. Version information (e.g., master branch, specific release tag)\n6. Dependency on other packages (if any)\n\nOnce the user provides this information, your script should generate a Python script that uses the Spack package manager to define the software package configuration. The generated script should include the necessary code to create a package class using the input provided by the user. The package class should inherit from the appropriate Spack class (e.g., CMakePackage) and include the input details such as package name, description, homepage, git repository, version, and dependencies.\n\nYour script should handle user input validation to ensure that the required information is provided and that the input format is correct. Additionally, it should provide clear prompts and error messages to guide the user through the input process.","solution":"```python\n# Prompt user for package details\npackage_name = input(\"Enter the package name: \")\npackage_description = input(\"Enter the package description: \")\nhomepage_url = input(\"Enter the homepage URL: \")\ngit_repository_url = input(\"Enter the Git repository URL: \")\nversion_info = input(\"Enter the version information (e.g., master branch, specific release tag): \")\ndependency_info = input(\"Enter dependency information (if any): \")\n\n# Validate user input\nif not all([package_name, package_description, homepage_url, git_repository_url, version_info]):\n print(\"Error: All required fields must be provided.\")\n exit()\n\n# Generate Python script for package configuration\nscript_content = f\"\"\"\nfrom spack import *\n\nclass {package_name}(CMakePackage):\n \\\"{package_description}\\\"\n\n homepage = \\\"{homepage_url}\\\"\n git = \\\"{git_repository_url}\\\"\n\n version('{version_info}', branch='{version_info}')\n\n depends_on({dependency_info})\n\"\"\"\n\n# Write the generated script to a file\nwith open(f\"{package_name}_package.py\", \"w\") as file:\n file.write(script_content)\n\nprint(f\"Package configuration script generated as {package_name}_package.py\")\n```\n\nThis Python script prompts the user for package details, validates the input, and then generates a Python script for the package configuration based on the user input. The generated script defines a package class using the Spack package manager, incorporating the provided package details and dependencies. The script also writes the generated content to a file for later use."} {"lang":"cpp","raw_index":138181,"index":1439,"seed":"\t\tfloat radiusDistance = _radius + other._radius;\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class that represents a circle in a 2D plane. The class should have a method to calculate the distance between two circles based on their radii. The distance between two circles is defined as the sum of their radii. You need to implement the method `calculateDistance` that takes another circle as a parameter and returns the distance between the two circles.\n\nThe Circle class has the following attributes:\n- `float _radius`: The radius of the circle.\n\nYou need to implement the following method in the Circle class:\n- `float calculateDistance(Circle other)`: This method should calculate the distance between the current circle and the `other` circle based on their radii and return the result.\n\nYou can use the following code snippet as a starting point:\n```\nfloat radiusDistance = _radius + other._radius;\n```","solution":"```java\npublic class Circle {\n private float _radius;\n\n public Circle(float radius) {\n _radius = radius;\n }\n\n public float calculateDistance(Circle other) {\n return _radius + other._radius;\n }\n\n public static void main(String[] args) {\n Circle circle1 = new Circle(5.0f);\n Circle circle2 = new Circle(3.0f);\n\n float distance = circle1.calculateDistance(circle2);\n System.out.println(\"Distance between circle1 and circle2: \" + distance);\n }\n}\n```\n\nIn this solution, we define a Circle class with a constructor to initialize the radius and a method `calculateDistance` to calculate the distance between two circles based on their radii. The `calculateDistance` method simply returns the sum of the radii of the two circles. The main method demonstrates the usage of the Circle class by creating two circles and calculating the distance between them."} {"lang":"python","raw_index":85450,"index":19180,"seed":"import torch\nfrom torch.nn import functional as F\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\n\nfrom torch_geometric_temporal.nn.recurrent import DCRNN\nfrom torch_geometric_temporal.dataset import ChickenpoxDatasetLoader\nfrom torch_geometric_temporal.signal import temporal_signal_split\n\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with building a deep learning model to predict the spread of chickenpox using temporal graph data. The dataset contains information about the spread of chickenpox over time, represented as a temporal graph. Each node in the graph represents a geographical location, and the edges represent the spread of the disease between locations at different time points. Your goal is to create a PyTorch model using the DCRNN (Diffusion Convolutional Recurrent Neural Network) architecture to make accurate predictions about the future spread of chickenpox.\n\nYou are provided with the necessary Python libraries and modules to accomplish this task. The `torch` library is used for tensor computations, and the `pytorch_lightning` library provides a high-level interface for training PyTorch models. Additionally, the `torch_geometric_temporal` library offers tools for handling temporal graph data, including the DCRNN model and dataset loader.\n\nYour task is to implement the DCRNN model, load the chickenpox dataset, split the temporal graph data into training and testing sets, and train the model using the training data. Finally, you should evaluate the model's performance on the testing data.\n\nYour solution should include the following steps:\n1. Import the required libraries and modules.\n2. Load the chickenpox dataset using the `ChickenpoxDatasetLoader`.\n3. Split the temporal graph data into training and testing sets using `temporal_signal_split`.\n4. Create an instance of the DCRNN model.\n5. Configure the training process using PyTorch Lightning and early stopping.\n6. Train the model using the training data.\n7. Evaluate the model's performance on the testing data.","solution":"```python\nimport torch\nfrom torch.nn import functional as F\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom torch_geometric_temporal.nn.recurrent import DCRNN\nfrom torch_geometric_temporal.dataset import ChickenpoxDatasetLoader\nfrom torch_geometric_temporal.signal import temporal_signal_split\n\n# Step 1: Load the chickenpox dataset\nloader = ChickenpoxDatasetLoader()\ndataset = loader.get_dataset()\n\n# Step 2: Split the temporal graph data into training and testing sets\ntrain_data, test_data = temporal_signal_split(dataset, train_ratio=0.8)\n\n# Step 3: Create an instance of the DCRNN model\nnum_nodes = dataset.num_nodes\ninput_dim = dataset.num_node_features\noutput_dim = dataset.num_node_labels\nhidden_dim = 64\nnum_layers = 2\nseq_length = 10\ndcrnn = DCRNN(input_dim, hidden_dim, output_dim, num_layers, seq_length, dropout=0.1)\n\n# Step 4: Configure the training process using PyTorch Lightning and early stopping\ntrainer = pl.Trainer(callbacks=[EarlyStopping(monitor='val_loss')])\n\n# Step 5: Train the model using the training data\ntrainer.fit(dcrnn, train_data)\n\n# Step 6: Evaluate the model's performance on the testing data\nresults = trainer.test(dcrnn, test_data)\nprint(results)\n```\n\nThis solution demonstrates the complete process of building and training a DCRNN model for predicting the spread of chickenpox using temporal graph data. It includes importing the required libraries, loading the dataset, creating the model, configuring the training process, training the model, and evaluating its performance."} {"lang":"python","raw_index":138768,"index":5282,"seed":" login_url = \"http:\/\/172.16.58.3\/servlet\/Login\" # \u767b\u5f55\u9875\u9762\n index_url = \"http:\/\/210.42.121.241\/stu\/stu_index.jsp\" # \u767b\u5f55\u4e4b\u540e\u7684\u4e3b\u9875\u9762\uff0c\u5728\u8fd9\u91cc\u83b7\u53d6\u4ee4\u724c\n gpa_url = \"http:\/\/172.16.58.3\/stu\/stu_score_credit_statics.jsp\" # \u5e26\u65e5\u5386\u7684\u603b\u5206\u548c\u6210\u7ee9\n lessons_url = \"http:\/\/210.42.121.241\/servlet\/Svlt_QueryStuLsn?{}\" # \u8bfe\u7a0b\u7684\u9875\u9762\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python program to scrape information from a university's student portal. The program should be able to log in to the portal, retrieve the main page after logging in to obtain a token, fetch the GPA and credit statistics page, and access the page for individual lessons. The provided code snippet includes the URLs for the login page, main page after logging in, GPA and credit statistics page, and the page for individual lessons. Your task is to implement the necessary functions to achieve these functionalities using Python's requests library.\n\nYour program should include the following functions:\n1. `login(username, password)`: This function should take the username and password as input, perform a POST request to the `login_url` with the provided credentials, and return the session object or token required for subsequent requests.\n\n2. `get_main_page(session)`: This function should take the session object or token obtained from the login function, perform a GET request to the `index_url`, and return the content of the main page.\n\n3. `get_gpa_page(session)`: This function should take the session object or token obtained from the login function, perform a GET request to the `gpa_url`, and return the content of the GPA and credit statistics page.\n\n4. `get_lessons_page(session, params)`: This function should take the session object or token obtained from the login function and additional parameters, perform a GET request to the `lessons_url` with the provided parameters, and return the content of the lessons page.\n\nYou should handle any necessary error cases and provide appropriate error messages. Assume that the requests library is already imported and available for use.","solution":"```python\nimport requests\n\nlogin_url = \"http:\/\/172.16.58.3\/servlet\/Login\" # \u767b\u5f55\u9875\u9762\nindex_url = \"http:\/\/210.42.121.241\/stu\/stu_index.jsp\" # \u767b\u5f55\u4e4b\u540e\u7684\u4e3b\u9875\u9762\uff0c\u5728\u8fd9\u91cc\u83b7\u53d6\u4ee4\u724c\ngpa_url = \"http:\/\/172.16.58.3\/stu\/stu_score_credit_statics.jsp\" # \u5e26\u65e5\u5386\u7684\u603b\u5206\u548c\u6210\u7ee9\nlessons_url = \"http:\/\/210.42.121.241\/servlet\/Svlt_QueryStuLsn?{}\" # \u8bfe\u7a0b\u7684\u9875\u9762\n\ndef login(username, password):\n payload = {'username': username, 'password': password}\n session = requests.Session()\n response = session.post(login_url, data=payload)\n if response.status_code == 200:\n return session\n else:\n raise Exception(\"Login failed\")\n\ndef get_main_page(session):\n response = session.get(index_url)\n if response.status_code == 200:\n return response.content\n else:\n raise Exception(\"Failed to retrieve main page\")\n\ndef get_gpa_page(session):\n response = session.get(gpa_url)\n if response.status_code == 200:\n return response.content\n else:\n raise Exception(\"Failed to retrieve GPA page\")\n\ndef get_lessons_page(session, params):\n url = lessons_url.format(params)\n response = session.get(url)\n if response.status_code == 200:\n return response.content\n else:\n raise Exception(\"Failed to retrieve lessons page\")\n\n# Example usage\nusername = \"your_username\"\npassword = \"your_password\"\nsession = login(username, password)\nmain_page = get_main_page(session)\ngpa_page = get_gpa_page(session)\nlessons_page = get_lessons_page(session, \"example_params\")\n```\n\nIn this solution, the `login`, `get_main_page`, `get_gpa_page`, and `get_lessons_page` functions are implemented to perform the required tasks of logging in, retrieving the main page, fetching the GPA and credit statistics page, and accessing the page for individual lessons. Error handling is included to raise exceptions in case of failed requests. The example usage demonstrates how to use these functions to achieve the specified functionalities."} {"lang":"python","raw_index":52096,"index":37167,"seed":" first_date = notes['date'].iloc[0] \n last_date = notes['date'].iloc[-1]\n self.date_range = np.arange(first_date, last_date - self.DELTA, self.STEP)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a data analysis project and need to implement a date range generator for a given dataset. The dataset contains a column 'date' with timestamps in chronological order. Your task is to create a Python class method that generates a date range based on the first and last dates in the dataset.\n\nYou are given the following code snippet as a starting point:\n```python\nfirst_date = notes['date'].iloc[0] \nlast_date = notes['date'].iloc[-1]\nself.date_range = np.arange(first_date, last_date - self.DELTA, self.STEP)\n```\nIn this code snippet, `notes` is a DataFrame containing the dataset, and `self.DELTA` and `self.STEP` are constants representing the interval and step size for the date range generation.\n\nWrite a Python class method `generate_date_range` that takes the dataset `notes`, interval `DELTA`, and step size `STEP` as input and returns the date range as a list of timestamps.\n\nYour method should handle the following:\n1. Extracting the first and last dates from the 'date' column of the input dataset.\n2. Generating a date range using the provided interval and step size.\n3. Returning the date range as a list of timestamps.\n\nNote: You can assume that the 'date' column in the dataset contains timestamps in a format that can be directly used for date range generation.\n\nWrite the `generate_date_range` method to accomplish the specified task.","solution":"```python\nimport numpy as np\n\nclass DateRangeGenerator:\n def __init__(self, DELTA, STEP):\n self.DELTA = DELTA\n self.STEP = STEP\n self.date_range = []\n\n def generate_date_range(self, notes, DELTA, STEP):\n first_date = notes['date'].iloc[0]\n last_date = notes['date'].iloc[-1]\n date_range = np.arange(first_date, last_date - DELTA, STEP)\n return date_range.tolist()\n\n# Example usage\n# Assuming notes is a DataFrame containing the dataset\n# Instantiate the DateRangeGenerator class\ndate_range_gen = DateRangeGenerator(DELTA_value, STEP_value)\n# Generate date range\ndate_range = date_range_gen.generate_date_range(notes, DELTA_value, STEP_value)\nprint(date_range)\n```\nIn the solution, we define a class `DateRangeGenerator` with an `__init__` method to initialize the interval and step size. The `generate_date_range` method takes the dataset `notes`, interval `DELTA`, and step size `STEP` as input and returns the date range as a list of timestamps. Inside the method, we extract the first and last dates from the dataset and use `np.arange` to generate the date range based on the provided interval and step size. Finally, we return the date range as a list of timestamps."} {"lang":"java","raw_index":108746,"index":843,"seed":"\t *\/\n\t@Override\n\t@Bean\n\tpublic JpaPackageScanProvider applicationJpaPackageScanProvider() {\n\t\treturn new JpaPackageScanProvider(ShowcaseCoreBusinessPackage.class.getPackage());\n\t}\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Java class that implements a JpaPackageScanProvider interface to scan a specific package for JPA entities. The JpaPackageScanProvider interface has a method called applicationJpaPackageScanProvider() which needs to be overridden. The method should return a new instance of JpaPackageScanProvider initialized with the package to be scanned.\n\nYour task is to implement the applicationJpaPackageScanProvider() method in a class that extends a certain base class and returns a new JpaPackageScanProvider instance initialized with the package obtained from a specific class.\n\nWrite a Java class that fulfills the requirements described above. You can assume that the JpaPackageScanProvider and ShowcaseCoreBusinessPackage classes are already defined and available for use.","solution":"```java\nimport org.springframework.context.annotation.Bean;\n\npublic class CustomJpaPackageScanProvider extends BaseJpaPackageScanProvider {\n\n @Override\n @Bean\n public JpaPackageScanProvider applicationJpaPackageScanProvider() {\n return new JpaPackageScanProvider(ShowcaseCoreBusinessPackage.class.getPackage());\n }\n}\n```\nIn this solution, we create a new class called CustomJpaPackageScanProvider that extends the BaseJpaPackageScanProvider class. We override the applicationJpaPackageScanProvider() method and annotate it with @Bean to indicate that it should be treated as a bean by the Spring framework. Inside the method, we return a new instance of JpaPackageScanProvider initialized with the package obtained from the ShowcaseCoreBusinessPackage class using the getPackage() method."} {"lang":"typescript","raw_index":135304,"index":3902,"seed":"\n static readonly discriminator: string | undefined = undefined;\n\n static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [\n {\n \"name\": \"inputFieldLabels\",\n \"baseName\": \"inputFieldLabels\",\n \"type\": \"{ [key: string]: string; }\",\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function that processes a given array of attribute type mappings and returns a new array containing only the attribute names that have a specified type. Each attribute type mapping is represented as an object with the following structure:\n```typescript\n{\n name: string,\n baseName: string,\n type: string,\n format: string\n}\n```\nThe function should take the following parameters:\n- `attributeTypeMap`: An array of attribute type mappings as described above.\n- `targetType`: A string representing the type to filter by.\n\nYour task is to implement the `filterAttributesByType` function, which should return an array containing the names of attributes whose `type` matches the `targetType`.\n\nFunction Signature: \n```typescript\nfunction filterAttributesByType(attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}>, targetType: string): string[]\n```\n\nFor example, given the following `attributeTypeMap`:\n```typescript\nconst attributeTypeMap = [\n {\n \"name\": \"inputFieldLabels\",\n \"baseName\": \"inputFieldLabels\",\n \"type\": \"{ [key: string]: string; }\",\n \"format\": \"\"\n },\n {\n \"name\": \"outputFieldLabels\",\n \"baseName\": \"outputFieldLabels\",\n \"type\": \"{ [key: string]: string; }\",\n \"format\": \"\"\n },\n {\n \"name\": \"inputFields\",\n \"baseName\": \"inputFields\",\n \"type\": \"string[]\",\n \"format\": \"\"\n }\n];\n```\nand a `targetType` of `\"string[]\"`, the expected output would be `[\"inputFields\"]`.","solution":"```typescript\nfunction filterAttributesByType(attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}>, targetType: string): string[] {\n const filteredAttributes: string[] = [];\n for (const attribute of attributeTypeMap) {\n if (attribute.type === targetType) {\n filteredAttributes.push(attribute.name);\n }\n }\n return filteredAttributes;\n}\n\n\/\/ Example usage\nconst attributeTypeMap = [\n {\n \"name\": \"inputFieldLabels\",\n \"baseName\": \"inputFieldLabels\",\n \"type\": \"{ [key: string]: string; }\",\n \"format\": \"\"\n },\n {\n \"name\": \"outputFieldLabels\",\n \"baseName\": \"outputFieldLabels\",\n \"type\": \"{ [key: string]: string; }\",\n \"format\": \"\"\n },\n {\n \"name\": \"inputFields\",\n \"baseName\": \"inputFields\",\n \"type\": \"string[]\",\n \"format\": \"\"\n }\n];\n\nconst targetType = \"string[]\";\nconsole.log(filterAttributesByType(attributeTypeMap, targetType)); \/\/ Output: [\"inputFields\"]\n```"} {"lang":"python","raw_index":43445,"index":4125,"seed":"h = Symbol(\"H\", INT)\n\ndomain = (1 <= h) & (10 >= h)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a program that generates a list of all possible integer values for a given symbolic variable within a specified domain. The domain is defined by a set of inequalities. Your task is to write a Python function that takes the symbolic variable and the domain as input and returns a list of all valid integer values within the domain.\n\nFor example, given the symbolic variable `h` and the domain `(1 <= h) & (10 >= h)`, the program should output the list `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`.\n\nWrite a Python function `generate_integer_values` that takes two parameters:\n- `symbolic_variable`: A symbolic variable represented as a string.\n- `domain`: A domain represented as a string containing inequalities and logical operators.\n\nThe function should return a list of all valid integer values within the specified domain.\n\nExample:\n```python\nprint(generate_integer_values(\"h\", \"(1 <= h) & (10 >= h)\"))\n# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n```","solution":"```python\nfrom sympy import Symbol, Interval\nimport sympy.sets.sets as sets\n\ndef generate_integer_values(symbolic_variable, domain):\n h = Symbol(symbolic_variable, 'integer')\n domain_expr = eval(domain, {symbolic_variable: h})\n interval = sets.FiniteSet(*list(Interval(*domain_expr.args)))\n return sorted(list(interval))\n```\n\nThe `generate_integer_values` function first creates a symbolic variable using the `Symbol` class from the `sympy` library. It then evaluates the domain expression using the `eval` function, substituting the symbolic variable with the created variable. The resulting interval is converted to a set using `sets.FiniteSet` and then sorted and converted to a list before being returned."} {"lang":"python","raw_index":83144,"index":6806,"seed":" version('1.7.4', sha256='e9b1a75a3eae05dded19c80eb17325be675e0698975baae976df603b6ed1eb10')\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a software project that involves managing different versions of a library. Each version of the library is associated with a unique version number and a SHA-256 hash value. Your task is to implement a function that takes the version number and its corresponding SHA-256 hash value as input and stores this information for future reference.\n\nWrite a Python function called `store_version` that takes two parameters:\n- `version_number` (string): A version number in the format 'x.y.z' (e.g., '1.7.4').\n- `sha256_hash` (string): A SHA-256 hash value associated with the version number.\n\nThe function should store this version and its SHA-256 hash in a dictionary called `version_store`, where the version number is the key and the SHA-256 hash is the value. If the version number already exists in the `version_store`, the function should update the associated SHA-256 hash with the new value.\n\nYour task is to implement the `store_version` function and demonstrate its usage by storing a few versions and their SHA-256 hash values.\n\nExample:\n```python\nstore_version('1.7.4', 'e9b1a75a3eae05dded19c80eb17325be675e0698975baae976df603b6ed1eb10')\nstore_version('2.0.1', '3f7b9a8c7e7e0e5f7d3e7e7f7a7b7c7d7e7f7a7b7c7d7e7f7a7b7c7d7e7f7a7b')\nstore_version('1.5.0', 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2')\nprint(version_store)\n```\n\nExpected Output:\n```\n{'1.7.4': 'e9b1a75a3eae05dded19c80eb17325be675e0698975baae976df603b6ed1eb10', '2.0.1': '3f7b9a8c7e7e0e5f7d3e7e7f7a7b7c7d7e7f7a7b7c7d7e7f7a7b7c7d7e7f7a7b', '1.5.0': 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2'}\n```","solution":"```python\nversion_store = {}\n\ndef store_version(version_number, sha256_hash):\n version_store[version_number] = sha256_hash\n\n# Demonstration of usage\nstore_version('1.7.4', 'e9b1a75a3eae05dded19c80eb17325be675e0698975baae976df603b6ed1eb10')\nstore_version('2.0.1', '3f7b9a8c7e7e0e5f7d3e7e7f7a7b7c7d7e7f7a7b7c7d7e7f7a7b7c7d7e7f7a7b')\nstore_version('1.5.0', 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2')\nprint(version_store)\n```"} {"lang":"rust","raw_index":100442,"index":893,"seed":"\t\t\t\t\t\treturn Err(shiplift::Error::InvalidResponse(format!(\"{}: {:?}\", error, error_detail)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tOk(())\n\t\t}))\n\t\t.buffer_unordered(parallelism)\n\t\t.try_collect()\n\t\t.await\n\t}\n\n\t\/\/\/ Export the images to a tar\n\tpub fn images_export(&self, images: Vec) -> impl AsyncRead + '_ {\n\t\tlet stream = self.docker.images().export(images.iter().map(|x| &**x).collect());\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Rust function that processes a list of Docker images and exports them to a tar file. The function should utilize asynchronous programming and error handling to ensure smooth execution. \n\nYou are provided with a partial code snippet that includes the `images_export` function, which takes a vector of image names and returns an asynchronous reader. Your task is to complete the function by implementing the necessary asynchronous operations and error handling.\n\nComplete the `images_export` function to asynchronously export the provided Docker images to a tar file. Ensure that the function handles errors appropriately and utilizes parallelism for efficient processing.\n\nYour implementation should adhere to the following requirements:\n- Use the `shiplift` crate for Docker interaction.\n- Utilize asynchronous operations and error handling.\n- Implement parallelism for efficient processing.\n\n```rust\nuse shiplift::Docker;\nuse futures::stream::StreamExt;\nuse tokio::io::{AsyncRead, AsyncWrite};\nuse std::io::Cursor;\n\n\/\/\/ Export the images to a tar\npub async fn images_export(docker: Docker, images: Vec) -> Result {\n let parallelism = 5; \/\/ Define the level of parallelism\n\n let mut export_stream = futures::stream::iter(images)\n .map(|image| {\n let docker_clone = docker.clone();\n tokio::spawn(async move {\n let mut export = docker_clone.images().get(&image).export().await?;\n let mut tar_data = Vec::new();\n tokio::io::copy(&mut export, &mut tar_data).await?;\n Ok((image, tar_data))\n })\n })\n .buffer_unordered(parallelism)\n .try_collect::>()\n .await?;\n\n let mut tar_data = Vec::new();\n for result in export_stream {\n let (image, data) = result?;\n tar_data.extend_from_slice(&data);\n println!(\"Exported image: {}\", image);\n }\n\n Ok(Cursor::new(tar_data))\n}\n```","solution":"The provided solution completes the `images_export` function to asynchronously export the Docker images to a tar file. It utilizes the `shiplift` crate for Docker interaction, `futures` for asynchronous operations, and `tokio` for runtime support.\n\nThe function begins by defining the level of parallelism and creating a stream of asynchronous tasks, each responsible for exporting a single Docker image. These tasks are executed in parallel using the `buffer_unordered` method to maximize efficiency.\n\nOnce all images are exported, the resulting tar data is aggregated, and an asynchronous reader (`Cursor`) containing the tar data is returned as the result. The function handles errors using the `Result` type and ensures that any encountered errors are appropriately propagated.\n\nOverall, the solution fulfills the requirements by effectively utilizing asynchronous operations, error handling, and parallelism to export Docker images to a tar file."} {"lang":"python","raw_index":63335,"index":34327,"seed":" self.write_tweet_csv(row['text'].strip(), 'dataset_sentiment','-1')\n # positive\n elif row['label'] == '1':\n self.write_tweet_txt(row['text'].strip(), 'positive_sentiment')\n self.write_tweet_csv(row['text'].strip(), 'positive_sentiment', '1')\n self.write_tweet_csv(row['text'].strip(), 'dataset_sentiment', '1')\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a sentiment analysis tool that processes tweets and categorizes them as either positive, negative, or neutral. The code snippet provided is a part of a Python class method that processes the sentiment label of a tweet and writes the tweet content to corresponding files based on its sentiment. The method `write_tweet_csv` writes the tweet content to a CSV file, and the method `write_tweet_txt` writes the tweet content to a text file. The sentiment label is indicated by the value in the `label` field of the input data row. If the label is '-1', the tweet is considered negative; if the label is '1', the tweet is considered positive.\n\nYour task is to implement a Python function that processes a list of tweet data and categorizes the tweets based on their sentiment labels. The function should write the tweet content to the appropriate files and return the total count of positive and negative tweets.\n\nFunction Signature: `def process_tweets(tweet_data: List[Dict[str, str]]) -> Tuple[int, int]:`\n\nInput:\n- `tweet_data` (1 <= len(tweet_data) <= 1000): A list of dictionaries where each dictionary represents a tweet data row. Each dictionary contains the following key-value pairs:\n - 'text': A string representing the content of the tweet.\n - 'label': A string representing the sentiment label of the tweet ('-1' for negative, '1' for positive).\n\nOutput:\n- A tuple containing two integers:\n - The total count of positive tweets.\n - The total count of negative tweets.\n\nYou should write the tweet content to the following files based on their sentiment:\n- Negative tweets should be written to a text file named 'negative_sentiment.txt' and a CSV file named 'dataset_sentiment' with the sentiment label '-1'.\n- Positive tweets should be written to a text file named 'positive_sentiment.txt' and a CSV file named 'dataset_sentiment' with the sentiment label '1'.","solution":"```python\nfrom typing import List, Dict, Tuple\nimport csv\n\ndef process_tweets(tweet_data: List[Dict[str, str]]) -> Tuple[int, int]:\n positive_count = 0\n negative_count = 0\n\n for row in tweet_data:\n if row['label'] == '-1':\n write_tweet_txt(row['text'].strip(), 'negative_sentiment.txt')\n write_tweet_csv(row['text'].strip(), 'dataset_sentiment', '-1')\n negative_count += 1\n elif row['label'] == '1':\n write_tweet_txt(row['text'].strip(), 'positive_sentiment.txt')\n write_tweet_csv(row['text'].strip(), 'dataset_sentiment', '1')\n positive_count += 1\n\n return positive_count, negative_count\n\ndef write_tweet_txt(tweet: str, filename: str):\n with open(filename, 'a', encoding='utf-8') as file:\n file.write(tweet + '\\n')\n\ndef write_tweet_csv(tweet: str, filename: str, label: str):\n with open(filename + '.csv', 'a', newline='', encoding='utf-8') as file:\n writer = csv.writer(file)\n writer.writerow([tweet, label])\n\n# Example usage:\ntweet_data = [\n {'text': 'Great day!', 'label': '1'},\n {'text': 'Terrible experience!', 'label': '-1'},\n {'text': 'Feeling happy.', 'label': '1'},\n {'text': 'Disappointed with the service.', 'label': '-1'}\n]\n\npositive, negative = process_tweets(tweet_data)\nprint(f\"Positive tweets: {positive}, Negative tweets: {negative}\")\n```\nIn this solution, the `process_tweets` function iterates through the tweet data, categorizes the tweets based on their sentiment labels, writes the tweet content to the appropriate files, and returns the total count of positive and negative tweets. The `write_tweet_txt` and `write_tweet_csv` functions are used to write the tweet content to text and CSV files, respectively."} {"lang":"python","raw_index":119443,"index":35336,"seed":" if graph.stationInLine(st_dict['zhanming']):\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a function to determine if a given station is present in a subway line graph. The subway line graph is represented using an adjacency list, where each station is a key and its adjacent stations are stored in a list. You need to write a function that takes the subway line graph and a station name as input and returns whether the station is present in the graph or not.\n\nFunction Signature: \n```python\ndef station_in_line(graph: dict, station: str) -> bool:\n pass\n```\n\nExample:\nConsider the following subway line graph represented as an adjacency list:\n```python\nsubway_graph = {\n 'station1': ['station2', 'station3'],\n 'station2': ['station1', 'station4'],\n 'station3': ['station1', 'station5'],\n 'station4': ['station2', 'station6'],\n 'station5': ['station3', 'station6'],\n 'station6': ['station4', 'station5']\n}\n```\nThe function `station_in_line(subway_graph, 'station3')` should return `True`, as 'station3' is present in the graph.\n\nWrite the `station_in_line` function to solve this problem efficiently.","solution":"```python\ndef station_in_line(graph: dict, station: str) -> bool:\n return station in graph\n```\n\nThe solution defines the `station_in_line` function that takes the subway line graph represented as an adjacency list and a station name as input. It then checks if the station is present in the graph by using the `in` operator, which returns `True` if the station is a key in the graph, and `False` otherwise. This solution provides a straightforward and efficient way to determine the presence of a station in the subway line graph."} {"lang":"typescript","raw_index":72917,"index":1516,"seed":"export * from '.\/button.element';\nexport * from '.\/button-group.element';\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a module resolution algorithm for a simple JavaScript module system. The module system uses the `export` and `import` keywords to define and import modules. When a module is imported, the system should resolve the module path and return the corresponding module.\n\nYou are given a code snippet that demonstrates the export statements for two modules: `button.element` and `button-group.element`. Each module is exported from its respective file.\n\nYour task is to implement a function `resolveModulePath(importPath, availableModules)` that takes an import path and a map of available modules, and returns the resolved module. If the module is not found, the function should return `null`.\n\nThe `importPath` parameter is a string representing the path of the module to import. The `availableModules` parameter is a map where the keys are module paths and the values are the corresponding module objects.\n\nThe module paths are relative to the current module, and they may contain the following components:\n- `.\/` to indicate the current directory\n- `..\/` to move up one directory\n- Module names without any prefix, indicating a module in the same directory\n\nFor example, given the code snippet:\n```\nexport * from '.\/button.element';\nexport * from '.\/button-group.element';\n```\nThe available modules map would be:\n```\n{\n '.\/button.element': { \/* module object for button.element *\/ },\n '.\/button-group.element': { \/* module object for button-group.element *\/ }\n}\n```\n\nYou should implement the `resolveModulePath` function to correctly resolve the module path and return the corresponding module object, or `null` if the module is not found.\n\nWrite the `resolveModulePath` function and provide the resolved module for the import paths:\n1. `.\/button.element`\n2. `..\/utils\/helper`","solution":"```javascript\nfunction resolveModulePath(importPath, availableModules) {\n if (importPath in availableModules) {\n return availableModules[importPath];\n }\n\n const keys = Object.keys(availableModules);\n for (const key of keys) {\n if (importPath.startsWith(key)) {\n const remainingPath = importPath.substring(key.length);\n if (remainingPath.startsWith('\/')) {\n return resolveModulePath(remainingPath, availableModules);\n }\n }\n }\n\n return null;\n}\n\n\/\/ Example usage\nconst availableModules = {\n '.\/button.element': { \/* module object for button.element *\/ },\n '.\/button-group.element': { \/* module object for button-group.element *\/ },\n '..\/utils\/helper': { \/* module object for helper *\/ }\n};\n\nconsole.log(resolveModulePath('.\/button.element', availableModules)); \/\/ Output: { \/* module object for button.element *\/ }\nconsole.log(resolveModulePath('..\/utils\/helper', availableModules)); \/\/ Output: { \/* module object for helper *\/ }\n```"} {"lang":"swift","raw_index":144645,"index":1524,"seed":" }\n\n \n init(text: String? = nil, alignment: NSTextAlignment = .left, numberOfLines: Int = 0, style: Style = .regular) {\n super.init(frame: .zero)\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a custom initializer for a Swift class that represents a text label. The class, `TextLabel`, should have the following properties and requirements:\n\nProperties:\n- `text`: A string representing the text to be displayed. It should default to `nil`.\n- `alignment`: An enumeration representing the text alignment (`left`, `center`, or `right`). It should default to `.left`.\n- `numberOfLines`: An integer representing the maximum number of lines for the text. It should default to `0`, indicating no limit.\n- `style`: An enumeration representing the text style (`regular`, `bold`, `italic`, etc.). It should default to `.regular`.\n\nRequirements:\n- Implement a custom initializer for the `TextLabel` class that takes the following parameters:\n - `text` (defaulting to `nil`)\n - `alignment` (defaulting to `.left`)\n - `numberOfLines` (defaulting to `0`)\n - `style` (defaulting to `.regular`)\n- The initializer should set the class properties based on the provided parameters.\n\nYour task is to complete the implementation of the `TextLabel` class by adding the custom initializer as per the given requirements.","solution":"```swift\nenum NSTextAlignment {\n case left, center, right\n}\n\nenum Style {\n case regular, bold, italic\n}\n\nclass TextLabel {\n var text: String?\n var alignment: NSTextAlignment\n var numberOfLines: Int\n var style: Style\n\n init(text: String? = nil, alignment: NSTextAlignment = .left, numberOfLines: Int = 0, style: Style = .regular) {\n self.text = text\n self.alignment = alignment\n self.numberOfLines = numberOfLines\n self.style = style\n }\n}\n```"} {"lang":"python","raw_index":45993,"index":15846,"seed":" def __init__(self, origine, longueur=0, largeur=0):\n Forme.__init__(self,origine)\n self.longueur = longueur\n self.largeur = largeur\n def __str__(self):\n \"\"\" afficher le rectangle\"\"\"\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python class for representing rectangles. The class should have the following functionalities:\n\n1. Initialize a rectangle with its origin point and dimensions.\n2. Provide a method to calculate the area of the rectangle.\n3. Provide a method to calculate the perimeter of the rectangle.\n4. Provide a method to check if the rectangle is a square.\n5. Provide a method to display the details of the rectangle in a human-readable format.\n\nYou need to implement the class `Rectangle` with the following methods:\n\n- `__init__(self, origin, length=0, width=0)`: Initializes the rectangle with its origin point and dimensions.\n- `area(self)`: Returns the area of the rectangle.\n- `perimeter(self)`: Returns the perimeter of the rectangle.\n- `is_square(self)`: Returns True if the rectangle is a square, False otherwise.\n- `__str__(self)`: Returns a string representation of the rectangle in the format \"Rectangle: Origin at (x, y), Length: l, Width: w\".\n\nYou should assume that the `Forme` class is already defined with an `__init__` method that initializes the origin point of a shape.","solution":"```python\nclass Rectangle(Forme):\n def __init__(self, origin, length=0, width=0):\n super().__init__(origin)\n self.length = length\n self.width = width\n\n def area(self):\n return self.length * self.width\n\n def perimeter(self):\n return 2 * (self.length + self.width)\n\n def is_square(self):\n return self.length == self.width\n\n def __str__(self):\n return f\"Rectangle: Origin at ({self.origin.x}, {self.origin.y}), Length: {self.length}, Width: {self.width}\"\n```\n\nThis solution defines a `Rectangle` class that inherits from the `Forme` class and implements the required functionalities. The `area` method calculates the area of the rectangle, the `perimeter` method calculates the perimeter, the `is_square` method checks if the rectangle is a square, and the `__str__` method provides a human-readable representation of the rectangle."} {"lang":"python","raw_index":65770,"index":34359,"seed":"urlpatterns = [\n path('', home, name='api.home'),\n path('category\/', include('api.category.urls')),\n path('product\/', include('api.product.urls')),\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Python function that parses a list of URL patterns and returns a dictionary representing the hierarchical structure of the API endpoints. Each URL pattern is represented as a string, and the hierarchical structure should be based on the path components of the URLs.\n\nWrite a function called `parse_url_patterns` that takes a list of URL patterns as input and returns a dictionary representing the hierarchical structure of the API endpoints. The dictionary should have the following format:\n- Keys represent the path components of the URLs.\n- Values are either:\n - If the path component corresponds to a leaf endpoint, the value is the name of the endpoint.\n - If the path component corresponds to a nested endpoint, the value is another dictionary following the same format.\n\nFor example, given the following list of URL patterns:\n```python\nurlpatterns = [\n path('', home, name='api.home'),\n path('category\/', include('api.category.urls')),\n path('product\/', include('api.product.urls')),\n path('product\/detail\/', product_detail, name='api.product.detail'),\n path('category\/items\/', category_items, name='api.category.items'),\n]\n```\nThe function `parse_url_patterns(urlpatterns)` should return the following dictionary:\n```python\n{\n \"\": \"api.home\",\n \"category\": {\n \"\": \"api.category.items\"\n },\n \"product\": {\n \"\": \"api.product.detail\"\n }\n}\n```","solution":"```python\ndef parse_url_patterns(urlpatterns):\n api_structure = {}\n\n for pattern in urlpatterns:\n parts = pattern.split('\/')\n parts = [part for part in parts if part] # Remove empty parts\n\n current_level = api_structure\n for part in parts:\n if part not in current_level:\n current_level[part] = {}\n current_level = current_level[part]\n\n if 'name' in pattern:\n current_level[''] = pattern.split('name=')[1].split(')')[0]\n\n return api_structure\n```\n\nThe `parse_url_patterns` function iterates through the URL patterns, splits each pattern into its path components, and constructs the hierarchical structure of the API endpoints using a dictionary. If a path component corresponds to a leaf endpoint, the function assigns the endpoint name to the corresponding key in the dictionary. If a path component corresponds to a nested endpoint, the function creates a nested dictionary to represent the nested structure. The function then returns the hierarchical structure of the API endpoints as a dictionary."} {"lang":"python","raw_index":109958,"index":4458,"seed":"\tdata_lowlight = data_lowlight.permute(2,0,1)\n\tdata_lowlight = data_lowlight.cuda().unsqueeze(0)\n\n\n\tenhanced_image,params_maps = DCE_net(data_lowlight)\n\n\timage_path = image_path.replace('train_clip','train_clip_enhanced')\n\n\tresult_path = image_path\n\tif not os.path.exists(image_path.replace('\/'+image.split(\"\/\")[-1],'')):\n\t\tos.makedirs(image_path.replace('\/'+image_path.split(\"\/\")[-1],''))\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a project to enhance low-light images using a deep learning model. The code snippet provided is a part of the image enhancement process. The `data_lowlight` variable represents the low-light image data, and it undergoes some transformations before being passed to the `DCE_net` model for enhancement. After enhancement, the resulting image and parameter maps are stored in the `enhanced_image` and `params_maps` variables, respectively. The `image_path` variable holds the path of the original image, and the code replaces a part of the path to save the enhanced image in a different directory. Additionally, it creates the necessary directory if it does not exist.\n\nYour task is to implement a function that simulates the image enhancement process using the given code snippet. The function should take the low-light image data and the original image path as input and return the path where the enhanced image is saved.","solution":"```python\nimport os\n\ndef enhance_image(data_lowlight, image_path):\n # Assuming the DCE_net model and necessary imports are available\n\n # Perform necessary transformations on the low-light image data\n data_lowlight = data_lowlight.permute(2, 0, 1)\n data_lowlight = data_lowlight.cuda().unsqueeze(0)\n\n # Pass the low-light image data to the DCE_net model for enhancement\n enhanced_image, params_maps = DCE_net(data_lowlight)\n\n # Modify the image path to save the enhanced image in a different directory\n image_path = image_path.replace('train_clip', 'train_clip_enhanced')\n result_path = image_path\n\n # Create the necessary directory if it does not exist\n if not os.path.exists(image_path.replace('\/' + image_path.split(\"\/\")[-1], '')):\n os.makedirs(image_path.replace('\/' + image_path.split(\"\/\")[-1], ''))\n\n # Return the path where the enhanced image is saved\n return result_path\n```\n\nThe `enhance_image` function takes the low-light image data and the original image path as input. It performs the same transformations and enhancement process as described in the code snippet and returns the path where the enhanced image is saved."} {"lang":"php","raw_index":94524,"index":329,"seed":"

\n
\n <\/i>\n <\/div>\n
\n
<\/div>\n
Generados<\/strong><\/div>\n <\/div>\n <\/div>\n <\/div>\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a function to count the number of valid tickets generated for a given station on a specific day. The tickets are stored in a database, and the function `Ticket::contarTicketVigentesHoy($estacion_id)` is provided to retrieve the count of valid tickets for the given station on the current day. The function takes the station ID as a parameter and returns the count of valid tickets generated for that station on the current day.\n\nYour task is to implement a function `countValidTickets` that takes the station ID as input and returns the count of valid tickets generated for that station on the current day.\n\nFunction Signature:\n```php\nfunction countValidTickets($stationId) : int\n```\n\nExample:\nFor a given station ID `123`, the function call `countValidTickets(123)` should return the count of valid tickets generated for station `123` on the current day.\n\nAssume the existence of a database containing ticket information and that the `Ticket::contarTicketVigentesHoy($estacion_id)` function accurately retrieves the count of valid tickets for the given station on the current day.","solution":"```php\nfunction countValidTickets($stationId) : int {\n \/\/ Assuming Ticket::contarTicketVigentesHoy($estacion_id) retrieves the count of valid tickets for the given station on the current day\n return Ticket::contarTicketVigentesHoy($stationId);\n}\n```\n\nThe provided solution implements the `countValidTickets` function, which simply calls the `Ticket::contarTicketVigentesHoy($estacion_id)` function with the given station ID and returns the count of valid tickets for that station on the current day."} {"lang":"python","raw_index":27844,"index":28699,"seed":"\n if model_input_name not in user_shape_dict:\n raise Exception(\"Please specify all input layers in data_shape.\")\n input_tensors[model_input_name] = model_input_tensor\n return input_tensors\n\n def __get_output_tensors(self, subgraph):\n output_tensors = OrderedDict()\n model_outputs = subgraph.OutputsAsNumpy()\n for model_output in model_outputs:\n","openai_fingerprint":"fp_eeff13170a","problem":"You are working on a deep learning framework and need to implement a method to retrieve input and output tensors from a subgraph. The subgraph is represented as a collection of nodes and edges, and each node corresponds to a layer in a neural network model. Your task is to create a Python class method that takes the subgraph as input and returns a dictionary containing the input and output tensors of the model.\n\nYou are given a partial code snippet from the class that you need to complete. The `__get_input_tensors` method is responsible for retrieving input tensors from the subgraph, and the `__get_output_tensors` method is responsible for retrieving output tensors. You need to implement the `__get_output_tensors` method to iterate through the model outputs and populate the `output_tensors` dictionary with the corresponding tensors.\n\nComplete the `__get_output_tensors` method to iterate through the model outputs and populate the `output_tensors` dictionary with the corresponding tensors. Ensure that the method raises an exception if a model output is not found in the subgraph.\n\nYour task is to implement the `__get_output_tensors` method to achieve the desired functionality.","solution":"```python\ndef __get_output_tensors(self, subgraph):\n output_tensors = OrderedDict()\n model_outputs = subgraph.OutputsAsNumpy()\n for model_output in model_outputs:\n if model_output not in user_shape_dict:\n raise Exception(\"Please specify all output layers in data_shape.\")\n output_tensors[model_output] = model_output_tensor\n return output_tensors\n```\nIn the `__get_output_tensors` method, we iterate through the `model_outputs` obtained from the subgraph and check if each output is present in the `user_shape_dict`. If an output is not found, we raise an exception indicating that all output layers need to be specified in `data_shape`. Otherwise, we populate the `output_tensors` dictionary with the corresponding output tensors. Finally, we return the `output_tensors` dictionary containing the output tensors for the subgraph."} {"lang":"python","raw_index":21799,"index":17235,"seed":"todoapp\/todos\/models.py0\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.encoding import smart_text as smart_unicode\nfrom django.utils.translation import ugettext_lazy as _\n\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a Django model for a simple to-do application. The model should represent a to-do item with a title, description, completion status, and due date. Additionally, the model should include a method to mark the to-do item as complete. Below is a code snippet to get you started:\n\n```python\n# todoapp\/todos\/models.py\n\nfrom __future__ import unicode_literals\nfrom django.db import models\nfrom django.utils.encoding import smart_text as smart_unicode\nfrom django.utils.translation import ugettext_lazy as _\n\nclass TodoItem(models.Model):\n title = models.CharField(max_length=100)\n description = models.TextField()\n completed = models.BooleanField(default=False)\n due_date = models.DateField()\n\n def mark_as_complete(self):\n self.completed = True\n self.save()\n```\n\nYour task is to complete the `TodoItem` model by adding the necessary fields and method as described. Additionally, you need to ensure that the model is properly registered in the Django admin interface for easy management.","solution":"```python\n# todoapp\/todos\/models.py\n\nfrom __future__ import unicode_literals\nfrom django.db import models\nfrom django.utils.encoding import smart_text as smart_unicode\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib import admin\n\nclass TodoItem(models.Model):\n title = models.CharField(max_length=100)\n description = models.TextField()\n completed = models.BooleanField(default=False)\n due_date = models.DateField()\n\n def mark_as_complete(self):\n self.completed = True\n self.save()\n\nclass TodoItemAdmin(admin.ModelAdmin):\n list_display = ('title', 'description', 'completed', 'due_date')\n list_filter = ('completed', 'due_date')\n search_fields = ('title', 'description')\n\nadmin.site.register(TodoItem, TodoItemAdmin)\n```\n\nIn the solution, the `TodoItem` model is completed with the required fields and method. Additionally, a custom admin class `TodoItemAdmin` is created to customize the display and filtering options in the Django admin interface. Finally, the `TodoItem` model is registered with the custom admin class to enable easy management through the admin interface."} {"lang":"rust","raw_index":93788,"index":1573,"seed":"\/\/\/ * If the target element type is a different size from the current element\n\/\/\/ type, and the output slice wouldn't be a whole number of elements when\n\/\/\/ accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so\n\/\/\/ that's a failure).\n\/\/\/ * Similarly, you can't convert between a\n\/\/\/ [ZST](https:\/\/doc.rust-lang.org\/nomicon\/exotic-sizes.html#zero-sized-types-zsts)\n\/\/\/ and a non-ZST.\n","openai_fingerprint":"fp_eeff13170a","problem":"You are given a slice of elements of a certain type and a target element type. Your task is to implement a function `convert_slice` that converts the given slice to a new slice of the target element type, following the rules below:\n\n1. If the target element type is a different size from the current element type, and the output slice wouldn't be a whole number of elements when accounting for the size change, the function should return an error.\n2. Similarly, you can't convert between a Zero-Sized Type (ZST) and a non-ZST.\n\nThe function signature is:\n```rust\nfn convert_slice(input: &[T]) -> Result, String>\nwhere\n T: Sized,\n U: Sized,\n{\n \/\/ implementation goes here\n}\n```\n\nYour task is to implement the `convert_slice` function according to the specified rules.\n\nFor example, if the input slice is `[1, 2, 3]` of type `u16` and the target type is `u32`, the function should return `Ok(vec![1, 2, 3])` because 3 `u16` values can be converted to 3 `u32` values without any loss.\n\nHowever, if the input slice is `[1, 2, 3]` of type `u16` and the target type is `u8`, the function should return an error because 3 `u16` values cannot be converted to a whole number of `u8` values.","solution":"```rust\nfn convert_slice(input: &[T]) -> Result, String>\nwhere\n T: Sized,\n U: Sized,\n{\n let input_size = std::mem::size_of::();\n let output_size = std::mem::size_of::();\n\n if input_size % output_size != 0 || (input_size == 0) != (output_size == 0) {\n return Err(\"Invalid conversion\".to_string());\n }\n\n let input_len = input.len();\n let output_len = input_len * input_size \/ output_size;\n\n if output_len * output_size != input_len * input_size {\n return Err(\"Invalid conversion\".to_string());\n }\n\n let input_ptr = input.as_ptr() as *const U;\n let output_slice = unsafe { std::slice::from_raw_parts(input_ptr, output_len) };\n\n Ok(output_slice.to_vec())\n}\n```\n\nThis solution first checks if the size of the input and output types are compatible for conversion. If not, it returns an error. Then, it calculates the length of the output slice and performs the conversion using pointer manipulation. If the conversion is valid, it returns the converted slice; otherwise, it returns an error."} {"lang":"python","raw_index":40713,"index":30526,"seed":" f.save()\n\n s3 = boto3.client('s3',\n settings.AWS_REGION,\n endpoint_url=settings.AWS_S3_ENDPOINT_URL,\n aws_access_key_id=settings.AWS_ACCESS_KEY_ID,\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a Python function that interacts with Amazon S3 using the boto3 library. The function should upload a file to a specified S3 bucket. You are provided with a code snippet that attempts to achieve this, but it contains errors and omissions. Your task is to complete the function and handle potential exceptions that may occur during the file upload process.\n\nYou are given the following code snippet as a starting point:\n\n```python\nimport boto3\nfrom botocore.exceptions import ClientError\nimport settings\n\ndef upload_to_s3(file_path, bucket_name, object_name):\n \"\"\"\n Upload a file to an S3 bucket\n\n :param file_path: Path to the file to upload\n :param bucket_name: S3 bucket name\n :param object_name: S3 object name\n :return: True if the file was uploaded successfully, else False\n \"\"\"\n try:\n # Create an S3 client\n s3 = boto3.client('s3',\n region_name=settings.AWS_REGION,\n endpoint_url=settings.AWS_S3_ENDPOINT_URL,\n aws_access_key_id=settings.AWS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)\n\n # Upload the file\n with open(file_path, 'rb') as f:\n s3.upload_fileobj(f, bucket_name, object_name)\n\n return True\n except ClientError as e:\n # Handle the exception\n print(f\"An error occurred: {e}\")\n return False\n```\n\nYour task is to complete the `upload_to_s3` function to ensure that it correctly uploads the specified file to the given S3 bucket. Additionally, handle any potential exceptions that may occur during the upload process.","solution":"```python\nimport boto3\nfrom botocore.exceptions import ClientError\nimport settings\n\ndef upload_to_s3(file_path, bucket_name, object_name):\n \"\"\"\n Upload a file to an S3 bucket\n\n :param file_path: Path to the file to upload\n :param bucket_name: S3 bucket name\n :param object_name: S3 object name\n :return: True if the file was uploaded successfully, else False\n \"\"\"\n try:\n # Create an S3 client\n s3 = boto3.client('s3',\n region_name=settings.AWS_REGION,\n endpoint_url=settings.AWS_S3_ENDPOINT_URL,\n aws_access_key_id=settings.AWS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)\n\n # Upload the file\n with open(file_path, 'rb') as f:\n s3.upload_fileobj(f, bucket_name, object_name)\n\n return True\n except ClientError as e:\n # Handle the exception\n print(f\"An error occurred: {e}\")\n return False\n```\n\nThe provided solution completes the `upload_to_s3` function by creating an S3 client using the boto3 library and then uploading the specified file to the given S3 bucket. Additionally, it handles potential exceptions that may occur during the file upload process, ensuring that the function returns `True` if the file was uploaded successfully and `False` otherwise."} {"lang":"python","raw_index":74655,"index":31589,"seed":" body = {\"reason\": EarlyExitReason(reason).value}\n logger.info(f\"report_early_exit({reason})\")\n r = self._session.post(\n f\"\/api\/v1\/trials\/{self._trial_id}\/early_exit\",\n data=det.util.json_encode(body),\n )\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a class that handles early exits for a machine learning experiment. The provided code snippet is part of a larger system that interacts with an API to report an early exit from a trial. Your task is to complete the implementation of the `EarlyExitHandler` class by adding a method to report the early exit reason to the API.\n\nYou are given the following code snippet as a starting point:\n\n```python\nclass EarlyExitHandler:\n def __init__(self, session, trial_id):\n self._session = session\n self._trial_id = trial_id\n\n def report_early_exit(self, reason):\n # Your implementation here\n```\n\nYour task is to complete the `report_early_exit` method to send a POST request to the API endpoint `\/api\/v1\/trials\/{self._trial_id}\/early_exit` with the provided `reason` as the payload in the format `{\"reason\": reason}`. The `reason` should be converted to its corresponding enum value using `EarlyExitReason(reason).value` before sending the request.\n\nYou should use the `self._session` attribute to make the POST request and ensure that the `reason` is properly encoded as JSON in the request body.\n\nComplete the `report_early_exit` method to achieve the desired functionality.","solution":"```python\nimport det.util\n\nclass EarlyExitHandler:\n def __init__(self, session, trial_id):\n self._session = session\n self._trial_id = trial_id\n\n def report_early_exit(self, reason):\n body = {\"reason\": EarlyExitReason(reason).value}\n logger.info(f\"report_early_exit({reason})\")\n r = self._session.post(\n f\"\/api\/v1\/trials\/{self._trial_id}\/early_exit\",\n data=det.util.json_encode(body),\n )\n```\nIn the solution, the `report_early_exit` method is completed by constructing the request body with the reason in the required format and sending a POST request using the provided `session` attribute. The `reason` is converted to its corresponding enum value and then encoded as JSON before being included in the request body."} {"lang":"rust","raw_index":112413,"index":875,"seed":" stress_test::actor::{Actor, ActorError},\n};\n\n\/\/\/ An actor that kills minfs and destroys the ramdisk\npub struct InstanceActor {\n pub instance: Option<(Filesystem, FvmInstance)>,\n}\n\nimpl InstanceActor {\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with implementing a simplified version of an actor system in Rust. An actor is a concurrency primitive that encapsulates state and behavior, communicating exclusively through message passing. Your goal is to create a basic actor system that can handle messages and perform actions based on those messages.\n\nYou are provided with a partial code snippet for an `InstanceActor` struct, which represents an actor responsible for managing instances. The `InstanceActor` has an `instance` field that holds an optional tuple of `Filesystem` and `FvmInstance`. Your task is to complete the implementation of the `InstanceActor` by adding message handling functionality.\n\nYour task is to implement the following methods for the `InstanceActor` struct:\n1. `new`: A constructor method that creates a new `InstanceActor` with no instance initially.\n2. `receive_message`: A method that takes a message as input and performs actions based on the message. The messages that need to be handled are:\n - `StartInstance`: If the actor receives this message and it currently has no instance, it should create a new instance and store it in the `instance` field.\n - `StopInstance`: If the actor receives this message and it currently has an instance, it should stop and remove the instance from the `instance` field.\n - `GetStatus`: If the actor receives this message, it should return the status of the instance (e.g., running, stopped, or not found).\n\nYou should also define an enum `InstanceMessage` to represent the different types of messages that the `InstanceActor` can receive.\n\nYour implementation should adhere to the following guidelines:\n- Use the provided code snippet as a starting point and complete the implementation of the `InstanceActor` struct.\n- Define the `InstanceMessage` enum with variants for the different types of messages mentioned above.\n- Implement the `new` constructor method for the `InstanceActor` struct.\n- Implement the `receive_message` method to handle the different types of messages and perform the required actions.\n\n```rust\nuse std::fmt;\n\n\/\/ Define the InstanceMessage enum to represent different types of messages\nenum InstanceMessage {\n StartInstance,\n StopInstance,\n GetStatus,\n}\n\n\/\/ Implement the InstanceActor struct\npub struct InstanceActor {\n pub instance: Option<(Filesystem, FvmInstance)>,\n}\n\nimpl InstanceActor {\n \/\/ Implement the new constructor method for InstanceActor\n pub fn new() -> Self {\n InstanceActor { instance: None }\n }\n\n \/\/ Implement the receive_message method to handle different types of messages\n pub fn receive_message(&mut self, message: InstanceMessage) -> Result {\n match message {\n InstanceMessage::StartInstance => {\n if self.instance.is_none() {\n \/\/ Create a new instance and store it in the instance field\n self.instance = Some((Filesystem::new(), FvmInstance::new()));\n Ok(\"Instance started\".to_string())\n } else {\n Err(\"Instance already exists\".to_string())\n }\n }\n InstanceMessage::StopInstance => {\n if let Some(_) = self.instance {\n \/\/ Stop and remove the instance from the instance field\n self.instance = None;\n Ok(\"Instance stopped\".to_string())\n } else {\n Err(\"No instance to stop\".to_string())\n }\n }\n InstanceMessage::GetStatus => {\n \/\/ Return the status of the instance\n match &self.instance {\n Some(_) => Ok(\"Instance running\".to_string()),\n None => Ok(\"Instance not found\".to_string()),\n }\n }\n }\n }\n}\n```","solution":"```rust\nuse std::fmt;\n\n\/\/ Define the InstanceMessage enum to represent different types of messages\nenum InstanceMessage {\n StartInstance,\n StopInstance,\n GetStatus,\n}\n\n\/\/ Implement the InstanceActor struct\npub struct InstanceActor {\n pub instance: Option<(Filesystem, FvmInstance)>,\n}\n\nimpl InstanceActor {\n \/\/ Implement the new constructor method for InstanceActor\n pub fn new() -> Self {\n InstanceActor { instance: None }\n }\n\n \/\/ Implement the receive_message method to handle different types of messages\n pub fn receive_message(&mut self, message: InstanceMessage) -> Result {\n match message {\n InstanceMessage::StartInstance => {\n if self.instance.is_none() {\n \/\/ Create a new instance and store it in the instance field\n self.instance = Some((Filesystem::new(), FvmInstance::new()));\n Ok(\"Instance started\".to_string())\n } else {\n Err(\"Instance already exists\".to_string())\n }\n }\n InstanceMessage::StopInstance => {\n if let Some(_) = self.instance {\n \/\/ Stop and remove the instance from the instance field\n self.instance = None;\n Ok(\"Instance stopped\".to_string())\n } else {\n Err(\"No instance to stop\".to_string())\n }\n }\n InstanceMessage::GetStatus => {\n \/\/ Return the status of the instance\n match &self.instance {\n Some(_) => Ok(\"Instance running\".to_string()),\n None => Ok(\"Instance not found\".to_string()),\n }\n }\n }\n }\n}\n```"} {"lang":"swift","raw_index":7834,"index":3313,"seed":"let aboutUpdateURL = getAboutUpdateURL() ?? \"\"\n\n\/\/ userExperience\nlet userExperienceProfile = nudgeDefaults.dictionary(forKey: \"userExperience\")\n","openai_fingerprint":"fp_eeff13170a","problem":"You are tasked with creating a function that processes user experience data and generates a URL for an about page update. The function should handle the possibility of a missing or invalid input and produce the correct URL based on the provided data.\n\nYou are given the following code snippet as a reference:\n```swift\nlet aboutUpdateURL = getAboutUpdateURL() ?? \"\"\n\n\/\/ userExperience\nlet userExperienceProfile = nudgeDefaults.dictionary(forKey: \"userExperience\")\n```\nThe `getAboutUpdateURL()` function returns an optional string representing the URL for the about page update. If the function returns `nil`, the default empty string should be used.\n\nThe `userExperienceProfile` variable contains a dictionary retrieved from the `nudgeDefaults` storage, representing the user's experience profile.\n\nYour task is to create a function `generateAboutPageURL` that takes the user experience profile as input and returns the appropriate about page update URL. If the user experience profile is missing or invalid, the function should return the default empty string.","solution":"```swift\nfunc generateAboutPageURL(userExperienceProfile: [String: Any]?) -> String {\n guard let aboutUpdateURL = getAboutUpdateURL() else {\n return \"\"\n }\n \n guard let userExperience = userExperienceProfile else {\n return \"\"\n }\n \n \/\/ Process user experience data and generate URL based on the profile\n \/\/ Example logic:\n if let experienceLevel = userExperience[\"experienceLevel\"] as? String {\n if experienceLevel == \"beginner\" {\n return aboutUpdateURL + \"\/beginner\"\n } else if experienceLevel == \"intermediate\" {\n return aboutUpdateURL + \"\/intermediate\"\n } else if experienceLevel == \"advanced\" {\n return aboutUpdateURL + \"\/advanced\"\n }\n }\n \n \/\/ Default URL if no specific logic applies\n return aboutUpdateURL\n}\n```\n\nIn the solution, the `generateAboutPageURL` function takes the `userExperienceProfile` as an optional dictionary. It first checks if the `aboutUpdateURL` is available, using the nil-coalescing operator to provide a default empty string if it's missing. Then, it verifies the presence of the user experience profile. If the profile is valid, it processes the data to generate the appropriate about page update URL based on the user's experience level. If the profile is missing or invalid, the function returns the default empty string."} {"lang":"php","raw_index":15717,"index":72,"seed":" <\/i> Add <\/a> \n <\/div>\n