[lang] | php [raw_index] | 36068 [index] | 553 [seed] | Route::get('/', function () { [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a simple web application using the Laravel framework. Your goal is to implement a route that handles HTTP GET requests to the root URL ("/") and returns a specific response. The response should include a JSON object containing information about a fictional product. You [solution] | ```php Route::get('/', function () { $product = [ 'name' => 'Smartphone X', 'price' => 599.99, 'availability' => 'In Stock' ]; return response()->json($product); }); ``` In the solution, we define an associative array `$product` containing the name, price, and av
[lang] | python [raw_index] | 34787 [index] | 19942 [seed] | def memcached_status(request): return view(request) [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a simplified version of a caching system similar to Memcached. Your goal is to create a Python class that can store key-value pairs in memory and provide methods for retrieving, adding, and removing items from the cache. Your task is to implement the `Memcached` cla [solution] | ```python class Memcached: def __init__(self): self.cache = {} def set(self, key, value, ttl): self.cache[key] = (value, time.time() + ttl) def get(self, key): if key in self.cache: value, expiry = self.cache[key] if time.time() < expiry:
[lang] | python [raw_index] | 126048 [index] | 13771 [seed] | for i in range(len(a)): a[i] = list(a[i]) return a [openai_fingerprint] | fp_eeff13170a [problem] | You are given a list of strings, where each string represents a word. Your task is to write a function that converts each word in the list into a list of characters and returns the modified list. Write a function `convert_to_char_list(words)` that takes in a list of strings `words` and returns a mo [solution] | ```python def convert_to_char_list(words): return [list(word) for word in words] ``` The function `convert_to_char_list` takes in a list of strings `words` and uses a list comprehension to iterate through each word and convert it into a list of characters. The resulting list of lists is then re
[lang] | python [raw_index] | 65025 [index] | 25707 [seed] | template=imps.PLT_TA_STYLE_TEMPLATE, colorway=imps.PLT_TA_COLORWAY, title=title, title_x=0.1, title_font_size=14, dragmode="pan", ) imagefile = "ta_adosc.png" # Check if interactive settings are enabled plt_link = "" [openai_fingerprint] | fp_eeff13170a [problem] | You are working on a financial data visualization project and need to create a Python script to generate a technical analysis plot for the Accumulation/Distribution Oscillator (ADOSC). The code snippet provided is a part of the script that sets up the plot's style, colorway, title, and interactive s [solution] | ```python import pandas as pd import plotly.express as px def calculate_adosc(df): high = df['high'] low = df['low'] close = df['close'] volume = df['volume'] ad = ((close - low) - (high - close)) / (high - low) adosc = ad * volume adosc = adosc.rolling(window=14).mean(
[lang] | python [raw_index] | 56415 [index] | 37526 [seed] | self.filterIp = filterIp self.ipFilterId = ipFilterId self.memo = None [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a memoization technique for a function that filters IP addresses based on a given filter ID. The code snippet provided initializes three instance variables: `filterIp`, `ipFilterId`, and `memo`. The `filterIp` variable holds a reference to the IP filtering function, [solution] | ```python class IPFilterMemoization: def __init__(self, filterIp, ipFilterId): self.filterIp = filterIp self.ipFilterId = ipFilterId self.memo = None def memoize_filter_ip(self): if self.memo is None: self.memo = {} if self.ipFilterId not
[lang] | python [raw_index] | 103917 [index] | 26748 [seed] | for s in strings: counts[s] += 1 print(counts) [openai_fingerprint] | fp_eeff13170a [problem] | You are given a list of strings. Your task is to write a Python function that takes this list as input and returns a dictionary containing the count of occurrences of each unique string in the list. The function signature is: ```python def count_string_occurrences(strings: List[str]) -> Dict[str, i [solution] | ```python from typing import List, Dict def count_string_occurrences(strings: List[str]) -> Dict[str, int]: counts = {} for s in strings: if s in counts: counts[s] += 1 else: counts[s] = 1 return counts ``` The `count_string_occurrences` function
[lang] | csharp [raw_index] | 37941 [index] | 4368 [seed] | int additionalBonus = int.Parse(Console.ReadLine()); if (studentsCount == 0 || lecturesCount == 0) { Console.WriteLine($"Max Bonus: 0."); Console.WriteLine($"The student has attended 0 lectures."); [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a program to calculate the bonus points for students based on their attendance and performance in lectures. The bonus points are calculated using the following formula: `(total bonus points = (student attendance / total lectures) * (5 + additional bonus))`. If the studen [solution] | ```csharp using System; class Program { static void Main() { int studentAttendance = int.Parse(Console.ReadLine()); int totalLectures = int.Parse(Console.ReadLine()); int additionalBonus = int.Parse(Console.ReadLine()); double bonusPoints = CalculateBonusPoi
[lang] | cpp [raw_index] | 42803 [index] | 989 [seed] | payload->validation_code = MHYPROT_ENUM_PROCESS_THREADS_CODE; payload->process_id = process_id; payload->owner_process_id = process_id; if (!request_ioctl(MHYPROT_IOCTL_ENUM_PROCESS_THREADS, payload, alloc_size)) { free(payload); return false; } // / [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function to retrieve information about the threads associated with a given process using a custom driver interface. The provided code snippet is part of a larger system that interacts with a kernel driver to perform this task. Your goal is to create a function that [solution] | ```c #include <stdbool.h> #include <stdlib.h> // Structure for the payload typedef struct { int validation_code; int process_id; int owner_process_id; } Payload; // Function to send IOCTL command to the driver extern bool request_ioctl(int command, Payload* payload, size_t size); int
[lang] | csharp [raw_index] | 94146 [index] | 949 [seed] | <reponame>MarcosCostaDev/IntegrationTest using IntegrationTest.Core.Command; using IntegrationTest.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IntegrationTest.Domain.Commands.Results { public cla [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a method to calculate the total amount of an invoice based on the items and their quantities. The `InvoiceCommandResults` class contains a list of `InvoiceItem` objects, each representing an item on the invoice. Each `InvoiceItem` has a `Name` property representing t [solution] | ```csharp using System; using System.Collections.Generic; namespace IntegrationTest.Domain.Commands.Results { public class InvoiceCommandResults { public List<InvoiceItem> Items { get; set; } public decimal CalculateTotalAmount(Dictionary<string, decimal> itemPrices)
[lang] | python [raw_index] | 46454 [index] | 13347 [seed] | async def start(): await http_connection.start_connection() [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python class that manages asynchronous HTTP connections. Your class should include a method to start the connection and a method to stop the connection. Additionally, you need to implement a mechanism to ensure that the connection is only started once and can be stoppe [solution] | ```python import asyncio class AsyncHTTPManager: def __init__(self): self.connection_started = False async def start_connection(self): if not self.connection_started: print("Starting HTTP connection") # Simulating asynchronous connection start
[lang] | python [raw_index] | 149793 [index] | 34137 [seed] | self.sku_p100d = models.Sku.objects.get(variant='P100D') self.sku_70 = models.Sku.objects.get(variant='70') self.owner_tyrell = models.Owner.objects.get() self.organization_ecorp = models.Organization.objects.get() [openai_fingerprint] | fp_eeff13170a [problem] | You are working on a car rental management system that includes models for SKUs (car variants), owners, and organizations. The code snippet provided initializes instances of SKUs and their respective owners and organizations. Your task is to create a function that calculates the total rental cost fo [solution] | ```python class Sku: def __init__(self, variant, rental_cost): self.variant = variant self.rental_cost = rental_cost class Owner: def __init__(self, organization=None): self.organization = organization class Organization: def __init__(self, discount=0):
[lang] | python [raw_index] | 84913 [index] | 21683 [seed] | 'description': 'Corpo de Deus', 'locale': 'pt-PT', 'notes': '', 'region': '', 'type': 'NRV' }, { 'date': '2018-06-10', 'description': 'Dia de Portugal', 'locale': 'pt-PT', 'notes': '', 'region': '', 'type [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a program to parse and analyze a dataset containing information about public holidays in different locales. Each entry in the dataset is represented as a dictionary with the following keys: 'date', 'description', 'locale', 'notes', 'region', and 'type'. The 'date' key ho [solution] | ```python def find_holidays_by_locale(dataset, target_locale): holidays_in_locale = [holiday for holiday in dataset if holiday['locale'] == target_locale] sorted_holidays = sorted(holidays_in_locale, key=lambda x: x['date']) return sorted_holidays ```
[lang] | typescript [raw_index] | 94535 [index] | 4942 [seed] | : text} </Tag> ); }; export default ReadingTime; [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a function that calculates the reading time of a given text. The reading time is defined as the estimated time it takes for an average reader to read the text. For the purpose of this problem, assume that an average reader reads at a speed of 200 words per minute. You a [solution] | ```javascript // Function to calculate the reading time based on the number of words in the text const calculateReadingTime = (text) => { // Split the text into words using whitespace as the delimiter const words = text.split(/\s+/); // Calculate the estimated reading time in minutes (round
[lang] | php [raw_index] | 40525 [index] | 1480 [seed] | declare(strict_types=1); namespace SetBased\Stratum\SqlitePdo\Test; /** * Test cases for inserting a row. */ [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function that validates the correctness of a given namespace declaration in a PHP code snippet. The namespace declaration must adhere to the following rules: 1. The namespace declaration must be enclosed within a `declare(strict_types=1);` statement. 2. The namespa [solution] | ```php function validateNamespaceDeclaration(string $code): bool { $lines = explode("\n", $code); $strictTypesFound = false; $namespaceFound = false; foreach ($lines as $line) { $trimmedLine = trim($line); if (strpos($trimmedLine, 'declare(strict_types=1);') === 0) {
[lang] | php [raw_index] | 47783 [index] | 2584 [seed] | 5 => '', 6 => '', 7 => '', ]; public static $exelHeader = [ 1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a class that represents a spreadsheet. The class should have a method to convert a given column number into its corresponding column label, similar to how columns are labeled in Excel. You are provided with a code snippet that includes a partial implementation of th [solution] | ```php class Spreadsheet { public static $exelHeader = [ 1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', // ... more mappings ]; public static function getColumnLabel($columnNumber) { $label =
[lang] | python [raw_index] | 13609 [index] | 33418 [seed] | from datadog.util.compat import is_p3k from tests.unit.api.helper import ( DatadogAPIWithInitialization, [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function that checks if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. You are given the following code snippet [solution] | ```python def is_palindrome(s): # Remove spaces and punctuation, and convert to lowercase s = ''.join(e for e in s if e.isalnum()).lower() # Check if the string is equal to its reverse return s == s[::-1] ``` The `is_palindrome` function first removes spaces and punctuation fro
[lang] | python [raw_index] | 128321 [index] | 6096 [seed] | print table [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a program that generates a multiplication table for a given number. The program should take an integer input `n` and output a multiplication table for the numbers 1 through 10 multiplied by `n`. The table should be neatly formatted and displayed in a clear, readable mann [solution] | ```python def generate_multiplication_table(n): print(f"Multiplication Table for {n}:") for i in range(1, 11): print(f"{i} x {n} = {i * n}") # Example usage generate_multiplication_table(5) ```
[lang] | python [raw_index] | 115463 [index] | 15996 [seed] | _Titles = List[str] _Text = Tuple[_Titles, _Alineas] _LabelizedText = Tuple[_Text, Set[TopicName]] def _build_labelized_text(raw_text: Tuple[int, List[str], List[Dict]], labels: Set[TopicName]) -> _LabelizedText: text = raw_text[1], [EnrichedString.from_dict(dict_) for dict_ in raw_text[2]] [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function to process a dataset of texts and their corresponding labels. The dataset is represented as a list of tuples, where each tuple contains an integer identifier, a list of strings representing the text, and a list of dictionaries. Each dictionary in the list [solution] | ```python from typing import List, Tuple, Dict, Set _Titles = List[str] _Alineas = List[str] _LabelizedText = Tuple[Tuple[_Titles, _Alineas], Set[str]] class EnrichedString: @classmethod def from_dict(cls, data: Dict) -> 'EnrichedString': # Implementation of EnrichedString.from_d
[lang] | typescript [raw_index] | 36737 [index] | 331 [seed] | </> ) } export default Header [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function that checks whether a given string represents a valid HTML tag. In HTML, a tag is considered valid if it follows the syntax rules for opening and closing tags. An opening tag starts with `<` followed by the tag name and ends with `>`, while a closing tag s [solution] | ```typescript function isValidHTMLTag(tag: string): boolean { const openingTagRegex = /^<([a-zA-Z_][\w-]*)>$/; const closingTagRegex = /^<\/([a-zA-Z_][\w-]*)>$/; if (openingTagRegex.test(tag)) { return true; } else if (closingTagRegex.test(tag)) { return true; } else { return
[lang] | csharp [raw_index] | 12882 [index] | 1144 [seed] | } catch (PackagingException) { threwPackagingException = true; } // Assert Assert.True(threwPackagingException); } } [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a unit test for a method that is expected to throw a specific exception under certain conditions. The code snippet provided is a part of a unit test written in C# using the xUnit testing framework. The test method is checking whether the expected exception, `Packagin [solution] | ```csharp // Solution for the implementation of the ProcessPackage method public class PackageProcessor { public void ProcessPackage(Package package) { // Example condition: If the package weight is negative, throw PackagingException if (package.Weight < 0) {
[lang] | python [raw_index] | 104040 [index] | 23484 [seed] | params = { [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function that takes a dictionary of parameters and their values as input and returns a formatted string representing the parameters in a URL query string format. The URL query string format consists of key-value pairs separated by '&' and each key-value pair is sep [solution] | ```python def format_query_string(params: dict) -> str: formatted_params = [] for key, value in params.items(): formatted_key = str(key).replace(' ', '%20') formatted_value = str(value).replace(' ', '%20') formatted_params.append(f"{formatted_key}={formatted_value}")
[lang] | python [raw_index] | 33072 [index] | 29016 [seed] | mock_args = mock.MagicMock() expected_fields = ('name', 'endpoint', 'public_endpoint', 'username', 'password') ret = WebProcessingServiceForm(mock_args) self.assertEqual(WebProcessingService, ret.Meta.model) self.assertEqual(expected_fields, ret.Meta.fields) [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python form class for a web processing service. The form should be designed to handle specific fields and their corresponding widgets and labels. Your task is to implement the `WebProcessingServiceForm` class according to the given requirements. The `WebProcessingServ [solution] | ```python from django import forms from yourapp.models import WebProcessingService class WebProcessingServiceForm(forms.ModelForm): class Meta: model = WebProcessingService fields = ['name', 'endpoint', 'public_endpoint', 'username', 'password'] widgets = { '
[lang] | cpp [raw_index] | 77697 [index] | 1683 [seed] | // the cable index is not valid // LEGACY const cable_segment* cable(index_type index) const; // LEGACY const std::vector<segment_ptr>& segments() const; [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with refactoring a legacy codebase that includes a class representing a cable with segments. The legacy code provides two member functions for accessing cable segments: `cable` and `segments`. The `cable` function returns a pointer to a cable segment given an index, and the `segments` [solution] | ```cpp #include <vector> #include <memory> // Define the modernized Cable class class Cable { public: // Define the cable segment type using SegmentPtr = std::shared_ptr<CableSegment>; // Constructor and other member functions can be added as per requirements // Return a pointer t
[lang] | rust [raw_index] | 94886 [index] | 3232 [seed] | /// The take-profit-limit order. Unused for now. TakeProfitLimit, /// The limit-maker order. Unused for now. LimitMaker, /// Fallback for all other variants. #[serde(other)] Other, } impl ToString for OrderType { fn to_string(&self) -> String { match self { [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a custom `ToString` trait for a Rust enum called `OrderType`. The `OrderType` enum represents different types of orders in a financial trading system. Your goal is to implement the `to_string` method for the `OrderType` enum, which converts each variant to its corres [solution] | ```rust impl ToString for OrderType { fn to_string(&self) -> String { match self { OrderType::Limit => "LIMIT".to_string(), OrderType::Market => "MARKET".to_string(), OrderType::TakeProfitLimit | OrderType::LimitMaker => "UNUSED".to_string(),
[lang] | python [raw_index] | 99738 [index] | 2082 [seed] | partition_access=False) def open(self, **kwargs): return 'open_worked' # Don't actually use this plugin [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a Python class that simulates a file system plugin. The plugin is responsible for providing access to a specific partition of a file system. Your goal is to complete the implementation of the `FileSystemPlugin` class by adding the necessary methods to handle partitio [solution] | ```python class FileSystemPlugin: def __init__(self, partition_access=False): self.partition_access = partition_access def open(self, **kwargs): return 'open_worked' # Don't actually use this plugin ``` The provided solution completes the implementation of the `FileSystemPl
[lang] | cpp [raw_index] | 81674 [index] | 673 [seed] | Arguments: Context - Pointer to the context to query GetExpirationTime - If TRUE return the expiration time. [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function that retrieves the expiration time from a given context. The function takes in a pointer to the context and a boolean flag indicating whether to retrieve the expiration time. If the flag is set to TRUE, the function should return the expiration time; other [solution] | ```c long long RetrieveExpirationTime(void* Context, int GetExpirationTime) { if (GetExpirationTime) { // Assuming the expiration time is stored in the context // Replace the following line with the actual logic to retrieve the expiration time long long expirationTime = *
[lang] | php [raw_index] | 9684 [index] | 1230 [seed] | <?php namespace Dotdigitalgroup\Email\Controller\Product; class Upsell extends \Dotdigitalgroup\Email\Controller\Edc { [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a PHP class that handles the upselling of products for an email marketing system. The class should extend a base controller and include methods for retrieving and processing upsell products. Your task is to complete the `Upsell` class by implementing the following m [solution] | ```php <?php namespace Dotdigitalgroup\Email\Controller\Product; class Upsell extends \Dotdigitalgroup\Email\Controller\Edc { // Retrieve a list of upsell products based on the input product ID public function getUpsellProducts($productId) { // Simulated implementation: Return
[lang] | python [raw_index] | 138327 [index] | 15874 [seed] | import reporter from reporter import Reporter [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a custom reporting system for a company's sales data. The system should be able to generate various types of reports based on the sales data and provide insights to the management team. To achieve this, you need to create a class called `SalesReporter` that utilizes [solution] | ```python from typing import List, Dict, Union import reporter class SalesReporter: def __init__(self, report_type: str): self.report_type = report_type def fetch_sales_data(self) -> List[Dict[str, Union[str, int]]]: # Assume this method fetches sales data from the company'
[lang] | typescript [raw_index] | 117892 [index] | 297 [seed] | <filename>boilerplate/app/screens/createScreen/nativeBase.ts import { connectState } from "@app/state" import { connectStyle } from "native-base" export default (name: string, Component: any) => { return connectStyle(name + "Screen", {})(connectState(Component)) } [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a higher-order function in TypeScript that takes a name and a component as input and returns a wrapped component using the `connectStyle` and `connectState` functions from the `native-base` and `@app/state` libraries, respectively. Your task is to complete the imple [solution] | ```typescript type ComponentType = any; // Define the correct type for the component function createWrappedComponent(name: string, Component: ComponentType): ComponentType { const connectedStyleComponent = connectStyle(name + "Screen", {})(Component); return connectState(connectedStyleComponent
[lang] | python [raw_index] | 60275 [index] | 27979 [seed] | resp = client.delete(f"/message/{json_data['id']}") assert resp.status_code == 200 def test_invalid_delete_message_by_id(client): resp = client.delete(f"/message/0") assert resp.status_code == 204 [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python function that interacts with a messaging API to handle message deletion. The API is accessed through an HTTP client, and the function should be designed to delete a message by its ID. The function should handle both valid and invalid scenarios, and appropriate a [solution] | ```python def delete_message_by_id(client, message_id): # Send a DELETE request to the messaging API endpoint resp = client.delete(f"/message/{message_id}") # Assert the status code of the response based on the message deletion result if resp.status_code == 200: # If the mes