query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function that processes a list of software packages and their attributes. Each package is represented as a dictionary containing the package name, a list of required libraries, and an optional flag. The function should filter the list of packages based on certain criteria and return t...
```python from typing import List def filter_packages(packages, required_lib, optional_flag) -> List[str]: filtered_packages = [] for package in packages: if required_lib in package['libraries'] and package['optional'] == optional_flag: filtered_packages.append(package['name']) return f...
magicoder
python
You are tasked with implementing a simple HTTP caching mechanism for a web application. The application is built using the Symfony framework, and the caching will be handled within the `httpcacheActions` class. The goal is to improve the performance of the application by caching the responses for specific actions. The...
```php class httpcacheActions extends sfActions { public function executePage1(sfWebRequest $request) { $cacheKey = 'page1_' . $request->getUri(); // Generate a unique cache key based on the request URI $cache = $this->getContext()->getViewCacheManager(); // Get the view cache manager if ($cache->has($...
magicoder
php
You are given a code snippet that calculates the last ten digits of the sum of the series 1^1 + 2^2 + 3^3 + ... + 1000^1000. Your task is to write a function that efficiently computes the last ten digits of the sum of the series for any given maximum number. Write a Python function `last_ten_digits_of_series(max_digit...
```python def last_ten_digits_of_series(max_digits): sum = 0 for i in range(1, max_digits+1): sum += pow(i, i, 10**10) # Using modular exponentiation to efficiently calculate last ten digits return str(sum)[-10:] ``` The solution defines a function `last_ten_digits_of_series` that iterates through...
magicoder
python
You are working as a DevOps engineer for a company that manages a PostgreSQL database. As part of your responsibilities, you need to create a script to automate the backup process for the PostgreSQL database. The company's security policy requires that the backup process be secure and controlled. You have been provided...
```bash #!/bin/bash # Check if the required environment variables are set if [ -z "${db_user}" ]; then echo "Error: Environment variable 'db_user' is not set." >> backup.log exit 1 fi # Perform the database backup /usr/bin/pg_dump -Fc -U "${db_user}" -h localhost -d pgdatabase > pgdatabase.sql.dump 2>> backup.log...
magicoder
shell
You are tasked with creating a Python function that processes and extracts relevant information from HTML content using XPath and map functions. Your function should take an HTML response object and return a list of stripped text from specific elements within the HTML. Write a Python function `extract_description_text...
```python from scrapy import Selector def extract_description_text(response, element_type): if element_type not in ["td", "p"]: raise ValueError("Invalid element_type. It must be 'td' or 'p'.") selector = Selector(text=response.body) if element_type == "td": extracted_text = map(unicode.st...
magicoder
python
You are tasked with implementing a reinforcement learning algorithm using PyTorch to train a neural network model. The given code snippet is a part of a larger reinforcement learning framework. The `tanh` function is applied to the output of a fully connected layer (`fc_1`) followed by a softmax function applied to the...
```python @classmethod def train_model(cls, net, transitions): states, actions, rewards, masks = transitions.state, transitions.action, transitions.reward, transitions.mask optimizer = torch.optim.Adam(net.parameters()) # Initialize the optimizer # Convert states, actions, and rewards to PyTorch tensors ...
magicoder
python
You are working on a machine learning framework that involves tiling input data for prediction. The `_predict_with_tiling_impl` function is responsible for making predictions using a tiling strategy, and the `_predict_sample` function is used to handle predictions with either padding or tiling, but not both. Your task ...
```python def predict_with_padding_and_tiling(prediction_pipeline, inputs, outputs, padding, tile_shapes, halos, verbose): if padding and tile_shapes and halos: raise ValueError("Simultaneous padding and tiling with halos is not supported") if padding: # Perform prediction with padding ...
magicoder
python
You are tasked with creating a program to manage incoming messages from different queues using the RabbitMQ messaging system. Your program should be able to handle messages from three different types of queues: CallQueue, MessageQueue, and DistributionListQueue. You are provided with a code snippet that initializes a R...
```csharp // Event handler for CallQueue messages private void OnCallQueueReceived(object sender, QueueMessageEventArgs e) { // Process the incoming message from the CallQueue // Add your implementation here progress.Report(1, $"Received message from CallQueue: {e.Message}"); } // Event handler for Message...
magicoder
csharp
You are tasked with implementing a simple texture manager in Rust. The given code snippet is part of a `TextureManager` struct, which is responsible for managing textures identified by unique IDs. The `insert_texture` method is used to add a new texture to the manager, associating it with a given ID. The `get_texture` ...
```rust struct TextureManager<T> { textures: std::collections::HashMap<usize, T>, } impl<T> TextureManager<T> { fn new() -> Self { TextureManager { textures: std::collections::HashMap::new(), } } fn insert_texture(&mut self, id: usize, texture: T) { self.textures.in...
magicoder
rust
You are tasked with implementing a program to train a multi-layer perceptron (MLP) deep neural network (DNN) using TensorFlow for image classification. The given code snippet initializes the TensorFlow session, creates a summary writer for visualizing the graph, and sets up a training loop to iterate through multiple e...
```python import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Load the MNIST dataset mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # Define the neural network architecture input_size = 784 # MNIST images are 28x28 pixels hidden1_size = 256 hidden2_size = 256 output_s...
magicoder
python
You are tasked with creating a program to calculate the temperature, pressure, density, and speed of sound at a given altitude using the International Standard Atmosphere (ISA) model. The ISA model is valid for altitudes up to 84,852 meters. Your program should take the altitude (h) as input and perform the following...
```python import math class Econst: R = 287.05 # Gas constant for air in J/(kg*K) def calculate_atmosphere_properties(h): if h < 0 or h > 84852: print('International Standard Atmosphere Calculations cannot be used for values above 84,852m') else: T = 288.15 - 0.0065 * h # Temperature cal...
magicoder
python
You are tasked with creating a Rust module that manages address spaces and calling conventions for a virtual machine. The module should provide a public interface for accessing the functionality related to address spaces and calling conventions. Your task is to implement the `AddressSpace` and `CallingConvention` modu...
```rust // address_space.rs pub struct AddressSpace { // Implementation details for memory management } impl AddressSpace { pub fn new() -> Self { // Initialize address space AddressSpace { // Initialize memory management data structures } } pub fn read_memory(&self...
magicoder
rust
You are tasked with implementing a simplified version of a module builder for a programming language. The module builder is responsible for managing bindings, scopes, and generating code for a compiler. The provided code snippet is a part of the module builder implementation and contains two methods: `next_index` and `...
```rust // ModuleBuilder struct to manage bindings, scopes, and code generation struct ModuleBuilder { compiling: Vec<Function>, // Assuming Function is a defined type } impl ModuleBuilder { // Constructor method to create a new ModuleBuilder instance fn new() -> Self { ModuleBuilder { ...
magicoder
rust
You are tasked with implementing a configuration update mechanism for a speech processing system. The given code snippet is a part of a Python class method responsible for updating a YAML configuration file with speech-related settings. The method `update_yaml_file` takes several parameters: section (str), key (str), v...
```python import yaml def update_speech_config(section, key, value, flag1, flag2): # Load the existing YAML configuration file with open('config.yaml', 'r') as file: config = yaml.safe_load(file) # Update the configuration based on the provided parameters and flags if flag1: config[sec...
magicoder
python
You are tasked with implementing a Python function that simulates the process of signal interpolation using NumPy. Signal interpolation is a method used to estimate the values of a signal at non-integer sample positions based on the known values at integer sample positions. In this problem, you are given the frequency ...
```python import numpy as np def interpolate_signal(frequency_range, freqs, cuda_res, numpy_res, idx): # Calculate the absolute values of the original signal cuda_res_abs = np.abs(cuda_res) numpy_res_abs = np.abs(numpy_res) # Interpolate the real parts of the original signal values at the given fr...
magicoder
python
You are tasked with creating a Python function that processes a list of Magic: The Gathering cards and their printings. Each card has a name, mana cost, and type line, and each printing has a corresponding image URL. Your function should take the list of cards and printings as input and return a dictionary where the ke...
```python def generate_card_image_dict(cards, printings): card_image_dict = {card['name']: [] for card in cards} for printing in printings: card_name = printing['card']['name'] if card_name in card_image_dict: card_image_dict[card_name].append(printing['image_url']) ret...
magicoder
python
You are tasked with creating a Python class that manages a simple menu system for a graphical user interface (GUI) application. The class should include methods for initializing the user interface, setting the window size, displaying a status message, and creating a menu with an exit action. Your task is to complete t...
```python from PyQt5.QtWidgets import QMainWindow, QAction, QApplication from PyQt5.QtGui import QIcon class GUIManager(QMainWindow): def __init__(self, icons): super().__init__() self.icons = icons self.init_ui() def init_ui(self): self.resize(400, 600) self.statusBar(...
magicoder
python
You are tasked with implementing a custom class that handles the retrieval and manipulation of data from a YAML file. The class should have an `__init__` method that reads the data from the "text.yml" file and stores it in an attribute called `data`. Additionally, the class should have a `__getattr__` method that takes...
```python # Sample usage of the CustomYAMLHandler class handler = CustomYAMLHandler() # Assuming "text.yml" contains the following data: # data: # person: # name: "John Doe" # age: 30 # location: # city: "New York" # country: "USA" # Accessing data using attribute names print(handler.data) # Outp...
magicoder
python
You are tasked with implementing a Vector class in Python that supports basic vector operations and unit conversions. The Vector class should be able to perform addition, subtraction, multiplication, and division with other vectors or scalar values. Additionally, it should support unit conversions for vectors using the...
```python import pint ureg = pint.UnitRegistry() class Vector: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __add__(self, other): if isinstance(other, Vector): return Vector(self.x + other.x, self.y + other.y, self.z + other.z) elif isin...
magicoder
python
You are tasked with implementing a file tree monitoring service in TypeScript. The `FileTreeService` class contains a private method `fsWatch$` that is responsible for updating the tree information of a given workspace when changes occur. The method takes an argument `tws` of type `ITreeWorkSpace` and is expected to ut...
```typescript import * as fs from 'fs'; interface ITreeWorkSpace { // Define the properties of the workspace tree } class FileTreeService { private fsWatcher: fs.FSWatcher | null = null; /** * 変更が行われた場合は引数`ITreeWorkSpace`のツリー情報を更新を行う。 * * @private * @param {ITreeWorkSpace} tws 監視対象ワークスペース情報 * @m...
magicoder
typescript
You are tasked with implementing a validation system for a partner creation form in a web application. The code snippet provided is a part of a validation chain that uses a fluent interface to validate various properties of the partner object. The `->that()` method is used to specify the value to be validated, followed...
```php class PartnerValidator { private $partnerData = []; private $validationRules = []; public function setName($name) { $this->partnerData['name'] = $name; return $this; } public function setUrl($url) { $this->partnerData['url'] = $url; return $this; ...
magicoder
php
You are working on a project that involves manipulating RDF (Resource Description Framework) data using Python's `rdflib` library. The code snippet provided is a part of the RDF manipulation process. Your task is to write a Python function that takes in a dictionary of variables and generates RDF triples based on the p...
```python import rdflib from rdflib import RDF, Literal, XSD from rdflib.namespace import Namespace def generate_rdf_triples(variables_dict): rdf = rdflib.Graph() sio = Namespace("http://semanticscience.org/resource/SIO_") obo = Namespace("http://purl.obolibrary.org/obo/") DCTERMS = Namespace("http://...
magicoder
python
You are tasked with implementing a function that processes a given Swift code snippet to extract and analyze the properties and methods being used. Your function should identify and categorize the different elements present in the code snippet, such as variable assignments, method calls, and property settings. The co...
```swift func analyzeCodeSnippet(_ codeSnippet: String) -> [String: [String]] { var variableAssignments: [String] = [] var propertySettings: [String] = [] var methodCalls: [String] = [] let lines = codeSnippet.components(separatedBy: .newlines) for line in lines { let trimmedLine =...
magicoder
swift
You are tasked with implementing a function that sends a request to update a user's profile information using the provided code snippet as a reference. You are given the following code snippet as a starting point: ```javascript export const ProfileInformationRequest = async ({ loginData, setError }: any) => request(...
```javascript export const ProfileInformationRequest = async ({ loginData, setError }: any) => { const profileUpdateData = { // Provide the data to update the user's profile information // Example: firstName: loginData.firstName, lastName: loginData.lastName, email: loginData.email, // Add any...
magicoder
javascript
You are tasked with implementing a non-maximum suppression (NMS) algorithm for peak detection in a 2D array. The given code snippet is a part of a larger program that processes a 2D array `peaks` to identify and suppress non-maximum values. The `peaks` array represents the detected peaks in a radar signal processing ap...
```python import numpy as np def cfar_nms(peaks, range_az, threshold): # Perform non-maximum suppression suppressed_peaks = np.copy(peaks) for i in range(1, peaks.shape[0] - 1): for j in range(1, peaks.shape[1] - 1): if peaks[i, j] >= threshold and peaks[i, j] > peaks[i-1, j-1] and peak...
magicoder
python
You are tasked with creating a function that takes a `dto` struct as input and returns a `chrono::DateTime` object. The `dto` struct contains the following fields: - `datetime2`: A struct with the fields `date`, `time`, `scale`, and `offset`. - `date`: A struct with the field `days`. - `time`: A struct with the fie...
```rust use chrono::{NaiveDate, NaiveTime, NaiveDateTime, FixedOffset, DateTime, Duration}; fn convert_to_datetime(dto: Dto) -> DateTime<FixedOffset> { let date = NaiveDate::from_ordinal(1, dto.datetime2.date.days() as i32); let ns = dto.datetime2.time.increments as i64 * 10i64.pow(9 - dto.datetime2.time.scale...
magicoder
rust
You are tasked with implementing a Battleship game in C#. The game consists of a `BattleshipGameState` class and a `BattleshipGame` class. The `BattleshipGameState` class represents the state of the game, including the board and the ships. The `BattleshipGame` class contains the game logic and methods for playing the g...
```csharp public void Show(BattleshipGameState state) { char[,] board = new char[state.BoardSize, state.BoardSize]; // Initialize the board with empty spaces for (int i = 0; i < state.BoardSize; i++) { for (int j = 0; j < state.BoardSize; j++) { board[i, j] = ' '; } ...
magicoder
csharp
You are tasked with implementing a password manager class in Python. The password manager should allow users to store, retrieve, and delete passwords for various accounts. The passwords should be encrypted for security purposes. You need to implement the `PasswordManager` class with the following methods: 1. `__init__...
```python from cryptography.fernet import Fernet class PasswordManager: def __init__(self, master_password: str): key = Fernet.generate_key() self.cipher_suite = Fernet(key) self.master_key = key def _encrypt_password(self, password: str) -> bytes: return self.cipher_suite.encr...
magicoder
python
You are tasked with implementing a simple recommender system using Python. The system will generate recommendations based on user interests and a set of candidate items. The recommendations will be generated using a simple exploration algorithm. You are given a class `Recommender` with the following methods: - `__init...
```python from typing import List import random class Recommender: def __init__(self, env_config: dict): self.num_candidates = env_config['num_candidates'] self.slate_size = env_config['slate_size'] self.resample_documents = env_config['resample_documents'] self.seed = env_config['s...
magicoder
python
You are tasked with implementing a program that processes a series of commands to manipulate a binary tree. The binary tree is initially empty, and the program supports the following operations: 1. Insert a node into the binary tree. 2. Search for a node in the binary tree. 3. Delete a node from the binary tree. 4. Pr...
```python class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: ...
magicoder
python
You are tasked with implementing a custom Swing component that extends a JPanel. This component should have the following requirements: 1. Overwrite the addMouseListener() method to do nothing. 2. Add a mouse event on mousePressed by calling super.addMouseListener(). 3. Replace the UIActionMap for the keyboard event. ...
```java import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; public class CustomPanel extends JPanel { public CustomPanel() { super.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { ...
magicoder
java
You are given a C++ program that includes two header files, "dominance_pruning.h" and "pattern_database.h". The program also includes several standard C++ libraries. Your task is to implement a function that utilizes the functionalities provided by these header files to solve a specific problem. You need to implement ...
```cpp #include "dominance_pruning.h" #include "pattern_database.h" int findMinimumAfterPruning(const vector<int>& input) { // Apply dominance pruning to reduce the search space vector<int> prunedInput = dominancePruning(input); // Use pattern database heuristic to estimate the cost to reach the goal stat...
magicoder
cpp
You are tasked with creating a Python class to represent news articles. The class should have attributes for the article's ID, category, title, URL, image URL, description, and date. Additionally, you need to implement a method that calculates the age of the news article in days based on the current date. Create a cla...
```python from datetime import datetime class News: def __init__(self, id, category, title, url, image_url, description, date): self.id = id self.category = category self.title = title self.url = url self.image_url = image_url self.description = description s...
magicoder
python
You are tasked with creating a function to determine whether casting an integer one increment above the maximum value of a 64-bit integer to a byte will result in an overflow. An overflow occurs when the value being assigned to a variable is outside the range that the variable can represent. Write a function `CheckInt...
```csharp using System; public class OverflowChecker { public static bool CheckIntegerOverflow() { long int64MaxValue = long.MaxValue; int oneIncrementAboveMax = checked((int)(int64MaxValue + 1)); try { byte byteValue = checked((byte)oneIncrementAboveMax); } ...
magicoder
csharp
You are tasked with implementing a simple linear regression model using Python. Your goal is to create a class that can fit the model to a given dataset using the ordinary least squares method. The class should have a `fit` method that takes input features `X` and target values `y`, and then calculates the coefficients...
```python import numpy as np class SimpleLinearRegression: def fit(self, X, y): ones = np.ones((X.shape[0], 1)) X = np.concatenate((ones, X), axis=1) self.w_ = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y) self.cost_ = self.calculate_cost(X, y, self.w_) def calculate_cost(self, X, ...
magicoder
python
You are tasked with creating a function that processes account balance data and generates projections for future account balances. The function is triggered by messages in a queue and is required to return the generated projections to another queue for further processing. Your task is to implement the `GetAccountBalan...
```csharp using SFA.DAS.Forecasting.Messages.Projections; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace SFA.DAS.Forecasting.Projections.Functions { public class GetAccountBalanceFunction { [FunctionName("GetAccountBalanceFunction")] p...
magicoder
csharp
You are tasked with implementing a Python class that manages threads and exceptions. Your class should include a method to raise an exception in a separate thread. The code snippet provided gives a starting point for the implementation. Your task is to complete the class by adding the necessary methods and logic to ach...
```python import ctypes import threading class ThreadManager: def __init__(self): # Initialize any necessary attributes or variables pass def raise_exception(self): thread_id = threading.get_ident() res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(Sy...
magicoder
python
You are tasked with creating a Python program to manage a list of generations in a family tree. The program should allow users to add, delete, and display generations using a graphical user interface (GUI). The GUI should include a label, a scrollable list, and a scrollbar. Your task is to implement the functionality ...
```python from tkinter import * def add_generation(): generation = entry.get() if generation: listNodes.insert(END, generation) entry.delete(0, END) def delete_generation(): selected_index = listNodes.curselection() if selected_index: listNodes.delete(selected_index) window = ...
magicoder
python
You are tasked with implementing a Python function that processes the response from an API call and handles potential errors. The function should take a response object `resp` as input and perform the following steps: 1. If the `resp.text` attribute is not empty, encode it to UTF-8, ignoring any errors, and then decode...
```python import os import signal def process_response(resp, count, crawler): try: if resp.text: api_result = resp.text.encode('utf-8', 'ignore').decode('utf-8') crawler.info(resp.headers) else: count += 1 return count except Exception as e: ...
magicoder
python
You are tasked with creating a Python decorator that logs the execution time of a function and reports it to a monitoring system. The decorator should use Redis as the connection for the monitoring system and should be compatible with RQ (Redis Queue) for asynchronous job execution. Your task is to implement the `moni...
```python import time from functools import wraps from redis import Redis from rq import Queue def monitor_execution_time(name, tags, id_): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) exe...
magicoder
python
You are tasked with creating a reinforcement learning algorithm to train an agent to play a simple game. The game environment provides observations in the form of `obs_v` and expects actions in the form of `act_v`. The neural network model `net` is used to predict actions based on the observations. The training process...
```python from datetime import datetime, timedelta start_time = datetime.now() while True: optimizer.zero_grad() output = net(obs_v) loss = loss_fun(output, act_v) loss.backward() optimizer.step() print(f'epoch:{i} loss:{loss.item():.3f} mean:{rewards_mean:.0f}') if rewards_mean > 475: ...
magicoder
python
You are tasked with creating a program that extracts the unique domain names from a list of URLs. A domain name is the part of a URL that identifies the IP address to which it corresponds. For example, in the URL "https://edition.cnn.com/travel/food-and-drink", the domain name is "cnn.com". Write a function or method ...
```python from urllib.parse import urlparse def extract_domain_names(urls): unique_domains = set() for url in urls: parsed_url = urlparse(url) domain = parsed_url.netloc if domain.startswith("www."): domain = domain[4:] # Remove "www." prefix unique_domains.add(doma...
magicoder
python
You are tasked with implementing a module system for a programming language. The module system should allow for the import and use of external code and scripts within a program. The code snippet provided is a part of the module system, where two items are being re-exported from the `code` and `script` modules. Your ta...
To implement the module system, you can create a module structure that allows for importing and re-exporting items. Here's a possible solution using Rust as an example: ```rust // Define a module structure to hold imported items mod module { pub mod code { pub struct ExternCode; } pub mod script {...
magicoder
rust
You are tasked with creating a web application that manages team activation status. The application is built using the Laravel framework and follows the MVC (Model-View-Controller) architecture. The provided code snippet is from the `laravel_advanced` repository, specifically the view file for team activation status. ...
```php // Team.php (Model) namespace App; use Illuminate\Database\Eloquent\Model; class Team extends Model { protected $fillable = ['activated']; } ``` ```php // TeamController.php (Controller) namespace App\Http\Controllers; use App\Team; use Illuminate\Http\Request; class TeamController extends Controller { ...
magicoder
php
You are tasked with creating a program that counts the occurrences of each character in a given input string. Your program should take the input string from standard input and output the count of each character in the following format: "character: count". The input string may contain alphanumeric characters, symbols, a...
```go package main import ( "bufio" "fmt" "os" "strings" "unicode" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter the input string: ") input, _ := reader.ReadString('\n') charCount := make(map[rune]int) for _, char := range strings.ToLower(input) { if unicode.IsLetter(char) { ch...
magicoder
go
You are tasked with implementing a Python program to process a file containing genomic data related to snarls and their traversals. The input file contains tab-separated values, and the program is expected to read this file, process the data, and write the results to an output file. The output file should contain speci...
```python from collections import Counter # Function to calculate contig coverage for each snarl traversal def calculate_contig_coverage(input_file, output_file): traversals = {} # Dictionary to store traversals for each snarl with open(input_file) as infile, open(output_file, "w") as outfile: outfile...
magicoder
python
You are tasked with creating a program to visualize data in a grid format. The program should take in a list of years and display the data in a grid, with a specified number of columns and optional horizontal spacing. Additionally, the program should have the option to print the grid. Write a function `visualize_data`...
```python import math def visualize_data(year_list, ncol, horizontal_spacing=0.1, print_grid=False): r = 1 # initiate row c = 1 # initiate column for yr in year_list: if c == ncol + 1: c = 1 ro = math.ceil(r / ncol) # visualize the data in the grid format...
magicoder
python
You are tasked with creating a user authentication system using FastAPI and a database. Your goal is to implement a function that handles user login requests and verifies the user's credentials. The provided code snippet is a part of the FastAPI application and demonstrates the login endpoint. The endpoint receives a P...
```python async def login(body: OAuth2PasswordRequestForm = Depends()): query = User.select().where(User.c.username == body.username) user = await db.fetch_one(query=query) if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.") ...
magicoder
python
You are tasked with implementing a class that calculates the value of a sine wave at a specific time. The class `SineWave` has a method `at_time` that takes a time value as input and returns the value of the sine wave at that time. Additionally, the class `TimeElapsed` is used to keep track of the elapsed time. Your ta...
```python import math class SineWave: def __init__(self): pass def at_time(self, time): return math.sin(time) # Calculate the value of the sine wave at the given time class TimeElapsed: def __init__(self): self.elapsed_time = 0 def get(self): return self.elapsed_time...
magicoder
python
You are tasked with creating a Java program to analyze a given source code file and count the occurrences of specific keywords within the file. The program should read the source code file, identify the package name, and then count the occurrences of the keywords "extends", "implements", and "import" within the file. T...
```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SourceCodeAnalyzer { public static void main(String[] args) { String fileName = "path_to_source_file.java"; // Replace with the actual ...
magicoder
java
You are given a code snippet that calculates the number of combinations (n choose r) for 1 ≤ n ≤ 100, such that the value of n choose r is greater than or equal to 1,000,000. The code snippet uses factorials and a nested loop to iterate through the values of n and r to find the count of such combinations. Your task is...
```python from math import factorial def count_combinations(): ans = 0 for n in range(1, 101): for r in range(1, n+1): if factorial(n) / (factorial(r) * factorial(n-r)) >= 1000000: ans += 1 return ans ``` The `count_combinations` function calculates the number of combin...
magicoder
python
You are tasked with creating a Python function that simulates a simplified version of the `check_X_y` function from the `sklearn.utils.validation` module. The `check_X_y` function is typically used to validate and preprocess input data and target values for machine learning models. Your task is to create a function cal...
```python import numpy as np def custom_check_X_y(X, y): if len(X) != len(y): raise ValueError("X and y must have the same length") if len(X.shape) == 1: X = X.reshape(-1, 1) if len(y.shape) == 1: y = y.reshape(-1, 1) return X, y ``` The `custom_check_X_y` functi...
magicoder
python
You are tasked with implementing a simple comment loading feature for a social media application. The application uses Combine framework to handle asynchronous operations. You are provided with a code snippet from the `CommentLoader` class, which is responsible for loading comments and notifying the presenter when the ...
```swift import Combine class CommentLoader { private var cancellable: AnyCancellable? weak var presenter: CommentPresenter? func loadComments() { let commentPublisher = Future<[String], Error> { promise in // Simulate asynchronous comment loading DispatchQueue.global().asy...
magicoder
swift
You are given a 2D grid of size 20001x20001, initially filled with zeros. The grid has a central point at coordinates (10000, 10000). You are also given a series of movements represented by pairs of integers (ax, ay), where ax and ay represent the change in x and y coordinates, respectively. Starting from the central p...
```python from typing import List, Tuple def simulateMovements(movements: List[Tuple[int, int]]) -> List[List[int]]: grid = [[0] * 20001 for _ in range(20001)] cx, cy, step = 10000, 10000, 0 for ax, ay in movements: cx += ax cy += ay step += 1 if grid[cx][cy] == 0: # Mark t...
magicoder
python
You are working on a web application that displays data from a database table. The code snippet provided is a part of the backend logic for handling data retrieval and filtering. The snippet includes variable assignments, conditional checks, and database queries using SQLAlchemy. Your task is to implement a function t...
```python from typing import List, Dict, Any def process_filtered_data(dt_start: int, dt_order_col: int, dt_search: str, column_list: List[str], user_type: str, dt_length: int, dt_order_dir: str) -> List[Dict[str, Any]]: dt_start = int(dt_start) dt_order_col = int(dt_order_col) if dt_search != '': ...
magicoder
python
You are tasked with implementing a function to generate a preview image from a given file. The function should take a `File` or `Blob` object as input and return a Promise that resolves to a string representing the data URL of the preview image. The function should create a canvas element, set its dimensions to a maxi...
```typescript private previewImage(file: File | Blob): Promise<string> { return new Promise((resolve, reject) => { const maxPreviewSize = 1024; const canvas = this.document.createElement('canvas'); canvas.width = maxPreviewSize; canvas.height = maxPreviewSize; canvas.style.cssText = `position: fix...
magicoder
typescript
You are tasked with implementing a Java method that calculates the time difference between two given timestamps in milliseconds. The timestamps are represented as strings in the format "yyyy-MM-dd HH:mm:ss.SSS". You are required to handle potential exceptions that may occur during the parsing of the timestamps. Write ...
```java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class TimeDifferenceCalculator { public static long calculateTimeDifference(String timestamp1, String timestamp2) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:m...
magicoder
java
You are tasked with implementing a simple queue data structure in Rust. A queue is a linear data structure that follows the First In First Out (FIFO) principle, where elements are inserted at the rear and removed from the front. Your task is to create a queue using a linked list and implement various operations on it. ...
```rust use std::ptr; struct Node<T> { value: T, next: Option<Box<Node<T>>>, } pub struct Queue<T> { head: Option<Box<Node<T>>>, tail: *mut Node<T>, } impl<T> Queue<T> { pub fn new() -> Self { Queue { head: None, tail: ptr::null_mut() } } pub fn enqueue(&mut self, value: T) { ...
magicoder
rust
You are working on a system that tracks and manages risks associated with different departments in an organization. The provided code snippet is a part of a larger system that updates the risk level for a specific department and risk category based on certain input parameters. The code snippet also involves caching the...
```python def updateRiskLevel(level, risks, result, cache, gauge_full, deptRiskLevelMap): risk = risks[int(result['risk']) - 1] key = (result['dept'], risk, result['start'], result['end']) cache[key] = level dept = result['dept'] gauge_full.labels(dept=dept, risk=risk, startZ=result['start'], endZ=...
magicoder
python
You are tasked with implementing a custom view layout in a Swift iOS application. The layout should consist of a stack view containing a title label and an image view. The stack view should be aligned to the center of its superview, with the title label having a maximum of two lines, centered text alignment, and the ab...
```swift import UIKit class CustomView: UIView { private let stackView = UIStackView() private let titleLabel = UILabel() private let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { ...
magicoder
swift
You are working on a font manipulation program that involves adding glyphs and components to font masters. The program uses a font object with a `glyphs` attribute to store glyphs and a `masters` list to store font masters. Each glyph has a name and can have one or more components added to it. Components are represente...
```python def add_component_to_masters(glyph_name, component_name, position): for idx, master in enumerate(font.masters): comp_name = component_name.upper() component = GSComponent(comp_name, position) font.glyphs[glyph_name].components.append(component) return font ``` In the solution, ...
magicoder
python
You are tasked with implementing a program to perform cross-validation for different regression models on various datasets. The code snippet provided is a part of this program and involves iterating through datasets and models to obtain information for cross-validation. The program has a list of datasets called `Datas...
```python # Import necessary libraries from sklearn.model_selection import cross_val_score from sklearn.linear_model import LinearRegression, Lasso, Ridge from sklearn.datasets import load_boston, load_diabetes import numpy as np # Define the list of datasets and models Datasets = [load_boston(), load_diabetes()] Mode...
magicoder
python
You are tasked with implementing a neural network model using PyTorch to classify images of handwritten digits from the MNIST dataset. The provided code snippet gives a brief explanation of the `nn.Sequential()` module in PyTorch, which allows for the sequential stacking of neural network layers. Your task is to creat...
```python import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.utils.data import DataLoader # Define the neural network model using nn.Sequential model = nn.Sequential( nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), ...
magicoder
python
You are tasked with implementing a method to calculate the instant forward rate for a given time period in a financial context. The instant forward rate is a measure of the interest rate for a very short period of time, often approaching zero. It is used in financial modeling and derivative pricing. The method `instant...
```python import sympy as sp class FinancialModel: def instant_forward_rate(self, t): # Assuming P(t) is given as a function or data # For the purpose of this solution, let's assume P(t) is a given function # Replace P(t) with the actual function or data representing the price of a zero-cou...
magicoder
python
You are tasked with implementing a function to determine if a given pattern matches a string. The function should return true if the pattern matches the string, and false otherwise. A pattern is a string consisting of unique characters, and the input string is a space-separated sequence of words. You need to implement...
```python class Solution: def word_pattern(self, pattern: str, str: str) -> bool: words = str.split(" ") if len(pattern) != len(words): return False pattern_map = {} word_map = {} for char, word in zip(pattern, words): if char not in ...
magicoder
python
You are working on a signal processing project and need to implement a whitening filter to remove correlated components from a given signal. The whitening filter involves computing the eigen decomposition of the covariance matrix of the input signal and then applying a transformation to whiten the signal. You are give...
The issue in the provided code snippet arises from the incorrect usage of the multiplication operator (*) when constructing the whitening filter matrix W. The correct operation for matrix multiplication in NumPy is the dot product, not the element-wise multiplication. Here's the corrected implementation for the whiten...
magicoder
python
You are tasked with analyzing the performance of a Python program using the `pstats` module. The `pstats` module provides a convenient interface for analyzing and visualizing profiling data generated by the Python `cProfile` module. The code snippet provided loads profiling data from a file named 'output.prof' and prin...
```python import pstats def top_n_functions(file_name, n): try: p = pstats.Stats(file_name) p.sort_stats('cumulative') top_functions = p.print_stats(n) return top_functions except FileNotFoundError: return "File not found" except Exception as e: return f"Erro...
magicoder
python
You are tasked with implementing a multi-threaded task management system in Rust. The system should allow for graceful termination of tasks within a specified timeout period. You are provided with a partial implementation of a `TaskManager` struct and its associated methods. The `TaskManager` struct has two atomic bool...
```rust use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; use std::time::Duration; struct TaskManager { is_stopping: Arc<AtomicBool>, is_force_stopped: Arc<AtomicBool>, } impl TaskManager { pub fn new() -> Self { TaskManager { is_stopping: Arc::new(AtomicBool::new(false)), ...
magicoder
rust
You are tasked with implementing a Python class that simulates an enumeration in C++. The class should support the creation of enum values and the retrieval of their corresponding integer values. Additionally, the class should allow for the iteration over all enum values. Your task is to complete the implementation of...
```python class Enum: def __init__(self): self._enum_map = {} def add_enum_value(self, name, value): self._enum_map[name] = value def get_enum_value(self, name): return self._enum_map.get(name) def __iter__(self): return iter(self._enum_map.items()) # Example usage en...
magicoder
python
You are tasked with creating a Python function that extracts version information and concatenates the contents of multiple files to generate a long description for a software package. Your function should replicate the behavior of the given code snippet. Your task is to implement a function `extract_version_and_descri...
```python import re import ast import codecs from typing import List, Tuple def extract_version_and_description(file_paths: List[str]) -> Tuple[str, str]: _version_re = re.compile(r'__version__\s+=\s+(.*)') version = '' longdesc = '' for file_path in file_paths: with open(file_path, 'rb') as f...
magicoder
python
You are tasked with implementing a function to generate a link for social authentication using the given parameters. The function should construct a URL based on the input parameters and return it as a result. You are given the following code snippet as a starting point: ```swift import Foundation final class GetLin...
```swift final class GetLinkForSocialAuthAPIProxy: LoginBaseAPIProxy { func getLinkForSocialAuth(providerName: String, clientId: Int, state: String, responseType: String, scope: String?, ...
magicoder
swift
You are given a code snippet representing a Rust macro invocation for creating SVG elements. Your task is to write a Rust function that parses this macro invocation and extracts the attributes and their corresponding values. The macro invocation is in the following format: ``` element_name![attrs!( At::from("attri...
```rust use std::collections::HashMap; fn parse_svg_macro(macro_invocation: &str) -> HashMap<String, String> { let mut attributes_map = HashMap::new(); let start_index = macro_invocation.find("!(").unwrap(); let end_index = macro_invocation.rfind(")").unwrap(); let attributes_str = &macro_invocation[...
magicoder
rust
You are tasked with implementing a custom doubly linked list in C++. The list should support the following operations: 1. `void push_back(int val)`: Adds a new node with the given value to the end of the list. 2. `void pop_back()`: Removes the last node from the list. 3. `void reverse()`: Reverses the order of the nod...
```cpp #include <iostream> using namespace std; class CustomList { private: struct Node { int data; Node* prev; Node* next; Node(int val) : data(val), prev(nullptr), next(nullptr) {} }; Node* head; Node* tail; public: CustomList() : head(nullptr), tail(nullptr) {} ...
magicoder
cpp
You are tasked with creating a program to analyze daily stock market data using box plots. A box plot is a graphical representation of the distribution of a dataset, showing the median, quartiles, and potential outliers. Your program should read in daily stock data, calculate the necessary statistics, and generate a bo...
```python import matplotlib.pyplot as plt import pandas as pd # Read daily stock data from file data = pd.read_csv('stock_data.txt', header=None, names=['Closing Prices']) # Calculate statistics median = data['Closing Prices'].median() q1 = data['Closing Prices'].quantile(0.25) q3 = data['Closing Prices'].quantile(0....
magicoder
python
You are tasked with creating a Python class that manages timesheets for leaders in an organization. The class should handle the creation and retrieval of timesheets for specific leaders and dates. Your task is to implement the `TimesheetManager` class with the following requirements: - The `TimesheetManager` class sho...
```python class TimesheetManager: def __init__(self, leader): self.leader = leader def get_timesheet(self, leader, date): timesheet = Timesheet.objects.for_leader_and_date(leader, date) if timesheet: return timesheet else: new_timesheet = Timesheet(leader...
magicoder
python
You are tasked with creating a script to automate the process of copying a source project directory to a destination directory and performing cleanup operations on the destination project. The script should handle the copying of the source project and the removal of specific files from the destination project. Your ta...
```bash #!/bin/bash # Define function to copy source project to destination directory function copy_source_project() { if [ -d "$SOURCE_PROJECT_DIR" ]; then cp -rf "$SOURCE_PROJECT_DIR" "$DEST_PROJECT_DIR" echo "Source project copied to destination directory." else echo "Source project ...
magicoder
shell
You are tasked with implementing a music playlist management system in Python. You need to create a class `music_list` that allows users to add music tracks to a playlist and play them using a music player. The `music_list` class should have a method `append_music` to add music tracks to the playlist. Each music track ...
```python from collections import deque class music_player: def __init__(self, music_list): self.music_list = music_list def open(self, sound): print(f"Playing {sound}") class music_list(object): def __init__(self): self.__music_list = deque() def append_music(self, sound, re...
magicoder
python
You are tasked with implementing a Python metaclass that enforces a specific naming convention for class attributes. The metaclass should ensure that any class using it has attributes with names ending in a specific suffix. Your task is to create the metaclass and demonstrate its usage with a sample class. Write a Pyt...
```python class AttributeNamingMeta(type): def __new__(cls, name, bases, dct): for attr_name in dct: if not attr_name.endswith('_attr') and not attr_name.startswith('__'): raise ValueError(f"Attribute name '{attr_name}' does not end with '_attr'") return super().__new__(c...
magicoder
python
You are tasked with creating a program that analyzes a given software license text to extract and count the permissions granted within it. The permissions are defined by specific keywords such as "use," "copy," "modify," "merge," "publish," "distribute," "sublicense," and "sell." Your program should read the license te...
```python def count_permissions(file_path): permissions = { "use": 0, "copy": 0, "modify": 0, "merge": 0, "publish": 0, "distribute": 0, "sublicense": 0, "sell": 0 } with open(file_path, 'r') as file: for line in file: for ...
magicoder
python
You are tasked with creating a custom directive in an Angular application. Your directive should change the background color of an element to yellow when the mouse hovers over it. Additionally, the directive should accept an input parameter to determine the color to change to, and it should also emit an event when the ...
```typescript // custom-highlight.directive.ts import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core'; @Directive({ selector: '[appCustomHighlight]' }) export class CustomHighlightDirective { @Input() highlightColor: string = 'yellow'; @Output() highlighted: EventEmitter...
magicoder
typescript
You are tasked with creating a function that validates a JSON Web Token (JWT) using a given secret key and a token. A JWT consists of three parts separated by dots: the header, the payload, and the signature. The signature is created by encoding the header and payload with the secret key using a specified algorithm (e....
```javascript // Import necessary functions from jwt.sh and config.sh source "../../config.sh" source "../../jwt.sh" function validateJWT(secretKey, token) { // Split the token into its three parts: header, payload, and signature const [header, payload, signature] = token.split('.'); // Encode the header and pa...
magicoder
javascript
You are tasked with creating a program to process an address book and store the contact information in a dictionary. The address book contains pairs of contact names and their corresponding phone numbers. If a contact name already exists in the dictionary, the program should concatenate the new phone number to the exis...
```python def process_addressbook_and_principals(addressbook, principals): current_addressbook_ctags = {} for contact, phone in addressbook: if contact not in current_addressbook_ctags: current_addressbook_ctags[contact] = str(phone) else: current_addressbook_ctags[c...
magicoder
python
You are given a Python code snippet that involves the use of a custom `vectors` class. Your task is to implement the `vectors` class and its methods to ensure that the code snippet runs as expected. The `vectors` class should support the following operations: 1. `resize(n)`: Resizes the vectors to have `n` elements, e...
```python class vectors: def __init__(self): self.elements = [] def resize(self, n): self.elements = [[] for _ in range(n)] def __len__(self): return len(self.elements) def __getitem__(self, i): return self.elements[i] def __setitem__(self, i, value): self...
magicoder
python
You are tasked with implementing a Python function that performs a specific data transformation and evaluation process for time series forecasting. The function takes in input data, applies a transformation, and then evaluates the forecasted values. Your task is to complete the implementation of the function by filling...
```python def transform_and_evaluate(X_test, Y_hat, Y_hats, mmn, len_test): """ Perform data transformation and evaluation for time series forecasting. Args: X_test (numpy.ndarray): Array of input test data. Y_hat (numpy.ndarray): Array of predicted values. Y_hats (list): List to store predicte...
magicoder
python
You are given a file containing a series of images in a specific format. The images are stored as a sequence of bytes, and the file begins with a 32-bit integer representing the number of columns in each image. Following this, the images are stored as a sequence of bytes, with each image being a 2D array of pixels. Eac...
```python import numpy as np def process_images(file_path, num_images, num_rows): with open(file_path, 'rb') as f: num_cols = np.fromfile(f, dtype=np.dtype('>i4'), count=1) images = np.fromfile(f, dtype=np.ubyte) images = images.reshape((num_images, num_rows * num_cols)).transpose() ...
magicoder
python
You are tasked with implementing a function that processes a list of nested objects and generates a formatted string representation of the object structure. Each object in the list may contain nested objects, and the output should reflect the hierarchical structure of the input. You are given a code snippet that uses ...
```java import java.util.List; import java.util.Map; public class ObjectFormatter { public static String formatObjects(List<Object> objects) { StringBuilder sb = new StringBuilder(); for (Object obj : objects) { if (obj instanceof Map) { formatMap((Map<?, ?>) obj, sb, 0)...
magicoder
java
You are tasked with implementing a player missile system for a 2D game. The system should allow the player to fire missiles at enemy targets. The player can fire multiple missiles simultaneously, and each missile should move in a straight line until it either reaches its maximum range or collides with an enemy target. ...
```csharp class PlayerMissileSystem : ClodoBehaviour { List<Missile> activeMissiles = new List<Missile>(); public override void OnUpdate() { UpdateMissiles(); } public void FireMissile(Vector2 targetPosition, float missileSpeed, float maxRange) { Missile newMissile = new Missile(transf...
magicoder
csharp
You are tasked with implementing a contact management system using Python. The system should support adding, deleting, changing, and searching for contacts. Each contact will have a name, phone number, and birthday. The contact information will be stored in a file using a specific format. Your task is to implement the...
```python class ContactManagementSystem: def __init__(self, file_path): self.file_path = file_path def add_contact(self, name, phone, birthday): with open(self.file_path, 'a') as file: string = f'{name}=%$#={phone}=%$#={birthday}' file.write(f'{string}\n') def delet...
magicoder
python
You are tasked with implementing a PHP class that interacts with an API endpoint. The endpoint provides methods for retrieving data based on specific criteria. Your task is to create a class that implements the `EndpointInterface` and provides the necessary functionality to interact with the API. You need to implement...
```php class YourEndpointClass implements EndpointInterface { private $apiBaseUrl; public function __construct($apiBaseUrl) { $this->apiBaseUrl = $apiBaseUrl; } public function get($id, array $params = array(), $function = null) { $url = $this->apiBaseUrl . '/' . $id; if (!emp...
magicoder
php
You are working at a toy store and need to create a program to calculate the total revenue from selling various types of toys. The program should take the quantity of each type of toy sold as input and then calculate the total revenue generated from selling those toys. You are given the following information: - The qu...
```python # Prompt the user to input the quantity of each type of toy sold puzzles = int(input("Enter the quantity of puzzles sold: ")) dolls = int(input("Enter the quantity of dolls sold: ")) bears = int(input("Enter the quantity of bears sold: ")) minions = int(input("Enter the quantity of minions sold: ")) trucks = ...
magicoder
python
You are tasked with implementing a function to generate segments based on the given parameters. The function `generate_segments` takes several arguments: `starttime`, `endtime`, `includeflags`, `excludeflags`, `writesegments`, and `usegwosc`. The `starttime` and `endtime` represent the start and end times for the segme...
```python def generate_segments(starttime, endtime, includeflags, excludeflags, writesegments, usegwosc): # Implement the function to generate segments based on the given parameters segmentlist = [] # Perform segment generation logic here based on the input parameters return segmentlist ``` In the so...
magicoder
python
You are tasked with creating a utility function for managing directories in a file system. Your function should handle the creation of a directory if it does not exist and panic with a custom error message if the creation fails. You are given a code snippet that demonstrates the usage of the function and the expected b...
```rust use std::fs; fn create_directory(path: &str, error_message: &str) { if let Err(err) = fs::create_dir_all(path) { panic!("{}: {}", error_message, err); } } fn main() { create_directory("/path/to/directory", "Failed to create directory"); } ``` The `create_directory` function uses the `fs::...
magicoder
rust
You are tasked with creating 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. The function should be named `count_unique` and should have the following signature: ```python def count_unique(nums: List[int]) -> Dict[int, int...
```python from typing import List, Dict def count_unique(nums: List[int]) -> Dict[int, int]: unique_counts = {} for num in nums: if num in unique_counts: unique_counts[num] += 1 else: unique_counts[num] = 1 return unique_counts ``` The `count_unique` function initia...
magicoder
python
You are tasked with creating a program to generate unique combinations of climate model configurations for a research project. Each combination consists of a climate model, a regional climate model, and a greenhouse gas emission scenario. The program should output all possible unique combinations of these three compone...
```python import itertools climate_models = ['EC-EARTH', 'GFDL-ESM2M', 'HadGEM2-ES', 'MIROC-ESM-CHEM', 'NorESM1-M'] regional_models = ['RACMO22E', 'WRF', 'RegCM4', 'COSMO-CLM'] emission_scenarios = ['rcp2.6', 'rcp4.5', 'rcp6.0', 'rcp8.5'] combinations = list(itertools.product(climate_models, regional_models, emission...
magicoder
python
You are tasked with creating a program that extracts and manipulates data from HTML code. Given an HTML snippet representing a section of a web page, your goal is to extract the URL from the anchor tag and then modify the class attribute of the div tag. Write a function `processHTML` that takes in the HTML snippet as ...
```python import re def processHTML(html_snippet): # Extract the URL from the anchor tag url_match = re.search(r'<a class="btn btn-orange-general view-all hidden-xs" href="([^"]+)">', html_snippet) if url_match: url = url_match.group(1) else: return "Invalid HTML snippet" # Modify ...
magicoder
python
You are tasked with creating a Python program to manage a virtual inventory system for a small business. The program should allow users to add, remove, and display items in the inventory. Additionally, the program should be able to handle errors and display appropriate error messages to the user. Your task is to imple...
```python import colorama from colorama import Fore, Style # Initialize colorama colorama.init() inventory = {} def add_item(item_name, quantity): if item_name and quantity: inventory[item_name] = quantity print(f"Added {quantity} units of {item_name} to the inventory.") else: print(F...
magicoder
python
You are tasked with creating a script to automate the setup of a MySQL database and the addition of a test user for mock authentication in a Docker environment. The given code snippet demonstrates the use of Docker commands to achieve this. Your task is to write a Python script that uses the `docker` module to interac...
```python import docker def run_mysql_container(): client = docker.from_env() mysql_container = client.containers.run( 'mysql', detach=True, name='mysql_setup', links={'devenv_mysql_1': 'mysql'} ) return mysql_container def execute_sql_script(container, script_path): ...
magicoder
python
You are tasked with implementing a data preprocessing algorithm for a machine learning project. The algorithm involves reading a list of file paths from a file, processing the data, and then writing the processed data to a new file. The specific steps of the algorithm are as follows: 1. Read a list of file paths from ...
```python vallist = 'vallist.txt' testlist = 'testlist.txt' sampling_times = 10 cropping_times = 3 fl = open(vallist).readlines() fl = [line.strip() for line in fl if line.strip() != ''] f_test = open(testlist, 'w') for i in range(len(fl)): line = fl[i].split(' ') file_path = line[0] # Assuming the file path...
magicoder
python
You are tasked with implementing a reinforcement learning environment for a simplified version of Texas Hold'em poker. The environment is represented by the `HoldemEnv` class, which is a subclass of the `gym.Env` class from the OpenAI Gym library. The environment has an action space that allows players to perform vario...
```python import gym class HoldemEnv(gym.Env): metadata = {'render.modes': ['human']} def __init__(self, game: HoldemGame): self._game = game @property def action_space(self): ''' Action space: {0,1,2,3,4} x (0, +oo) where 0 == bet, 1 == raise, 2 == check, 3 == call, 4 =...
magicoder
python
You are tasked with implementing a class for managing a grid hierarchy tree used in volume data processing. The class, `GridHierarchyTree`, is responsible for constructing and managing the hierarchy tree based on specified refinement levels and volume dimensions. The constructor of the `GridHierarchyTree` class takes ...
```cpp #include <iostream> namespace volume { class GridHierarchyTree { private: int _VolumeWidth; int _VolumeHeight; int _VolumeDepth; int _FixedRefinementLevel; int _HierarchicalRefinementLevel; public: GridHierarchyTree(int fixedRefinementLevel, int hier...
magicoder
cpp