query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a command-line tool for managing package recipes using the Conan package manager. The tool should support various options for building and uploading packages. Your task is to create a Python script that utilizes the `argparse` module to parse command-line arguments and perform the neces... | ```python
import argparse
from profile_management import ProfileManagement # Assuming the existence of a ProfileManagement module
DEFAULT_USER = "default_user" # Replace with the actual default user value
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='Conan Package Manager Tool')
# ... | magicoder | python |
You are tasked with creating a Rust module for handling MIDI data. Your module should provide functionality for parsing and processing MIDI messages. MIDI messages are structured as a series of bytes, with each message type having a specific format. Your task is to implement a Rust module that can parse and process MID... | ```rust
// Define the MIDI message types
enum MidiMessage {
NoteOn(u8, u8), // Represents a note on message with note number and velocity
NoteOff(u8, u8), // Represents a note off message with note number and velocity
ControlChange(u8, u8), // Represents a control change message with controller number and ... | magicoder | rust |
You are tasked with simulating the behavior of a simplified system that manages the configuration and manipulation of devices using a microcontroller. The system consists of a series of commands executed via a remote shell connection to a microcontroller, as well as local shell commands. Your goal is to implement a fun... | ```python
from typing import List
def process_commands(commands: List[str]) -> str:
gpio_direction = "IN"
gpio_state = "LOW"
devices_connected = ["nvme1", "nvme2", "nvme3"] # Example list of connected devices
for command in commands:
if 'Beetle --SetGpioDirection' in command:
gpio... | magicoder | python |
You are tasked with creating a Python program that simulates a simple car racing game using the `pygame` library. The game will involve a player-controlled car navigating through a track while avoiding obstacles. The player's score will be based on the distance traveled without hitting any obstacles.
Your task is to i... | ```python
import pygame
import random
# Initialize pygame
pygame.init()
# Set up the game window
window_width = 800
window_height = 600
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Car Racing Game')
# Define colors
white = (255, 255, 255)
black = (0, 0, 0)
# Defin... | magicoder | python |
You are tasked with implementing a custom authorization attribute in an ASP.NET Core application. The attribute should restrict access to a specific role and a set of privileged IP addresses. You are provided with a code snippet from a base controller that sets up the role-based authorization. Your task is to extend th... | ```csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Threading.Tasks;
public class CustomAuthorizationAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
{
private readonly string _ro... | magicoder | csharp |
You are tasked with creating a Python class that manages URL redirections for a web application. The class, `RedirectManager`, should have the following functionalities:
1. Method `save_entry(url: str, redirect_to: str)`: This method should save a new entry for URL redirection. It takes two parameters: `url` (the orig... | ```python
class RedirectManager:
def __init__(self):
self.page_not_found_entries = PageNotFoundEntry.objects.all()
def save_entry(self, url: str, redirect_to: str):
# Save a new entry for URL redirection
entry = RedirectEntry(url=url, redirect_to_url=redirect_to)
entry.save()
... | magicoder | python |
You are tasked with implementing a simplified version of a dependency injection container. In this problem, you will create a class `DependencyInjectionContainer` that can manage observer methods and contexts.
Your task is to implement the following methods in the `DependencyInjectionContainer` class:
1. `void addObs... | ```java
import java.util.HashMap;
import java.util.Map;
class ObserverMethod<T> {
// Implementation of ObserverMethod class
}
class Context {
// Implementation of Context class
}
public class DependencyInjectionContainer {
private Map<Class<?>, ObserverMethod<?>> observerMethods;
private Map<Class<?>... | magicoder | java |
You are tasked with creating a multithreaded program that simulates a simple ticketing system for a movie theater. The program should use Rust's standard library for synchronization and threading.
Your program should have the following requirements:
1. The movie theater has a limited number of seats, which should be r... | ```rust
use std::sync::{Arc, Mutex};
use std::thread;
struct MovieTheater {
available_seats: usize,
}
impl MovieTheater {
fn new(seats: usize) -> Self {
MovieTheater {
available_seats: seats,
}
}
fn purchase_ticket(&mut self) -> bool {
if self.available_seats > 0 {... | magicoder | rust |
You are tasked with creating a Python function to validate and process a set of parameters for adding a node to a UK8S cluster. The function should take in a dictionary of parameters and perform the following validations and processing steps:
- Ensure that the required parameters "ClusterId", "Password", and "UHostId"... | ```python
import base64
def validate_and_process_node_params(params: dict) -> dict:
required_params = ["ClusterId", "Password", "UHostId"]
for param in required_params:
if param not in params:
raise ValueError(f"Missing required parameter: {param}")
if not isinstance(params["Password"]... | magicoder | python |
You are tasked with creating a program that utilizes the `ApiHelper` class to retrieve and process JSON data from a given URL. The `ApiHelper` class contains a method `GetJsonString` that takes a URL as input and returns the JSON data as a string. Your task is to create a program that uses this method to fetch JSON dat... | ```csharp
using System;
using System.Net;
using Newtonsoft.Json.Linq;
public static class ApiHelper
{
public static string GetJsonString(string url)
{
string json = string.Empty;
using (WebClient client = new WebClient())
json = client.DownloadString(url);
return json;
... | magicoder | csharp |
You are working on a quantum computing project and need to implement a class for handling fermionic operators. Your task is to create a Python class that extends the `FermionSumOperators` class from the `netket` library. The class, named `AbInitio`, should be initialized with a Hilbert space `hi`, a one-body matrix `on... | ```python
from netket.custom.fermionic_hilbert import Fermions
from netket.custom.fermion_operator import SparseHermitianFermionOperator, FermionSumOperators, FermionTotalSpinNumberOperator
import numpy as np
class AbInitio(FermionSumOperators):
def __init__(self, hi, one_body_mat, two_body_mat):
n_orbital... | magicoder | python |
You are tasked with creating a program that simulates the inclusion of files in a web development project. In this scenario, the code snippet provided is from a web development project using a templating system. The `@include` directive is used to include the content of another file at the specified location. The inclu... | ```python
from typing import List
def resolveFileInclusions(inclusions: List[str]) -> List[str]:
graph = {}
for inclusion in inclusions:
included_file = inclusion.split('(')[1].split(')')[0]
including_file = inclusion.split("'")[1]
if included_file not in graph:
graph[includ... | magicoder | python |
You are tasked with creating a middleware function for a Node.js web application using Express.js. The middleware function should check if a user is authenticated before allowing access to certain routes. You are provided with a code snippet that sets up a router and applies the `isAuthenticated` middleware to the root... | ```javascript
// Middleware function to check if user is authenticated
function isAuthenticated(req, res, next) {
// Check if user is authenticated based on session or token
if (req.isAuthenticated()) { // Assuming req.isAuthenticated() is a function that checks user authentication
// User is authenticated, all... | magicoder | javascript |
You are tasked with implementing a custom dropdown component in a React application. The dropdown component should utilize a context to manage its state and provide functionality for other components to interact with it. The provided code snippet defines the context for the dropdown component.
Your task is to create a... | ```jsx
import React, { useContext, useState } from 'react';
import DropdownContext from './DropdownContext';
const Dropdown = () => {
const { options, onSelectOption } = useContext(DropdownContext);
const [isOpen, setIsOpen] = useState(false);
const [selectedOption, setSelectedOption] = useState(null);
const ... | magicoder | jsx |
You are tasked with creating a program that simulates a simple drawing application. The application should allow users to draw basic shapes such as rectangles, circles, and lines on a canvas. Additionally, the program should provide the functionality to select, move, and delete the drawn shapes.
To achieve this, you n... | ```csharp
using System;
using System.Collections.Generic;
using System.Drawing;
// Define an abstract Shape class with common properties and methods
public abstract class Shape
{
public abstract void Draw(Graphics graphics);
public abstract bool ContainsPoint(Point point);
}
// Implement Rectangle class inher... | magicoder | csharp |
You are tasked with implementing a simple token matching system for a lexer. The provided code snippet contains two methods of a `TokenMatcher` struct: `is_match` and `find`. The `is_match` method checks if any of the rules in the `TokenMatcher` match the given text, while the `find` method returns the first matching r... | ```rust
#[derive(Debug, Clone)]
pub enum TokenKind {
// Define the possible token kinds here
}
pub struct Rule {
pattern: String,
kind: TokenKind,
}
impl Rule {
pub fn new(pattern: &str, kind: TokenKind) -> Rule {
Rule {
pattern: pattern.to_string(),
kind,
}
... | magicoder | rust |
You are tasked with creating a Python function that processes command-line arguments and generates a configuration for a data redirection tool. The function should take the command-line arguments, parse them using a utility function, and then construct a configuration dictionary based on the parsed arguments. The confi... | ```python
import utils
def generate_config(argv, redirect_port_args, usage):
opts = utils.parse(argv, redirect_port_args, ".splunkrc", usage=usage)
config = {
"scheme": opts.kwargs["scheme"],
"host": opts.kwargs["host"],
"port": opts.kwargs["port"],
"redirecthost": "localhost",... | magicoder | python |
You are tasked with implementing a function to transform a given input of type `BTreeMap<i32, Vec<char>>` into a `BTreeMap<char, i32>`. The input map contains integer keys and corresponding lists of characters as values. Your goal is to create a new map where the characters become keys and the counts of each character ... | ```rust
use std::collections::BTreeMap;
pub fn transform(input: &BTreeMap<i32, Vec<char>>) -> BTreeMap<char, i32> {
let mut result: BTreeMap<char, i32> = BTreeMap::new();
for (_, chars) in input {
for &c in chars {
*result.entry(c).or_insert(0) += 1;
}
}
result
}
```
The ... | magicoder | rust |
You are tasked with creating a Python function that processes and sends training session details to a chat bot. The function should take in the training session details, format them into a message, send the message to the chat bot, and return a value. However, if an exception occurs during the process, the function sho... | ```python
import datetime
def process_training_session(func_name, start_time, end_time, elapsed_time, chat_id, value):
DATE_FORMAT = "%Y-%m-%d %H:%M:%S" # Assuming DATE_FORMAT is defined elsewhere
try:
contents = [
'Main call: %s' % func_name,
'Starting date: %s' % start_time.s... | magicoder | python |
You are tasked with creating a Python class that represents a backend module for quantum computing. The backend module should be able to perform quantum operations and provide information about its capabilities. Your task is to implement the abstract base class for the backend module, ensuring that the required backend... | ```python
from abc import ABC, abstractmethod
from qiskit.version import __version__
class Backend(ABC):
"""Abstract base class for backend modules."""
@abstractmethod
def quantum_operation(self, circuit):
"""Perform a quantum operation on the given circuit."""
pass
@abstractmethod
... | magicoder | python |
You are tasked with implementing a Graph Isomorphism Network (GIN) in Python. GIN is a type of neural network designed to operate on graph-structured data. The given code snippet provides a partial implementation of a GIN model using PyTorch. Your task is to complete the implementation of the GIN model by defining the ... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class MLP(nn.Module):
def __init__(self, n_layers, input_dim, hidden_dim, output_dim):
super(MLP, self).__init__()
self.layers = nn.ModuleList()
self.layers.append(nn.Linear(input_dim, hidden_dim))
for _ in... | magicoder | python |
You are tasked with implementing a program to process and display a series of points on a 2D plane. Each point is represented by a set of parameters, and your program needs to format and print these points according to a specific template.
The template for each point is as follows:
```
'1 4 0 1 0 0 50 -1 20 0.000 1 0.... | ```python
def format_point(cx, cy, point_radius, sx, sy, ex, ey, count):
formatted_point = '1 4 0 1 0 0 50 -1 20 0.000 1 0.0000 {cx} {cy} {point_radius} {point_radius} {sx} {sy} {ex} {ey}'.format(**locals())
count += 1
return formatted_point, count
``` | magicoder | python |
You are given a directed graph `g` and a set of nodes `vrs`. The code snippet provided is intended to remove the nodes in the set `vrs` from the graph `g_allowed` and `g`. However, the snippet is incomplete and lacks the necessary context to understand the problem fully. Your task is to complete the code snippet by wri... | ```python
import networkx as nx
def remove_nodes_from_graphs(g_allowed, g, vrs):
g_allowed.remove_nodes_from(vrs)
g.remove_nodes_from(vrs)
def resulting_graph(g):
return g
```
In the `remove_nodes_from_graphs` function, the `remove_nodes_from` method of the NetworkX graph is used to remove the nodes in th... | magicoder | python |
You are tasked with implementing a Rust program to fetch system information using the `susfetch` library. The `SusFetch` struct represents system information, and the `default` method is used to initialize it by fetching various system details. Your task is to complete the implementation of the `SusFetch` struct and it... | ```rust
use susfetch::{get_item_from_c_buf, IOResult, get_kernel_version, get_shell, get_window_manager, get_host, get_os, get_terminal};
#[derive(Debug)]
pub struct SusFetch {
kernel: String,
shell: String,
wm: String,
host: String,
os: String,
terminal: String,
}
impl SusFetch {
fn defau... | magicoder | rust |
You are tasked with implementing a function that processes a dictionary and outputs a formatted string based on the given delimiter. The function should take in three parameters: a dictionary `var`, a string `delimiter`, and a string `trans_delimiter`. The dictionary `var` contains key-value pairs, where the keys are s... | ```python
def make_safe(s: str, trans_delimiter: str) -> str:
return s.replace(trans_delimiter, ',')
def process_dictionary(var: dict, delimiter: str, trans_delimiter: str) -> str:
sorted_keys = sorted(var.keys(), key=lambda x: var[x])
formatted_keys = [make_safe(key, trans_delimiter) for key in sorted_key... | magicoder | python |
You are tasked with implementing a Python class method that converts an Abstract Syntax Tree (AST) node into an assignment statement. The AST represents the structure of a Python program and is commonly used for code analysis and transformation.
Your task is to complete the `from_ast` method within a Python class. The... | ```python
def from_ast(self, namespace, node):
""" Creates an assignment statement from an AST node. """
# Import necessary classes from the AST module
from ast import Assign, Name, Store, Num, Str
# Check the type of the AST node
if isinstance(node, Assign):
# If the node is an assignment... | magicoder | python |
You are tasked with implementing a custom pass for an intermediate representation (IR) in a compiler infrastructure. The IR is represented using the FEXCore library, which provides functionalities for managing the IR and emitting instructions.
Your task is to create a pass that performs a specific transformation on th... | ```cpp
#include "CustomPasses/MyCustomPass.h"
#include <FEXCore/IR/IR.h>
#include <FEXCore/IR/IREmitter.h>
#include <FEXCore/IR/PassManager.h>
#include <FEXCore/Utils/LogManager.h>
namespace FEXCustomPasses {
class MyCustomPass : public FEXCore::IR::Pass {
public:
MyCustomPass() = default;
~MyCustomPass() = defau... | magicoder | cpp |
You are tasked with creating a custom Babel plugin that performs a specific transformation on JavaScript code. The plugin should identify and transform specific patterns within the code. Your goal is to implement the transformation logic for the plugin.
You are provided with a code snippet that sets up the testing env... | ```javascript
// Solution for the transformation logic within the examplePlugin
const examplePlugin = ({ types }) => {
return {
visitor: {
CallExpression(path) {
if (
path.node.callee.type === "MemberExpression" &&
path.node.callee.object.name === "console" &&
path.nod... | magicoder | javascript |
You are tasked with implementing a Huffman coding algorithm to compress and decompress text data. Huffman coding is a widely used algorithm for lossless data compression. In this problem, you will create a program that reads a text file, constructs a Huffman tree based on the frequency of characters in the file, and th... | ```cpp
#include <iostream>
#include <fstream>
#include <queue>
#include <unordered_map>
#include <bitset>
struct Node {
char data;
int frequency;
Node* left;
Node* right;
};
struct Compare {
bool operator()(Node* const& a, Node* const& b) {
return a->frequency > b->frequency;
}
};
cla... | magicoder | cpp |
You are tasked with implementing a Java class that models a modular minecart system. The provided code snippet is a simplified version of the `ModuleStandard` class, which extends a base class and overrides a method to calculate energy consumption. Your task is to complete the implementation of the `ModuleStandard` cla... | ```java
public class EntityMinecartModular {
// Class implementation details are not provided for this problem
}
public class ModuleStandard extends BaseModule {
public ModuleStandard(final EntityMinecartModular cart) {
super(cart);
}
@Override
public int getConsumption(final boolean isMov... | magicoder | java |
You are tasked with creating a command-line utility that processes input files and generates output files based on specific commands and options. Your program should be able to handle various command-line arguments and perform the required operations on the input files to produce the desired output.
Your task is to im... | ```python
import argparse
import os
import time
def process_input_file(input_file, output_file, verbose=False):
# Simulate processing operations
# Replace this with actual file processing logic
if verbose:
print(f"Processing input file: {input_file}...")
time.sleep(2) # Simulate processing tim... | magicoder | python |
You are tasked with creating a Python class that can parse and manipulate Jenkins credentials stored in XML format. Your task is to implement a method within the class that can extract the username and password from the given XML snippet and return them as a dictionary.
You are provided with a code snippet that define... | ```python
import xml.etree.ElementTree as ET
class JenkinsCredentialTestBase:
config_xml = """<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
<scope>GLOBAL</scope>
<id>Test Credential</id>
<username>Test-User</username>
<password><PASSWORD></password>
... | magicoder | python |
You are tasked with implementing a function that automatically sets the height of UITableViewCells in a UITableView. The function should take into account the content within the cells and adjust the height dynamically. You are given a code snippet from a UIViewController's `viewDidLoad` method, which indicates that the... | ```swift
func autoSetCellHeight(tableView: UITableView) {
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100 // Set an initial estimated row height, can be adjusted based on the content
// Ensure the following properties are set in the viewDidLoad method of the view... | magicoder | swift |
You are tasked with implementing a simplified version of a templating engine's node class in TypeScript. The provided code snippet is a part of a TypeScript project for a templating engine, and it includes a class definition for `InlineIf` that extends the `NunjucksNode` class.
Your task is to complete the implementat... | ```typescript
import { NunjucksNode } from './nunjucksNode';
export class InlineIf extends NunjucksNode {
// ... other class properties and methods
evaluateCondition(context: Record<string, any>): any {
const conditionRegex = /{{\s*(.*?)\s*\?\s*(.*?)\s*:\s*(.*?)\s*}}/;
const matches = this.source.match(co... | magicoder | typescript |
You are tasked with creating a Python function that retrieves and processes data from a website. The function should take an ID as input and use it to make a GET request to a specific URL. The response from the website will be in HTML format, and the function should parse this HTML to extract relevant information.
You... | ```python
import httpx
from bs4 import BeautifulSoup as bso
def retrieve_part_groups(id):
BASE_URL = 'https://www.realoem.com/bmw/'
LANGUAGE = 'enUS'
URL = f"{BASE_URL}{LANGUAGE}"
params = {'id': id}
r = httpx.get(f'{URL}/partgrp', params=params)
soup = bso(r.text, "html.parser")
links... | magicoder | python |
You are tasked with implementing a Python class that processes image data from a ROS (Robot Operating System) environment. The provided code snippet initializes a ROS node and sets up a publisher and subscriber for specific topics. Your task is to complete the implementation of the `StarterNode` class by adding the `im... | ```python
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Bool
from constants import STARTER_TOPIC, IMAGE_TOPIC, PROCESSED_IMAGE_TOPIC, STARTER_NODE
class StarterNode:
def __init__(self):
rospy.init_node(STARTER_NODE)
self.start_publisher = rospy.Publisher(STARTER_TOPIC, B... | magicoder | python |
You are tasked with implementing a Python function that calculates the optimal transport cost matrix for a given set of source and target data points. The optimal transport problem is a mathematical optimization problem that deals with finding the most efficient way to transport a distribution of mass from one set of p... | ```python
import numpy as np
def calculate_optimal_transport_cost_matrix(data_src, data_tar, label_src):
if data_src.shape != data_tar.shape:
raise ValueError("Source and target data shapes must be equal")
# Calculate the cost matrix based on Euclidean distance between data points
num_src_points =... | magicoder | python |
You are tasked with implementing a class for creating and manipulating Bezier curves in a 2D space. The class should provide methods for setting control points, evaluating the curve at a given parameter value, and updating the curve's visual representation.
Your task is to implement the `BezierCurve` class with the fo... | ```python
class BezierCurve:
def __init__(self, p1, p2, p3, p4):
self.m_p1 = p1
self.m_p2 = p2
self.m_p3 = p3
self.m_p4 = p4
def evaluate(self, t):
invt = 1 - t
pos_x = invt * invt * invt * self.m_p1[0] \
+ 3 * invt * invt * t * self.m_p2[0] \
... | magicoder | python |
You are tasked with implementing a Python class that extends a base class and adds functionality for handling file upload results. The base class `BaseModel` is provided by the `asposehtmlcloud` library. Your task is to create a new class `FilesUploadResult` that inherits from `BaseModel` and adds specific attributes a... | ```python
from asposehtmlcloud.models import BaseModel
class FilesUploadResult(BaseModel):
def __init__(self):
super().__init__()
self.uploaded_files = []
self.failed_files = []
self.total_files = 0
def add_uploaded_file(self, file_name):
self.uploaded_files.append(file... | magicoder | python |
You are tasked with implementing a simulated annealing (SA) optimization algorithm to maximize a given objective function. Simulated annealing is a probabilistic optimization technique used to find the global optimum in a large search space. The algorithm starts with an initial solution and iteratively explores the sol... | Objective function `maxtf_job`:
```python
def maxtf_job(solution):
# Implement the objective function to be maximized
# Example:
return -1 * (solution[0]**2 + solution[1]**2) # Negative sign for maximization
```
Simulated Annealing Optimization Function:
```python
import numpy as np
class SimulatedAnneal... | magicoder | python |
You are tasked with implementing a function to calculate the width of a given string or attributed string when rendered with a specific font size. The function should take into account the possibility of the input being either a regular string or a rich text attributed string.
You are given the following function sign... | ```swift
func getStringWidth(str: String?, attriStr: NSAttributedString?, font: UIFont) -> CGFloat {
guard let str = str, !str.isEmpty else {
if let attriStr = attriStr {
return attriStr.size().width
} else {
return 0
}
}
if let attriStr = attriStr {
... | magicoder | swift |
You are tasked with implementing a function to manage a list of alarms in a mobile application. The provided code snippet includes a function `localRead` and a static method `fromLocal` within a class or struct named `Alarms`. The `localRead` function is responsible for parsing a JSON string retrieved from local storag... | ```swift
import Foundation
struct Alarm: Codable {
let time: String
let label: String
// Add any other properties as needed
}
struct Alarms {
var list: [Alarm] = []
func localRead() {
if let jsonData = UserDefaults.standard.data(forKey: "alarms") {
do {
list = ... | magicoder | swift |
You are given a 2D matrix of integers representing the elevation map of a region. Each cell in the matrix represents the height of the land at that position. Your task is to write a function to determine if a cell is a local minimum, meaning it is lower in elevation than its neighboring cells.
You need to implement th... | ```python
def is_local_min(matrix, x, y):
n = len(matrix)
m = len(matrix[0])
def is_valid_cell(i, j):
return 0 <= i < n and 0 <= j < m
neighbors = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]
valid_neighbors = [(i, j) for i, j in neighbors if is_valid_cell(i, j)]
is_low = True
for i, ... | magicoder | python |
You are tasked with implementing a class hierarchy for a cloud service management system. The system includes classes for users, virtual machines, and cloud providers. Your task is to create the necessary classes and methods to represent these entities and their relationships.
You are provided with a code snippet that... | ```python
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.virtual_machines = []
def add_virtual_machine(self, virtual_machine):
self.virtual_machines.append(virtual_machine)
def remove_virtual_machine(self, virtual_machine):
if ... | magicoder | python |
You are tasked with creating a Python function that simulates a simple authorization system for accessing training tests in an educational application. The function should check if the user is authorized to access the training tests and then allow or deny access accordingly.
You are given the following code snippet as... | ```python
def test_opening_TT_without_authorization(app, is_authorized):
if is_authorized:
app.Button_menu.Test_Button_Videocourses() # Allow access to training tests
else:
# Handle unauthorized access, e.g., display an error message or redirect to the authorization page
pass
```
In th... | magicoder | python |
You are given an array of integers representing the scores of a game. The game is played by two players, and they take turns to make moves. In each move, a player can choose to remove any one element from either end of the array. The player's score increases by the value of the removed element. The game continues until... | ```python
from typing import List
def maxScore(nums: List[int]) -> int:
n = len(nums)
dp = [[0] * n for _ in range(n)]
for length in range(1, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if length == 1:
dp[i][j] = nums[i]
else:
... | magicoder | python |
You are tasked with creating a Python program that processes a directory of files and organizes them based on their last modified date. Your program should move files from the source directory to destination directories based on the year and month of their last modified date. For example, if a file was last modified in... | ```python
import os
import shutil
import datetime
def organize_files(source_directory, destination_directory):
for root, _, files in os.walk(source_directory):
for file in files:
file_path = os.path.join(root, file)
modified_time = os.path.getmtime(file_path)
modified_da... | magicoder | python |
You are tasked with creating a Python class to manage a history of counts and timestamps. Your class should have the following functionalities:
1. Initialize the history with an initial count and timestamp.
2. Update the history with a new count and timestamp.
3. Retrieve the latest count and timestamp from the histor... | ```python
class CountHistory:
def __init__(self, initial_count: int, initial_timestamp: str):
self.latest_count = initial_count
self.latest_timestamp = initial_timestamp
def update_history(self, new_count: int, new_timestamp: str):
self.latest_count = new_count
self.latest_times... | magicoder | python |
You are tasked with implementing a class hierarchy for a data loader system. The system is designed to read various types of data from different sources. Your task is to create a class `ScalarReader` that inherits from the abstract class `IReader` and implements the functionality to read a single float, int, str, or ot... | ```python
from abc import ABC, abstractmethod
from typing import Union
class IReader(ABC):
@abstractmethod
def read_data(self) -> Union[float, int, str]:
pass
class ScalarReader(IReader):
"""Numeric loader readers abstraction. Reads a single float, int, str or other from loader."""
def __ini... | magicoder | python |
You are given a string `a` of length `n`. Your task is to write a function or method to find the length of the shortest non-empty prefix of `a` that repeats to form the entire string `a`. If no such prefix exists, return -1.
Write a function:
```cpp
int shortestRepeatingPrefix(string a);
```
**Input**
The input consis... | ```cpp
int shortestRepeatingPrefix(string a) {
int len = a.length();
for (int i = 0; i < len; i++) {
if (len % (i + 1) == 0 && a[0] == a[i]) {
bool bj = false;
for (int j = 0; j + i + 1 < len; j++) {
if (a[j] != a[j + 1 + i]) {
bj = true;
... | magicoder | cpp |
You are tasked with creating a Python script that manages the organization of files into folders based on their file extensions. Your script should take a directory path as input and then create subfolders for each unique file extension found within that directory. For example, if the input directory contains files wit... | ```python
import os
import shutil
def organize_files(directory):
file_extensions = set()
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
file_extensions.add(filename.split('.')[-1])
for ext in file_extensions:
create_folder(os.path.j... | magicoder | python |
You are tasked with creating a Python program that processes a given text file and performs specific operations on the content. The program should read a text file, extract certain information, and then display the processed data in a user-friendly format.
Your task is to implement a Python program that accomplishes t... | ```python
import argparse
import re
def process_text_file(file_path):
try:
with open(file_path, 'r') as file:
data = file.readlines()
total_age = 0
count = 0
for line in data:
match = re.match(r'Name: (.*), Age: (\d+), Occupation: (.*)', line)... | magicoder | python |
You are tasked with creating a program that analyzes a given text file to count the occurrences of each unique word. The program should ignore punctuation and treat uppercase and lowercase letters as equivalent. Additionally, the program should exclude common English stop words such as "the," "and," "of," etc., from th... | ```python
import re
def countUniqueWords(file_path):
stop_words = {"the", "and", "of", "in", "to", "a", "is", "it", "that"} # Define common English stop words
word_count = {}
with open(file_path, 'r') as file:
text = file.read().lower() # Read the file and convert the text to lowercase
w... | magicoder | python |
You are tasked with implementing a function that calculates the total area covered by a set of rectangles on a 2D plane. Each rectangle is represented by its top-left corner coordinates (x, y) and its dimensions (width, height). The function should take an array of rectangles as input and return the total area covered ... | ```swift
struct Rectangle {
let x: Int
let y: Int
let width: Int
let height: Int
}
func totalAreaCovered(rectangles: [Rectangle]) -> Int {
var area = 0
var points = Set<(Int, Int)>()
for rect in rectangles {
for i in rect.x..<(rect.x + rect.width) {
for j in rect.y..<(r... | magicoder | swift |
You are tasked with creating a Python program that retrieves data from a secure API endpoint using the `urllib` library. Your program should handle the HTTPS connection and include necessary headers for authentication. Additionally, the retrieved data should be processed and displayed in a specific format.
Your progra... | ```python
import urllib.request
import json
# Define the API endpoint URL and required headers
export_url = "https://api.example.com/data"
headers = {
'Authorization': 'Bearer your_access_token',
'Content-Type': 'application/json'
}
# Create a context to handle HTTPS connection
ctx = ssl.create_default_contex... | magicoder | python |
You are given a Python code snippet that processes an image to create a heat map. The code uses nested loops to iterate over the pixels of the image and applies a distance-based calculation to update the heat map. Your task is to implement a function that encapsulates this image processing logic.
Write a function `gen... | ```python
def generate_heat_map(image, r, index):
h = len(image)
w = len(image[0])
offset = 10
heat_map = [[0 for _ in range(w)] for _ in range(h)]
for i in range(h):
for j in range(w):
if image[i][j] != 0:
for m in range(-r, r+1):
for n in ra... | magicoder | python |
You are tasked with creating a Python script to automate the process of fixing directory permissions on a Unix-based system. The script should traverse through a given directory and its subdirectories, setting specific permissions for directories and files, and changing the group ownership of all files and directories ... | ```python
import os
import sys
def fix_permissions(root_dir):
try:
for dirpath, dirnames, filenames in os.walk(root_dir):
for dirname in dirnames:
dir_full_path = os.path.join(dirpath, dirname)
os.chmod(dir_full_path, 0o775) # Set directory permissions to 0775
... | magicoder | python |
You are tasked with creating a command-line tool that processes a Cypher query for a Neo4j database. The tool should accept various options and arguments to customize the query execution. Your task is to implement the logic to parse the command-line options and arguments, validate them, and process the Cypher query acc... | ```python
import sys
from optparse import OptionParser
def process_cypher_query(arglist):
opt = OptionParser()
opt.add_option('--primary_key', action='store', default='', dest='primary_key')
opt.add_option('--logmodulo', action='store', type='int', default=0, dest='logmodulo')
opt.add_option('--add_end... | magicoder | python |
You are tasked with creating a web application for an online store that sells various products. The application has two main sections: frontend for regular users and an admin section for managing products. The provided code snippet is a part of the backend logic for the frontend section. It retrieves product data from ... | ```php
// ProductController.php
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
// Other controller methods...
public function addProduct(Request $request)
{
// Validate the incoming request data
$request->validate([
'name' => ... | magicoder | php |
You are given a Rust struct representing a binary tree node. Your task is to implement a function that checks whether two binary trees are identical or not. Two binary trees are considered identical if they have the same structure and the same node values at each position.
The given Rust struct for the binary tree nod... | ```rust
fn is_identical(p: Option<Box<TreeNode>>, q: Option<Box<TreeNode>>) -> bool {
match (p, q) {
(None, None) => true,
(Some(p_node), Some(q_node)) => {
p_node.val == q_node.val
&& is_identical(p_node.left, q_node.left)
&& is_identical(p_node.right, q_... | magicoder | rust |
You are tasked with implementing a SeriesCounter struct in Rust that represents a counter for a series of values. The SeriesCounter can be in one of three states: a specific value, an ongoing series denoted by "?", or an error state denoted by "<error>". Additionally, you need to implement the Display trait for the Ser... | ```rust
enum SeriesCounter {
Value(i32),
OnGoing,
Error,
}
impl fmt::Display for SeriesCounter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SeriesCounter::Value(value) => write!(f, "{}", value),
SeriesCounter::OnGoing => write!(f, "?"),
... | magicoder | rust |
You are tasked with implementing a quest tracking system for a role-playing game. The system should handle quest objectives, progress tracking, and message notifications for the player. You are given a code snippet that represents part of the quest tracking logic. Your task is to complete the implementation of the ques... | ```java
// Define the Quest class to track quest progress and completion
class Quest {
private String displayName;
private int amount;
private int currentAmount;
private boolean isAchievement;
private boolean completeBefore;
public Quest(String displayName, int amount, boolean isAchievement) {
... | magicoder | java |
You are tasked with creating a function that simulates the behavior of a Jetstream Manager in a messaging system. The Jetstream Manager is responsible for managing streams, which are sequences of messages. Your task is to implement a function that interacts with the Jetstream Manager to perform various operations on st... | ```typescript
import { connect, NatsConnection, createInbox } from "nats";
import { JetStreamManager, StreamAPI } from "nats";
async function interactWithJetstreamManager(
serverConfig: any,
streamName: string,
streamConfig: any
): Promise<string[]> {
const nc = await connect(serverConfig); // Connect to the N... | magicoder | typescript |
You are tasked with implementing a Java program to model and manipulate nucleotides. A nucleotide is a molecule that serves as the basic building block of DNA and RNA. The provided code snippet is a partial implementation of a class `TypeIntegerNucleotide` that extends the abstract class `Nucleotide`. The `TypeIntegerN... | ```java
public class TypeIntegerNucleotide extends Nucleotide {
public TypeIntegerNucleotide(int value) {
super(0, value);
}
/**
* Adds the value of another TypeIntegerNucleotide to this nucleotide and returns a new TypeIntegerNucleotide with the sum value.
* @param other the TypeInteger... | magicoder | java |
You are tasked with implementing a function that processes a data structure representing an inline keyboard markup for a messaging platform. The provided code snippet is a part of the function and contains a section where the `callback_data` attribute is set to "splus". Your task is to complete the function by writing ... | ```python
from typing import List, Dict
from telegram import InlineKeyboardMarkup
def generate_inline_keyboard_markup() -> InlineKeyboardMarkup:
upload_selection = [
[
{"text": "Button 1", "callback_data": "splus"},
{"text": "Button 2", "callback_data": "sminus"}
],
... | magicoder | python |
You are tasked with implementing a Python function to expand contractions in a given text. Contractions are shortened versions of words or syllables, often created by replacing certain letters with an apostrophe. For example, "can't" is a contraction of "cannot". Your function should take a string of text as input and ... | ```python
import re
def expand_contractions(text: str) -> str:
contractions_dict = {
"ain't": "are not",
"aren't": "are not",
"can't": "cannot",
"can't've": "cannot have",
"could've": "could have",
"couldn't": "could not",
"didn't": "did not",
"doesn'... | magicoder | python |
You are tasked with creating a function to fetch and display data from a database table using the CodeIgniter framework. The given code snippet is a part of a CodeIgniter model class named `Md_ganti`. The `fetch_prodi` function is responsible for retrieving and returning data from the database table `ganti` joined with... | ```php
class Md_ganti extends CI_Model
{
function fetch_prodi()
{
// Assuming the database configuration is already set in the CodeIgniter configuration files
// Load the database library if not already loaded
$this->load->database();
// Assuming the database table names and co... | magicoder | php |
You are working on a machine learning project and have been tasked with evaluating the performance of a trained model using various metrics. The model has been trained using training and validation data, and you need to calculate and display the metrics for both datasets. Additionally, you are required to log these met... | ```python
# Import necessary libraries
import numpy as np
import pandas as pd
# Define the train_model function
def train_model(data, parameters):
# Implementation of model training
# This function returns the trained model
pass
# Define the get_model_metrics function
def get_model_metrics(model, data):
... | magicoder | python |
You are tasked with implementing a generic function in Rust that takes a mutable reference to a struct's inner field and an argument, and returns a value. Your task is to define the function signature and implement the function using the given code snippet as a reference.
Your task is to:
1. Define the function signat... | ```rust
// Define the function signature for FnOnce
trait FnOnce<Arg> {
type Inner;
type Ret;
fn call_once(&mut self, inner: &mut Self::Inner, arg: Arg) -> Self::Ret;
}
// Implement the FnOnce function
struct MyFn;
impl<Arg, Ret> FnOnce<Arg> for MyFn {
type Inner = i32;
type Ret = Ret;
fn ca... | magicoder | rust |
You are tasked with implementing a simple neural network using TensorFlow to classify handwritten digits from the MNIST dataset. The network should consist of an input layer, a hidden layer, and an output layer. You need to define the network's structure, implement the forward propagation to produce the output, define ... | ```python
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# Step 1: Define the neural network structure
n_input = 784 # MNIST data input (img shape: 28*28)
n_hidden = 256 # Hidden layer number of features
n_classes = 10 # MNIST total classes (0-9 digits)
# Input and output placeh... | magicoder | python |
You are tasked with creating a shell script that generates a temporary working directory and sets up a trap to ensure the directory is removed when the script exits. Your script should also handle the case where the temporary directory creation fails.
Write a shell script that accomplishes the following:
1. Creates a ... | ```bash
#!/bin/bash
# Function to handle cleanup and exit
cleanup_and_exit() {
if [ -n "${TMP_WORKDIR}" ] && [ -d "${TMP_WORKDIR}" ]; then
rm -rf "${TMP_WORKDIR}"
fi
exit 1
}
# Create temporary working directory
TMP_WORKDIR=$(mktemp -d -p "${PWD}") || { echo "Failed to create temporary directory"; cleanup_a... | magicoder | shell |
You are tasked with implementing a template factory that can create templates for different programming languages. The `CreateTemplate` method takes in three parameters: `language` (a string representing the programming language), `template` (a string representing the template content), and `model` (an object represent... | ```csharp
using System;
public class TemplateFactory : ITemplateFactory
{
public string CreateTemplate(string language, string template, object model)
{
switch (language)
{
case "CSharp":
return MergeCSharpTemplate(template, model);
case "JavaScript":
... | magicoder | csharp |
You are working as a DevOps engineer for a web application hosted on an Ubuntu server. Your task is to create a script that will start the web application as a background process and redirect its standard output and standard error to a log file. The web application is packaged as a JAR file and is located at `~/project... | ```bash
#!/bin/bash
# Change directory to /home/ubuntu/webapp
cd /home/ubuntu/webapp || { echo "Failed to change directory"; exit 1; }
# Execute the JAR file as a sudo user, redirecting output and errors to the log file
sudo java -jar ~/project/target/ROOT.jar > /home/ubuntu/csye6225.log 2>&1 &
# Check if the proces... | magicoder | shell |
You are tasked with creating a Python class that acts as a generic SQL connector, capable of connecting to different types of SQL databases. The class should be able to establish a connection, execute SQL queries, and retrieve results. To achieve this, you need to implement the `SqlConnector` class with methods for con... | ```python
import sqlite3
import cx_Oracle
class SqlConnector:
def __init__(self):
self.connection = None
self.cursor = None
def connect_sqlite(self, db_file):
try:
self.connection = sqlite3.connect(db_file)
self.cursor = self.connection.cursor()
prin... | magicoder | python |
You are tasked with implementing a web application feature that involves handling category deletion. The code snippet provided is a part of a PHP Laravel controller method responsible for deleting a category from the admin panel. The method uses the `redirect` function to redirect the user to the category management pa... | ```php
use Illuminate\Database\QueryException;
class CategoryController extends Controller
{
public function delete($categoryId)
{
try {
// Perform the category deletion operation here, assuming $categoryId is the ID of the category to be deleted
// Example: Category::destroy($c... | magicoder | php |
You are tasked with implementing a function to decompress a memory buffer using the zlib library. The provided code snippet contains a function prototype and some initialization code for the zlib library. Your task is to complete the implementation of the `deflate_memory` function, which takes a source buffer and its l... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
unsigned char* deflate_memory(Bytef* src, unsigned src_len) {
int ret;
z_stream strm;
size_t dest_len = 262144; // 256k chunk size as suggested by zlib doc
unsigned char* dest = (unsigned char*)malloc(dest_len);
if ... | magicoder | c |
You are tasked with creating a Python function that takes a list of integers as input and returns the maximum sum of a contiguous subarray within the input list. The function should efficiently handle both positive and negative integers.
You are provided with the following code snippet as a starting point:
```python
... | ```python
def max_subarray_sum(nums):
max_sum = float('-inf') # Initialize the maximum sum as negative infinity
current_sum = 0 # Initialize the current sum as 0
for num in nums:
current_sum = max(num, current_sum + num) # Update the current sum by choosing the maximum between the current number ... | magicoder | python |
You are tasked with implementing a parser for a simplified INI file format. INI files are configuration files that contain sections, each of which can hold key-value pairs. The code snippet provided is a part of a parser for an INI file format. The parser encounters different types of tokens while scanning the file, su... | ```swift
enum ParseError: Error {
case UnsupportedToken(err: String)
}
enum SCAN_STATUS {
case SCANNING_SECTION
case SCANNING_KEY_VALUE_PAIR
case SCANNING_COMMENT
}
func parseINIFile(_ input: String) throws -> [String: [String: String]] {
var result: [String: [String: String]] = [:]
var curren... | magicoder | swift |
You are given a code snippet that attempts to estimate the value of π using a Monte Carlo method. The code snippet is incomplete and contains errors. Your task is to complete the code and fix the errors to correctly estimate the value of π.
The Monte Carlo method for estimating π involves randomly selecting points wit... | ```python
import random
import math
import stdio
# Initialize variables
num_points = 1000000 # Number of random points to generate
points_inside_circle = 0
# Generate random points and count the number of points inside the quarter circle
for _ in range(num_points):
x = random.uniform(0, 1) # Generate random x-c... | magicoder | python |
You are tasked with creating a function that parses a given HTML string and extracts all the URLs present in the anchor (`<a>`) tags. The function should return an array of unique URLs found in the HTML string.
You are provided with a code snippet that represents a part of an HTML template. The HTML string may contain... | ```javascript
const extractUrlsFromHTML = (htmlString) => {
const urlRegex = /href=["'](.*?)["']/g;
const matches = htmlString.matchAll(urlRegex);
const urls = [];
for (const match of matches) {
urls.push(match[1]);
}
return Array.from(new Set(urls));
};
// Test the function with the provided HTML snip... | magicoder | javascript |
You are given a Python code snippet that appears to be part of a program for traversing a 2D grid of characters. The code snippet contains a series of conditional statements that determine the movement direction based on the characters in the grid. Your task is to create a program that simulates the traversal of a 2D g... | ```python
def grid_traversal(lines, start_x, start_y):
dx, dy = 1, 0 # Initial movement direction
answer = "" # Initialize the string to store encountered characters
x, y = start_x, start_y # Initialize the current position
while 0 <= y < len(lines) and 0 <= x < len(lines[y]):
if lines[y][x]... | magicoder | python |
You are given a string `s` and a character `c`. Your task is to write a function `shortestToChar` that returns an array of integers representing the shortest distance from each character in the string to the nearest occurrence of the given character `c`.
The function signature is:
```cpp
std::vector<int> shortestToCha... | ```cpp
#include <vector>
#include <string>
#include <algorithm>
class Solution
{
public:
std::vector<int> shortestToChar(std::string &s, char c)
{
std::vector<int> res(s.size(), s.size()); // Initialize the result array with maximum possible distance
int pos = -s.size(); // Initialize the pos... | magicoder | cpp |
You are tasked with creating a Python function that processes Jupyter notebook cells and converts specific cell types into Markdown format. The function should handle two different scenarios: one for converting a code cell with a specified heading level into Markdown, and another for converting a raw cell into Markdown... | ```python
def convert_to_markdown(cell):
"""
Convert Jupyter notebook cell to Markdown format based on cell type and attributes.
Args:
cell: dict - The Jupyter notebook cell to be processed.
Returns:
dict: The modified cell after applying the appropriate conversion.
"""
if cell['cell_t... | magicoder | python |
You are tasked with creating a Python program that simulates a simple color dictionary. The dictionary will store color names as keys and their corresponding RGB values as tuples. Your program should provide functionality to add new colors, update existing colors, retrieve RGB values for given color names, and remove c... | ```python
class ColorDictionary:
def __init__(self):
self.colors = {"BLACK": (0, 0, 0)}
def add_color(self, color_name, rgb_value):
self.colors[color_name] = rgb_value
def update_color(self, color_name, rgb_value):
if color_name in self.colors:
self.colors[color_name] =... | magicoder | python |
You are tasked with creating a Python unit test for a scenario involving Azure App Service and Kubernetes. Your goal is to write a test case that ensures the correct behavior of a specific scenario within the AppserviceKubernetesScenarioTest class. The test should validate the functionality of the scenario under certai... | ```python
import unittest
import os
from azure_devtools.scenario_tests import AllowLargeResponse
from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer, RoleBasedServicePrincipalPreparer)
TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..'))
class TestAppserviceKubernetesScenario(unitt... | magicoder | python |
You are given a list of integers representing the daily stock prices of a certain company. Your task is to determine the number of "increasing" days, where the stock price is higher than the previous day's price.
Write a function `count_increasing_days` that takes a list of integers `stock_prices` as input and returns... | ```python
def count_increasing_days(stock_prices):
increasing_count = 0
for i in range(1, len(stock_prices)):
if stock_prices[i] > stock_prices[i - 1]:
increasing_count += 1
return increasing_count
# Test the function
stock_prices = [10, 7, 11, 9, 15, 8, 12]
print(count_increasing_days(... | magicoder | python |
You are given a matrix `M` representing the friend relationships between students in a class. If `M[i][j] = 1`, then student `i` and student `j` are friends. The matrix is symmetric, meaning if `M[i][j] = 1`, then `M[j][i] = 1`.
Your task is to implement a function `findCircleNum` to find the total number of friend ci... | ```python
class Solution:
def findCircleNum(self, M):
def dfs(student):
for friend in range(len(M)):
if M[student][friend] == 1 and friend not in visited:
visited.add(friend)
dfs(friend)
num_students = len(M)
visited = set(... | magicoder | python |
You are tasked with developing a Python script for data ingestion from a Firestore database into a data processing pipeline. The script will utilize the provided credentials and configuration parameters to efficiently retrieve and process data from the Firestore database.
Given the following code snippet:
```python
CR... | ```python
from google.cloud import firestore
import json
def ingest_firestore_data(credentials_path_buckets, credentials_path_firestore, collection_name, batch_limit):
# Authenticate with Firestore using the provided credentials
with open(credentials_path_firestore) as json_file:
credentials = json.loa... | magicoder | python |
You are tasked with creating a Python program to manage a train center. The program should utilize threading to handle concurrent tasks and should also read configuration settings from a file. The configuration file is expected to contain settings for the admin module.
Your task is to implement the `start_train_center... | ```python
import threading
def start_train_center():
# Implementation of the start_train_center function
pass # Placeholder for the actual implementation
# Assuming the config dictionary is provided
config = {
'admin': {
'username': 'admin_user',
'password': 'admin_pass'
}
}
try:
... | magicoder | python |
You are given a list of strings representing file names. Each file name consists of a name and an extension separated by a dot. Your task is to write a function that groups the file names by their extensions and returns a dictionary where the keys are the extensions and the values are lists of file names with that exte... | ```python
def group_files_by_extension(file_names):
file_groups = {}
for file_name in file_names:
name, extension = file_name.rsplit('.', 1)
extension = extension.lower() # Convert the extension to lowercase
if extension in file_groups:
file_groups[extension].append(file_nam... | magicoder | python |
You are tasked with implementing a configuration class for a REST API in C#. The configuration class should have a protected property called `Configuration` of type `Sandbox2hireRestApiConfiguration`, with a private setter. Your task is to complete the implementation of the `Sandbox2hireRestApiConfiguration` class and ... | ```csharp
using System;
public class Sandbox2hireRestApiConfiguration
{
private Sandbox2hireRestApiConfiguration config;
public Sandbox2hireRestApiConfiguration(Sandbox2hireRestApiConfiguration config)
{
this.config = config;
}
public Sandbox2hireRestApiConfiguration GetConfiguration()
... | magicoder | csharp |
You are tasked with creating a script to automate the preparation of parallel corpora for natural language processing tasks. The script should handle the setup of the environment, networking, and execution of specific commands.
Your script should take the following parameters:
- `LANG`: The language setting for the en... | ```bash
#!/bin/bash
# Set default values
LANG=${LANG:-C.UTF-8}
NET=${NET:-host}
CONTAINER_NAME=${CONTAINER_NAME:-prepare-free-parallel-corpora}
COMMAND=${COMMAND:-bash}
# Start the container with specified parameters
docker run -e LANG=$LANG --net=$NET --name $CONTAINER_NAME -it prepare-free-parallel-corpora $COMMAND... | magicoder | shell |
You are tasked with creating a Python program that processes contact information from a file and generates an output contact file. The program should utilize command-line arguments for input and output file specifications.
Your program should accept the following command-line arguments:
- `--input FILE`: Specifies the... | ```python
import argparse
import os
def parse_contacts(input_file):
# Function to parse the input contact file and extract contacts and total frames
# Implementation details are not provided, as it depends on the specific format of the input file
# Placeholder implementation
contacts = [] # Placehold... | magicoder | python |
You are given a positive integer `n`. Your task is to write a function that takes `n` as input and returns the minimum number of operations required to make `n` equal to 1. The allowed operations are as follows:
1. If `n` is odd, you can subtract 1 from it.
2. If `n` is even, you can divide it by 2.
For example, if `n... | ```python
def min_operations_to_one(n: int) -> int:
operations = 0
while n > 1:
if n % 2 == 0:
n //= 2
else:
if n == 3 or n % 4 == 1:
n -= 1
else:
n += 1
operations += 1
return operations
```
The `min_operations_to_o... | magicoder | python |
You are tasked with implementing a custom Result type in Java that can represent either a success with a value or a failure with an error message. Additionally, you need to create a method to convert this Result type into a VoidResult type, which represents a result without a value. The VoidResult type should allow for... | ```java
// Result class representing a result with either a success value or an error value
class Result<S, E> {
private final S success;
private final E error;
private Result(S success, E error) {
this.success = success;
this.error = error;
}
public static <S, E> Result<S,... | magicoder | java |
You are tasked with implementing a Python function that calculates the discrete Fourier transform (DFT) of a given input signal using the formula:
\[ X[k] = \sum_{n=0}^{N-1} x[n] \cdot e^{-i 2 \pi \frac{kn}{N}} \]
Where:
- \( X[k] \) is the k-th frequency component of the DFT
- \( x[n] \) is the input signal
- \( N \... | ```python
import numpy as np
class DFTCalculator:
def __init__(self, resolution):
self.resolution = resolution
def calculate_dft(self, x):
N = len(x)
X = []
for k in range(N):
X_k = 0
for n in range(N):
X_k += x[n] * np.exp(-1j * 2 * np.p... | magicoder | python |
You are tasked with creating a Python program that tokenizes a given input string based on a set of rules. The program should take a string as input and return a list of tokens based on the following rules:
1. Tokens are separated by spaces.
2. Tokens can be alphanumeric strings, but they cannot start with a digit.
3. ... | ```python
import re
def tokenize_string(input_string):
# Using regular expression to tokenize the input string
tokens = re.findall(r'\b\w+\b|[.,!?]', input_string)
return tokens
# Test the function with the example input
input_string = "Hello, world! This is a test 123."
print(tokenize_string(input_string... | magicoder | python |
You are given a snippet of code that represents a mathematical expression involving matrices. Your task is to write a function that can evaluate this expression and return the result. The matrices are represented as two-dimensional arrays, and the operations involved are multiplication and subtraction.
The given code ... | ```python
def evaluateExpression(n, code):
matrices = [[0 for _ in range(n)] for _ in range(n)]
def ma(i, j):
return matrices[i][j]
def mb(i, j, val):
matrices[i][j] = val
for line in code:
exec(line)
return matrices[1][1] # Return the result from the specified position ... | magicoder | python |
You are given a string representing the status of a system. The status string consists of lowercase letters and may contain spaces. Your task is to write a function to determine the number of occurrences of each letter in the status string, ignoring spaces, and return the result as a dictionary where the keys are the l... | ```python
def count_status_letters(status: str) -> dict:
status = status.replace(" ", "").lower() # Remove spaces and convert to lowercase
letter_count = {}
for letter in status:
if letter.isalpha(): # Check if the character is a letter
if letter in letter_count:
letter... | magicoder | python |
You are tasked with creating a program that can parse and extract licensing information from a given source code file. The licensing information is typically found within comments at the beginning of the file. The format of the comments may vary, but they generally contain details such as the copyright holder, the year... | ```python
import re
def extract_license_info(file_path: str) -> dict:
with open(file_path, 'r') as file:
first_lines = [next(file) for _ in range(5)] # Read the first 5 lines of the file
comments = [line.strip() for line in first_lines if line.strip().startswith('#') or line.strip().startswith('//... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.