query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a version control system that supports submodules. A submodule is a separate Git repository embedded within a parent repository. Your goal is to create a class `VersionControl` with the following methods:
1. `add_submodule(subdir: str, url: str, checkout: str)`: This method should add ... | ```python
class VersionControl:
def __init__(self):
self.submodules = {}
def add_submodule(self, subdir: str, url: str, checkout: str):
submodule = {"checkout": checkout}
if url is not None:
submodule["url"] = url
self.submodules[subdir] = submodule
self._run... | magicoder | python |
You are working on a project that involves simulating the execution of MIPS assembly language instructions. You have access to the `geco.mips` module, which provides functionalities for working with MIPS instructions and registers.
Your task is to create a Python function that takes a list of MIPS assembly instruction... | ```python
def execute_mips_instructions(instructions):
registers = {f"${i}": 0 for i in range(32)} # Initialize all registers to 0
for instruction in instructions:
parts = instruction.split()
opcode = parts[0]
if opcode == "add":
dest_reg, src_reg1, src_reg2 = parts[1], part... | magicoder | python |
You are tasked with implementing a function that processes and trains a machine learning model using a given dataset. The function takes in various parameters and performs different operations based on the provided flags. Your task is to complete the function by implementing the missing parts and ensuring that the mode... | ```python
def process_and_train_model(data, flags, model, optimizer, all_comps, all_prots, pair_to_value_y, metrics, transformer, tasks, sim_data_node):
val_dataset = data["val"]
test_dataset = data["test"]
if flags["eval"]:
# Perform evaluation
evaluation_results = trainer.evaluate(model, ... | magicoder | python |
You are tasked with implementing a function that manipulates tilemap objects in a game environment. The function should take a parent game object and an integer as input and create a new tilemap game object with a specific sorting order. Additionally, the function should add a composite collider to the provided collide... | ```csharp
using UnityEngine;
public class TilemapManager : MonoBehaviour
{
public GameObject CreateTilemapGameObject(string name, GameObject parent, int sortingOrder)
{
GameObject tilemapObject = new GameObject(name);
tilemapObject.transform.parent = parent.transform;
// Add Tilemap co... | magicoder | csharp |
You are tasked with implementing a simple parser for a custom programming language. The language supports while loops and basic arithmetic expressions. The parser is expected to produce an Abstract Syntax Tree (AST) from the input tokens. The provided code snippet contains assertions that validate the correctness of th... | ```python
from typing import List
class TokenType:
END_STATEMENT = 'End of Statement'
EOF = 'End of File'
class Token:
def __init__(self, token_type, value):
self.token_type = token_type
self.value = value
class ASTNode:
pass
class While(ASTNode):
def __init__(self, condition, bl... | magicoder | python |
You are tasked with implementing a Python function that processes a given dataset using a machine learning classifier. The dataset consists of two arrays, `x` and `t`, where `x` represents the input features and `t` represents the target values. The code snippet provided shows a transformation of the `t` array using a ... | ```python
import numpy as np
from sklearn import svm, neighbors
from sklearn.linear_model import SGDClassifier, LogisticRegression
def process_data_with_classifier(x, t, classifier_type):
if classifier_type == 'SVM_sigmoid':
clf = svm.SVC(kernel='sigmoid', degree=9, gamma=10)
elif classifier_type == 'S... | magicoder | python |
You are tasked with creating a Python module that manages controllers for a financial data export service. The module should contain classes for different controllers, each responsible for exporting data from a specific trading session to a database. The provided code snippet is a partial example of such a module.
You... | ```python
from typing import List, Dict, Any
class BaseController:
def export_to_db(self, data: List[Dict[str, Any]]) -> bool:
raise NotImplementedError("Subclasses must implement export_to_db method")
class ControllerForQuotesByTradeDate(BaseController):
def export_to_db(self, data: List[Dict[str, An... | magicoder | python |
You are tasked with implementing a scoring system for a game. The game involves rolling five dice and scoring points based on the combination of the rolled dice. The scoring system is based on various combinations such as three of a kind, four of a kind, full house, small straight, large straight, and chance.
Your tas... | ```python
from typing import List
class Scorer:
def __init__(self):
self.scores = [None] * 13 # Initialize scores list with 13 elements
def score_three_of_kind(self, dice: List[int]) -> int:
if self.scores[6] is None:
self.scores[6] = sum(dice) if any(dice.count(x) >= 3 for x in d... | magicoder | python |
You are tasked with creating a Python function that interacts with a web application using Selenium and Django's LiveServerTestCase. The web application is designed to manage information about animals, and the function needs to test the creation of a new animal entry.
You are provided with a code snippet that sets up ... | The provided Python function test_create_animal_entry uses Selenium to interact with the web application and test the creation of a new animal entry. It first navigates to the animal creation page, fills in the form with the given attributes (nome_animal, predador, venenoso, domestico), submits the form, and then verif... | magicoder | python |
You are tasked with implementing a function that calculates the direction of the sun based on the given timestamp and geographic coordinates. The function should handle both 2D and 3D cases, where the 3D case involves a viewport with latitude and longitude, and the 2D case involves x, y, and z coordinates.
Write a fun... | ```javascript
function calculateSunDirection(timestamp, coordinates) {
if (coordinates.x !== undefined && coordinates.y !== undefined && coordinates.z !== undefined) {
// 3D case
const [x, y, z] = [coordinates.x, coordinates.y, coordinates.z];
return [x, -z, y];
} else if (coordinates.latitude !== undef... | magicoder | javascript |
You are tasked with creating a script to automate the setup and deployment of a static web application and its associated API using Azure Static Web Apps and Azure Functions. Your script should install the necessary tools and start the application and API locally for development and testing purposes.
Given the provide... | ```bash
#!/bin/bash
# Check if npm is installed
if ! command -v npm &> /dev/null
then
echo "npm is not installed. Installing npm..."
# Install npm
# Add installation command for npm here
# Example: sudo apt install npm
fi
# Install required npm packages
echo "Installing required npm packages..."
npm i... | magicoder | shell |
You are tasked with creating a Python package version checker. Your program should take a user-input version number and compare it to a predefined version number within the package. The version numbers are in the format "YYYY.MM.DD" (Year, Month, Day). Your program should output whether the user-input version is the sa... | ```python
def compare_versions(predefined_version, user_version):
try:
predefined_parts = list(map(int, predefined_version.split('.')))
user_parts = list(map(int, user_version.split('.')))
if predefined_parts == user_parts:
return "Same"
elif predefined_parts < user_part... | magicoder | python |
You are tasked with creating a Python script that automates the testing of a command-line interface (CLI) module. The script should be able to execute tests independently or be integrated into a larger test suite. It is important to ensure that the correct version of the module is being tested, especially when the libr... | ```python
import subprocess
import sys
def run_cli_tests():
# Check the version of the module being tested
# Ensure the correct version is used for testing
# Use a virtual environment or setuptools develop mode for testing against the development version
# Execute the tests for the CLI module using su... | magicoder | python |
You are working on a Django project that involves a model called `BitFieldTestModel`. This model has a field named `flags`, which is a bit field representing various flags. The `flags` field is defined using the `django_bitfield.BitField` class, allowing for bitwise operations on the flags.
The code snippet provided i... | ```python
from django.db.models import F
def update_and_check_flags(instance, flag_operations):
"""
Update the flags of the given instance based on the provided flag operations and return whether a specific flag is set.
Args:
instance: An instance of BitFieldTestModel.
flag_operations: A list of f... | magicoder | python |
You are tasked with implementing a function to calculate the final discounted price of a product based on its original price and the discount percentage. The function should take the original price and the discount percentage as input and return the final discounted price. The final discounted price should be formatted... | ```python
def calculateDiscountedPrice(originalPrice, discountPercentage):
discountedPrice = originalPrice - (originalPrice * discountPercentage / 100)
formattedPrice = "${:,.2f}".format(discountedPrice)
return formattedPrice
# Test the function
originalPrice = 1000
discountPercentage = 20
print(calculateD... | magicoder | python |
You are tasked with creating a regular expression pattern to match and extract specific types of tokens from a given input string. The tokens to be matched include currency amounts, percentages, and ellipses. The currency amounts can be in the format of $12.40 or $100,000. The percentages can be in the format of 82% or... | ```python
import re
input_string = "The total amount is $250.50, representing a 15.5% increase from the previous year. The report is due in... three days."
pattern = r'\$?\d+(\.\d+)?%?|\.\.\.'
matches = re.findall(pattern, input_string)
print(matches)
```
The regular expression pattern `r'\$?\d+(\.\d+)?%?|\.\.\.'`... | magicoder | python |
You are tasked with creating a program that simulates a simple banking system. The program should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry.
Your task is to implement a `Bank` struct and associated methods to support the required banking operations. T... | ```rust
use std::collections::HashMap;
struct Bank {
name: String,
accounts: HashMap<u32, f64>,
}
impl Bank {
fn new(name: &str) -> Bank {
Bank {
name: name.to_string(),
accounts: HashMap::new(),
}
}
fn create_account(&mut self, account_number: u32) {
... | magicoder | rust |
You are tasked with implementing a secure authentication mechanism for a web application. The provided code snippet is a part of a Django view that handles the callback from a third-party authentication service. The view expects a GET request with parameters `state` and `code`. It then validates the `state` parameter a... | The provided code snippet contains several potential security vulnerabilities that need to be addressed to ensure a secure authentication mechanism. Here are the identified issues and their corresponding solutions:
1. Lack of CSRF Protection:
The code does not include any protection against Cross-Site Request Forge... | magicoder | http |
You are tasked with creating a Python function to preprocess and load training and validation data for a machine learning model. The training data is stored in a TensorFlow dataset and the validation data is stored in NumPy arrays. Your task is to implement the function `load_data` that takes in the paths to the traini... | The `load_data` function first loads the training images and labels from the given directory using NumPy's `np.load` method. It then creates a TensorFlow dataset `dataset_train` from the loaded training images and labels using `tf.data.Dataset.from_tensor_slices`. The function repeats the training dataset indefinitely ... | magicoder | python |
You are tasked with creating a script to generate ISO images for different software distributions. The script should take in various parameters and create an ISO image accordingly.
Write a shell script named `mkisoimages.sh` that takes the following parameters:
- `-b` (optional): Indicates that the ISO image should be... | ```bash
#!/bin/bash
# Function to display usage information
usage() {
echo "Usage: mkisoimages.sh [-b] image-label image-name base-bits-dir [extra-bits-dir]"
exit 1
}
# Validate the number of arguments
if [ $# -lt 4 ] || [ $# -gt 5 ]; then
usage
fi
# Parse the command-line options
bootable=false
if [ "$1" == "... | magicoder | shell |
You are tasked with implementing a Python function that converts a given input to a boolean value. The function should handle various input types and return the corresponding boolean value based on the input rules.
You are provided with a partial code snippet that includes a `config` function and a `convert_bool` func... | ```python
from dataclasses import dataclass
from functools import partial
config = partial(dataclass, kw_only=True)
def convert_bool(x):
if isinstance(x, bool): # If input is already a boolean, return it
return x
elif isinstance(x, str): # If input is a string, check for boolean representations
... | magicoder | python |
You are tasked with implementing a data structure to represent 3D objects in a graphics application. The structure should include optional fields for the object's name and rotation. The rotation is represented using a unit quaternion, which is a 4-dimensional vector. Additionally, the structure should support serializa... | ```rust
use serde::Serialize;
use nalgebra::UnitQuaternion;
#[derive(Serialize)]
pub struct Object3D {
#[cfg(feature = "names")]
#[cfg_attr(feature = "names", serde(skip_serializing_if = "Option::is_none"))]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rotation: ... | magicoder | rust |
You are tasked with creating a script to automate the waiting process for the availability of specific services on different hosts and ports. The script should utilize environment variables and a custom `wait-for.sh` script to wait for the services to become accessible.
The provided code snippet sets the `MHOST` envir... | ```bash
#!/bin/bash
# Set MHOST environment variable
export MHOST=${URI[$len-2]}
# Wait for the main service to become available
echo "Waiting for ${MHOST}:${MPORT} service..." && \
./wait-for.sh "$MHOST:$MPORT" -t 60 --
# Wait for the secondary service to become available
echo "Waiting for ${EHOST}:${EPORT} ser... | magicoder | shell |
You are tasked with implementing a function that takes a list of integers as input and returns a string representation of the list in reverse order.
Write a function `reverse_list_to_string` that takes a list of integers `input_list` as its parameter and returns a string representation of the list in reverse order. Th... | ```python
from typing import List
def reverse_list_to_string(input_list: List[int]) -> str:
reversed_list = list(map(str, reversed(input_list)))
return "".join(reversed_list)
```
The `reverse_list_to_string` function takes the input list and reverses it using the `reversed` function. Then, it maps each intege... | magicoder | python |
You are tasked with creating a unit test for a component in an Angular application. The component, `XmUserLoginWidgetComponent`, is responsible for rendering a user login widget. The test environment is set up using Angular's TestBed and the component is to be tested in isolation. Additionally, a mock service, `MockUse... | ```typescript
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { XmUserLoginWidgetComponent } from './xm-user-login-widget.component';
import { XmUserService } from 'path-to-xm-user-service'; // Replace with actual path
import { MockUserService } from 'path-to-mock-user-service'; // Repl... | magicoder | typescript |
You are tasked with creating a Python function that analyzes a given directory and its subdirectories to count the number of Python files that import specific modules. Your function should take the directory path and the module names as input and return a dictionary with the module names as keys and the count of Python... | ```python
import os
import ast
def count_imports(directory, module_names):
import_counts = {module: 0 for module in module_names}
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
with ... | magicoder | python |
You are tasked with implementing a Python decorator that caches the results of a function to a file. The decorator should check if the cache file exists and is not expired before calling the function. If the cache file exists and is valid, the decorator should return the cached result without calling the function. If t... | ```python
import os
import json
from time import time
from os import path
def cache_to_file(filename, expiration_time):
def decorator(func):
def wrapper(*args, **kwargs):
if path.exists(filename) and time() - path.getmtime(filename) < expiration_time:
with open(filename, 'r') as... | magicoder | python |
You are tasked with implementing a middleware system for a web framework in Rust. The middleware system should allow for the insertion of middleware functions that can modify the incoming request and outgoing response. The provided code snippet demonstrates the usage of the middleware system, where the `any` variable i... | ```rust
// Define a trait for middleware
trait Middleware {
fn handle(&mut self, req: &mut Request, res: &mut Response);
}
// Implement the middleware system
struct MiddlewareSystem {
middlewares: Vec<Box<dyn Middleware>>,
}
impl MiddlewareSystem {
fn new() -> Self {
MiddlewareSystem {
... | magicoder | rust |
You are tasked with implementing a function `do_it(hex_str)` that takes a hexadecimal string as input and returns the corresponding ASCII string after decoding the hexadecimal representation.
The function should perform the following steps:
1. Convert the input hexadecimal string to its binary representation.
2. Decod... | ```python
from binascii import unhexlify
def do_it(hex_str: str) -> str:
binary_str = unhexlify(hex_str) # Convert hexadecimal string to binary representation
ascii_str = binary_str.decode('utf-8') # Decode binary representation to obtain ASCII string
return ascii_str
```
The `do_it` function uses the `u... | magicoder | python |
You are tasked with implementing a simple identity provider system that generates unique user IDs for a given username. The system should assign a unique numerical ID to each username, starting from 1 and incrementing by 1 for each new username. Your task is to create a class `IdentityProvider` with the following metho... | ```javascript
class IdentityProvider {
constructor() {
this.userMap = new Map();
this.nextID = 1;
}
registerUser(username) {
if (!this.userMap.has(username)) {
this.userMap.set(username, this.nextID);
this.nextID++;
}
}
getUserID(username) {
return this.userMap.get(username);... | magicoder | javascript |
You are tasked with creating a script to automate the installation of Java Development Kit (JDK) on a Linux system. The script should handle the download, validation, and extraction of the JDK archive. Additionally, it should check if the JDK is already installed and skip the installation if it is. Below is a partial s... | ```bash
done
if [ $1 ]; then
if [ $1 = "-i jdk" ]; then
if type -p java; then
echo 'JDK is already installed.'
exit 0
fi
fi
fi
download() {
# Implement the download functionality here
# Example: wget <jdk_download_url>
}
is_valid_archive() {
# Implement the archive validation logic ... | magicoder | shell |
You are tasked with implementing a function that calculates the total number of parameters in a given neural network model. The parameters include both trainable and non-trainable parameters such as weights, biases, and other model parameters.
You are given a code snippet that represents a function with incomplete imp... | ```python
def calculate_total_parameters(model):
"""
Calculate the total number of parameters in the given neural network model.
Args:
model: The neural network model for which the parameters need to be calculated.
Returns:
int: The total number of parameters in the model.
"""
total_pa... | magicoder | python |
You are tasked with implementing a custom serialization packer for a networking library in C#. The serialization packer should be able to serialize and deserialize objects to and from a byte array. The packer should support various data types and handle the serialization and deserialization process efficiently.
You ar... | ```csharp
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using ZYSocket.Interface;
namespace NetxFrame
{
public class SerializationPacker
{
// Serialize an integer to a byte array
public byte[] PackInt(int value)
{
r... | magicoder | csharp |
You are tasked with implementing a MIDI event handling system. MIDI (Musical Instrument Digital Interface) is a technical standard that describes a protocol, digital interface, and connectors that allow a wide variety of electronic musical instruments, computers, and other related devices to connect and communicate wit... | ```javascript
class SequencerSpecificEvent {
constructor(id, data) {
this.id = id;
this.data = data;
}
}
// Handling MIDI meta event
const metaEventTypeNum = 0x12; // Example meta event type number
let event;
if (metaEventTypeNum === 0x12) {
const id = "exampleId"; // Example id
const data = [0x01, 0x... | magicoder | javascript |
You are working on a computer vision project and need to write a Python function to find the extreme points of a contour in an image using the OpenCV library. The function should take an input image and return the coordinates of the extreme points of the contour.
Write a Python function called `find_extreme_points` th... | ```python
import cv2
import numpy as np
def find_extreme_points(image, contour):
# Find the extreme points of the contour
leftmost = tuple(contour[contour[:, :, 0].argmin()][0])
rightmost = tuple(contour[contour[:, :, 0].argmax()][0])
topmost = tuple(contour[contour[:, :, 1].argmin()][0])
bottommos... | magicoder | python |
You are working on a project that involves interacting with a distributed configuration management system. The system uses a combination of Zookeeper and a custom SDK called `huskar_sdk_v2` to manage and retrieve configuration data. Your task is to write a Python function that retrieves a specific configuration value f... | ```python
def retrieve_and_calculate_config_value(key):
# Connect to the Zookeeper configuration management system
switch_client(OVERALL)
# Retrieve the configuration value for the given key
config_value = config_client.get(key)
# Perform a calculation on the retrieved value using the sqlalchemy l... | magicoder | python |
You are tasked with implementing a Python class that represents a hierarchical structure of namespaces and types. The structure consists of members, each of which can be a namespace or a type. A type can be either a simple type or a namespaced type. A namespaced type is a type that belongs to one or more namespaces.
Y... | ```python
class NamespacedType:
def __init__(self, namespaces):
self.namespaces = namespaces
class Type:
pass
class Namespace:
pass
class Structure:
def __init__(self, members):
self.members = members
# Test the implementation
namespace1 = Namespace()
namespace2 = Namespace()
type1 =... | magicoder | python |
You are tasked with implementing a modal component for a web application. The modal component should be able to display various types of content, such as text, images, forms, or custom components, and provide the ability to close the modal when the user interacts with it.
Your task is to create a JavaScript class for ... | ```javascript
class ModalComponent {
constructor() {
this.modalElement = document.createElement('div');
this.modalElement.classList.add('modal');
this.modalContent = document.createElement('div');
this.modalContent.classList.add('modal-content');
this.modalElement.appendChild(this.modalContent);
... | magicoder | javascript |
You are tasked with creating a Python class that manages the installation and versioning of packages for a software project. Your class should be able to handle the addition of new packages, updating package versions, and providing a description of the installed packages. The class should also have the ability to store... | ```python
class PackageManager:
def __init__(self, version, packages, description, author, author_email):
self.version = version
self.packages = packages
self.description = description
self.author = author
self.author_email = author_email
def add_package(self, package_na... | magicoder | python |
You are tasked with implementing a key-logging functionality in a C# application. To achieve this, you need to create a delegate for a key-sniffer callback function that will be used to capture key events. The delegate should take in parameters representing the input character, key flags, virtual key, and a reference t... | ```csharp
public unsafe delegate int KeySnifferCallback(byte inChar, KeyFlags inFlags, byte inVirtualKey, void* inRefcon);
```
The provided solution defines a C# delegate named `KeySnifferCallback` with the specified signature. The `unsafe` keyword is used to indicate that the delegate is used in an unsafe context, al... | magicoder | csharp |
You are tasked with creating a Python program that processes a given XML file and extracts specific information from it. The XML file contains data related to various methods and their associated attributes. Your program needs to parse the XML file, extract the relevant information, and perform specific operations base... | ```python
import xml.etree.ElementTree as ET
# Function to parse the XML file and extract method names and numbers
def extract_methods(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
methods = {}
for method in root.find('methods').iter('method'):
name = method.attrib['name']
... | magicoder | python |
You are tasked with creating a Rust program that processes data from a Mentat database using the `mentat_db` crate. The Mentat database is a powerful, scalable, and efficient database designed for complex data queries. Your program will need to perform specific operations on the data and produce a desired output.
Your... | ```rust
fn process_mentat_data(db_conn: &mentat_db::Conn, attribute: &str, value: &str, extract_attributes: &[&str]) -> Vec<Vec<String>> {
// Query the database to retrieve all entities that satisfy the given attribute and value pair.
let query = format!("[:find ?e :where [?e {} ?v] [(= ?v \"{}\")]]", attribute... | magicoder | rust |
You are tasked with implementing a Python decorator that wraps boolean operations for label expressions in a GIS (Geographic Information System) application. The decorator should handle the logical AND, OR, and NOT operations for label expressions used in GIS mapping.
Your task is to complete the implementation of the... | ```python
def boolean_op_wrapper(and_=None, or_=None, not_=None):
def decorator(func):
def wrapper():
result = ""
if and_:
result += " AND ".join(and_)
if or_:
if result:
result += " OR "
result += " OR "... | magicoder | python |
You are tasked with creating a program that can parse and analyze PHP code to extract specific information. Your program should be able to identify and extract the content within PHP sections, such as sections defined by `<?php ... ?>` tags, and perform a specific operation on the extracted content.
Write a function o... | ```python
import re
def extract_php_sections(php_code):
php_sections = re.findall(r'(?<=<\?php).*?(?=\?>)', php_code, re.DOTALL)
return [section.strip() for section in php_sections]
# Test the function with the given example
input_php_code = """
</div> <!-- /#container -->
</div></div>
<?php echo "Hello, Worl... | magicoder | python |
You are working on a cryptocurrency investment platform called Krypfolio. The platform allows users to allocate their investments across different cryptocurrencies based on a specified allocation strategy. The code snippet provided is a part of a Python class method that is responsible for checking the validity of an a... | ```python
class Krypfolio:
def __init__(self):
# Initialize Krypfolio attributes
pass
def _print(self, message):
# Helper method for printing messages
pass
def rebalance(self, krypfolio, prices, alloc, investment):
total_value = sum(krypfolio.values())
targe... | magicoder | python |
You are working on a web application framework that includes an admin module for managing various models. The code snippet provided is a part of the framework's routing system, which maps URLs to handler classes and their methods. Your task is to implement a function that retrieves the application routes for the admin ... | ```python
from . import admin_settings
from .handlers import AdminHandler
def get_application_routes(handler_cls=None):
if not handler_cls:
handler_cls = AdminHandler
if handler_cls.__name__ in admin_settings._application_routes:
return admin_settings._application_routes[handler_cls.__name__]
... | magicoder | python |
You are tasked with creating a Python script that automates the testing process for a project using the `py.test` framework. The script should run the tests in parallel using 4 processes, disable socket communication, treat runtime warnings as errors, measure test coverage, generate an HTML coverage report, and fail if... | ```python
import subprocess
def run_tests():
command = [
"py.test",
"-n", "4", # Run tests in parallel using 4 processes
"--disable-socket", # Disable socket communication
"-W", "error::RuntimeWarning", # Treat runtime warnings as errors
"--cov=src", # Measure test cover... | magicoder | python |
You are tasked with creating a Python function that utilizes the `phonemizer` library to convert a given text into its phonetic representation. The `phonemizer` library provides a function `phonemize` that takes text as input and returns its phonetic representation based on the specified language and accent.
You need ... | ```python
import sys
from phonemizer import phonemize
def convert_to_phonetic(text: str, language: str, accent: str) -> str:
phonetic_representation = phonemize(text, language=language, accent=accent)
return phonetic_representation
```
The `convert_to_phonetic` function takes the input `text`, `language`, and ... | magicoder | python |
You are tasked with implementing a submission processing system for a plugin-based API. The provided code snippet is a part of this system and includes a `Log` class for logging API activities and a function `run_submission` to process incoming data. The `run_submission` function checks for the presence of certain fiel... | ```python
class BadRequestException(Exception):
pass
class Log:
def __init__(self, name, file):
self.name = name
self.file = file
def log(self, message):
# Implementation of log method is not provided as it is not relevant to the problem.
API_LOG = Log("APIv10", "logs/APIv10.log")... | magicoder | python |
You are tasked with implementing a custom mapping function in Swift that can convert a dictionary to a specific data structure. The data structure is defined by a struct with properties that correspond to the keys in the dictionary. Your task is to create a function that takes a dictionary and a struct type as input, a... | ```swift
func mapDictionaryToStruct<T>(_ dictionary: [String: Any], _ type: T.Type) -> T? {
guard let structType = type as? Any.Type else {
return nil
}
var instance = structType.init()
let mirror = Mirror(reflecting: instance)
for case let (label?, value) in mirror.children {... | magicoder | swift |
You are tasked with implementing a custom clock interface in Java. The interface should provide methods for retrieving the current time and the elapsed time since system boot.
Your task is to create a class that implements the given interface and provides the required functionality. You should also write a method to c... | ```java
// Clock interface
interface Clock {
long time();
long tick();
}
// Custom clock implementation
class CustomClock implements Clock {
@Override
public long time() {
return System.currentTimeMillis();
}
@Override
public long tick() {
return SystemClock.elapsedRealtime... | magicoder | java |
You are given a list of integers representing a rotated version of a sorted array. Your task is to write a function to find the minimum element in this rotated array. The rotated array is formed by splitting the original sorted array into two non-empty subarrays and reversing their order. For example, the original sort... | ```python
from typing import List
def find_minimum_in_rotated_array(rotated: List[int]) -> int:
left, right = 0, len(rotated) - 1
while left < right:
mid = left + (right - left) // 2
if rotated[mid] > rotated[right]:
left = mid + 1
else:
right = mid
return... | magicoder | python |
You are tasked with creating a function that validates a given URL based on specific criteria. The function should take a URL as input and return a boolean value indicating whether the URL meets the specified requirements.
The URL validation criteria are as follows:
1. The URL must start with either "http://" or "http... | ```php
function validateURL(string $url): bool {
$pattern = '/^(http|https):\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*([\/][a-zA-Z0-9-\/]+)*$/';
return (bool) preg_match($pattern, $url);
}
// Test cases
var_dump(validateURL("http://www.example.com/page1")); // Output: true
var_dump(validateURL("https://sub-domain.exa... | magicoder | php |
You are tasked with creating a Python program to simulate a simple game using the BBC micro:bit. The game involves controlling a scrolling action using the micro:bit's accelerometer and button A. The program should display a happy face on the micro:bit's LED matrix and then continuously check for button A presses. When... | ```python
from microbit import *
def main():
display.show(Image.HAPPY)
while True:
if button_a.is_pressed():
y = accelerometer.get_y()
mouse.scroll(y // 100)
sleep(300)
if __name__ == "__main__":
main()
```
In the solution, we import the necessary modules from... | magicoder | python |
You are tasked with creating a Python function that simulates a simple robotic arm reaching for a target in a 2D environment. The function will take in the initial position of the robotic arm and the target position, and return a sequence of images representing the arm's movement towards the target.
The function signa... | ```python
import numpy as np
from typing import Tuple, List
import matplotlib.pyplot as plt
def simulate_robotic_arm(initial_position: Tuple[float, float], target_position: Tuple[float, float]) -> List[np.ndarray]:
# Initialize variables
arm_position = np.array(initial_position)
target = np.array(target_po... | magicoder | python |
You are tasked with implementing a class that manages notes for a graphical user interface (GUI) component. The class should provide methods to set a tooltip for the header, label, and note indicator, as well as a method to toggle the visibility of the note indicator. Additionally, the class should ensure that the visi... | ```java
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ToolTip;
import org.eclipse.swt.widgets.Widget;
public class NoteManager {
private Control header;
private Label label;
private Control noteIndicator... | magicoder | java |
You are tasked with creating a Python decorator that measures the execution time of a given function and prints the elapsed time in milliseconds. The decorator should be implemented using the `async` and `await` keywords to support asynchronous functions. You should also utilize the `asyncio` library for managing async... | ```python
import time
import asyncio
from functools import wraps
from typing import Callable, Any
def measure_execution_time(func: Callable) -> Callable:
@wraps(func)
async def wrapper(*args, **kwargs):
start_time = time.time() if not asyncio.iscoroutinefunction(func) else time.monotonic()
resu... | magicoder | python |
You are tasked with implementing a function to calculate the derivative of a given mathematical function using the finite difference method. The finite difference method is a numerical technique for estimating the derivative of a function at a particular point by evaluating the function at nearby points.
You are give... | ```python
def calculate_derivative(i_calc, eps):
derivatives = []
for ih in range(i_calc.size()):
fs = []
gs = []
c_orig = i_calc[ih]
for signed_eps in [eps, -eps]:
# Calculate the function values at c_orig + signed_eps and c_orig
f_plus = f(c_orig + signe... | magicoder | python |
You are tasked with implementing a simplified version of a BitSet data structure in C++. A BitSet is a fixed-size collection of bits, where each bit represents a boolean value (0 for false, 1 for true). The BitSet supports basic operations such as setting a bit, clearing a bit, checking if a bit is set, and performing ... | ```cpp
#include <vector>
class BitSet {
private:
std::vector<unsigned long long> bits;
public:
BitSet(int size) {
bits.resize((size + 63) / 64, 0);
}
void set(int pos) {
int index = pos / 64;
int bit = pos % 64;
bits[index] |= (1ULL << bit);
}
void clear(int p... | magicoder | cpp |
You are working on a project that involves training a neural network using TensorFlow. As part of the training process, you need to restore an embedding matrix from a specified path and then initialize the remaining variables before starting the training. Additionally, you are required to create a summary writer for lo... | ```python
import tensorflow as tf
def prepare_training(embedding_path, train_set, hyper, param, restorer, td):
with tf.Session() as sess:
# Restore embedding matrix first
restorer.restore(sess, embedding_path)
# Initialize other variables
gvariables = tf.global_variables()
... | magicoder | python |
You are tasked with exploiting a buffer overflow vulnerability in a simple program to gain control over the instruction pointer and redirect the program flow to execute arbitrary code. The provided code snippet is part of the vulnerable program, and your goal is to craft a payload that will exploit the program and gain... | To exploit the buffer overflow vulnerability and execute arbitrary code, you can construct a payload that overwrites the return address of the `change` function with the address of `system_plt`, followed by the address of a string containing the command you want to execute.
Here's an example of a payload in Python tha... | magicoder | python |
You are tasked with creating a C++ program that interacts with various libraries and interfaces to manage the power state of a system. The program will utilize the provided libraries and interfaces to query and set the power state of the system based on certain conditions.
The program should perform the following task... | ```cpp
#include <nlohmann/json.hpp>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/message/types.hpp>
#include <string>
#include <sys_info_param.hpp>
#include <transporthandler.hpp>
#include <tuple>
#include <vector>
#include <xyz/openbmc_project/Common/error.hpp>
#i... | magicoder | cpp |
You are tasked with implementing a program that can analyze the structure of an HTML file and determine the nesting level of each HTML tag. The nesting level of a tag is defined as the number of ancestor tags it is contained within. For example, a tag directly inside the `<body>` tag would have a nesting level of 1, wh... | ```python
from bs4 import BeautifulSoup
def calculate_nesting_levels(html_string: str) -> dict:
soup = BeautifulSoup(html_string, 'html.parser')
tag_nesting_levels = {}
def calculate_nesting(tag, level):
tag_nesting_levels[tag.name] = level
for child in tag.find_all(recursive=False):
... | magicoder | python |
You are tasked with implementing a text transformation function that replaces certain characters in a string based on a given dictionary mapping. The mapping consists of multiple letter definitions, where each key-value pair represents a character and its corresponding replacement string. If the input character matches... | ```rust
use std::collections::HashMap;
fn transform_text(text: &str, mapping: &HashMap<char, String>) -> String {
let mut result = String::new();
for character in text.chars() {
let lower_case = character.to_ascii_lowercase();
match mapping.get(&lower_case) {
Some(replacement) => r... | magicoder | rust |
You are tasked with implementing a function to filter and extract specific items from a Genomic Feature Format (GFF) file based on certain attributes. The GFF file contains information about genomic features such as genes, transcripts, and proteins, and is structured in a tab-delimited format with nine columns represen... | ```python
import datetime
class GFF:
def __init__(self):
self._header_general = []
def check_attr(filter_attr, item_attr):
for key in filter_attr.keys():
if key not in item_attr or item_attr[key] not in filter_attr[key]:
return False
return True
if len(inGFF) == 0:
raise V... | magicoder | python |
You are required to implement a function `decodeString` that takes a string `s` as input and returns the decoded string. The input string `s` is encoded in a specific format where some substrings are repeated multiple times.
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square bracke... | ```python
def decodeString(s: str) -> str:
stack = []
current_num = 0
current_str = ''
for char in s:
if char.isdigit():
current_num = current_num * 10 + int(char)
elif char == '[':
stack.append(current_str)
stack.append(current_num)
c... | magicoder | python |
You are tasked with implementing a function that securely stores a user's authentication token in the browser's local storage. The function should take an authentication token as a parameter and store it in the local storage using a secure approach.
Write a function `setToLocalStorage` that takes an object with an `au... | ```javascript
const setToLocalStorage = ({ authToken }) => {
try {
if (typeof authToken !== 'string' || authToken === '') {
throw new Error('Invalid authentication token');
}
// Use the Web Crypto API to generate a secure key for encryption
window.crypto.subtle.generateKey(
{
name... | magicoder | javascript |
You are working on an Angular application that manages user roles and permissions. The code snippet provided is a part of the Angular component for the admin interface. Your task is to implement a feature that restricts access to certain sections of the admin interface based on the user's role.
You have the following ... | ```typescript
import { ServisService } from '../servis.service';
import { KorisnikPom } from '../korisnikpom';
import { Preduzece } from '../preduzece';
import { Poljoprivrednik } from '../poljoprivrednik';
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
@Component({
sele... | magicoder | typescript |
You are tasked with implementing a class for managing enemies in a 2D game. The class, `Enemy`, has the following attributes and behaviors:
Attributes:
- `sprites`: A pointer to the texture containing the sprites for the enemies.
- `life`: An integer representing the remaining life of the enemy.
- `score`: An integer ... | ```cpp
#include "ModuleTextures.h"
#include "ModuleCollision.h"
struct Animation {
float speed;
bool loop;
// Other animation properties
};
enum COLLIDER_TYPE {
COLLIDER_ENEMY
// Other collider types
};
class Enemy {
public:
SDL_Texture* sprites;
int life;
int score;
Animation AnimWasp;
Animation* animatio... | magicoder | cpp |
You are tasked with creating a script to parse and validate the configuration parameters for an etcd (distributed key-value store) instance. The etcd configuration is provided as a command-line snippet, and your script should extract and validate the following parameters:
- `data-dir`: The directory path for storing th... | ```python
import re
def validate_etcd_config(config_str: str) -> bool:
config_params = {}
for param in config_str.split()[1:]:
key, value = param.split('=')
config_params[key.strip('-')] = value
if not config_params['data-dir'] or not config_params['name']:
return False
if not... | magicoder | python |
You are tasked with implementing a function to set the state of specific tasks within a directed acyclic graph (DAG) in an Apache Airflow environment. The function should be able to alter the state of individual tasks and update the overall state of the DAG run. The code snippet provided is a part of a test suite for t... | ```python
from airflow.models import State
def set_task_state(dag, task_id, date, state):
altered_tasks = set()
for task in dag.tasks:
if task.task_id == task_id:
task.set_state(state, date)
altered_tasks.add(task.task_id)
dag_run = dag.get_dagrun(date)
dag_state = Stat... | magicoder | python |
You are tasked with implementing a class for managing animated sprites in a 2D game. The class, named `Ship`, is responsible for drawing the sprite on the screen and playing a death animation when the ship is destroyed. The provided code snippet shows two methods of the `Ship` class: `draw` and `playDeathAnimation`.
T... | ```python
class Ship:
def __init__(self, x, y, width, height, animation):
self.x = x
self.y = y
self.width = width
self.height = height
self.animation = animation
def draw(self, screen):
# Draw the ship at its current position on the screen
screen.draw(se... | magicoder | python |
You are tasked with implementing a function that processes a series of transactions in a financial system. Each transaction is represented by a reference to the last transaction and the old last transaction, as well as a code section. The function should process these transactions and return the final result.
You are ... | ```python
from typing import List, Any
def processTransactions(refs: List[str], code: str) -> Any:
# Process the transactions based on the references and code
# Your implementation here
pass # Placeholder, replace with actual implementation
```
```python
# Example implementation of processTransactions fun... | magicoder | python |
You are tasked with implementing a C++ template metaprogramming problem related to the manipulation of type traits. Your goal is to create a type trait that determines whether a given type is a specialization of a particular template class.
You are provided with a code snippet that contains the end of a C++ header fil... | ```cpp
template <typename T, template <typename...> class Template>
struct is_specialization_of : std::false_type {};
template <template <typename...> class Template, typename... Args>
struct is_specialization_of<Template<Args...>, Template> : std::true_type {};
// Example usage:
// static_assert(is_specialization_of... | magicoder | cpp |
You are tasked with implementing a simplified version of a dynamic array class called `podarray`. The `podarray` class is designed to store elements of a specific type `eT` and provide various operations for accessing and modifying the elements. The class provides the following member functions and constructors:
1. `e... | ```cpp
#include <iostream>
#include <cstddef>
template<typename eT, typename uword>
class podarray {
private:
eT* data; // Pointer to the array of elements
uword size; // Current size of the array
public:
// Constructor to initialize the podarray with new_N elements from the array X
explicit podarra... | magicoder | cpp |
You are tasked with implementing a program to find the minimum path sum in a triangle. The triangle is represented as a list of lists, where each inner list represents a row of the triangle. The minimum path sum is the sum of the numbers along a path from the top to the bottom of the triangle, moving only to adjacent n... | ```python
def find_min_path(triangle):
# Start from the second bottom row and work upwards
for row in range(len(triangle) - 2, -1, -1):
for i in range(len(triangle[row])):
# For each element, add the minimum of the two adjacent elements from the row below
triangle[row][i] += min(... | magicoder | python |
You are tasked with implementing a custom pinned map data structure in Python. A pinned map is a type of hash table that allows for efficient key-value pair storage and retrieval. Your task is to create a Python class `PinnedMap` that mimics the behavior of the given code snippet.
The `PinnedMap` class should have the... | ```python
import ctypes as ct
class PinnedMap(HashTable):
def __init__(self, map_path, keyType, valueType, maxEntries):
super().__init__() # Assuming HashTable is a predefined class
map_fd = libbcc.lib.bpf_obj_get(ct.c_char_p(map_path))
if map_fd < 0:
raise ValueError("failed ... | magicoder | python |
You are tasked with implementing a neural network architecture for a reinforcement learning agent. The given code snippet is a part of the implementation of the network. The `conv_net_on` function applies convolutional layers to the input state, and the `hidden_layers_on` function creates hidden layers with specific si... | ```python
self.output_action = slim.fully_connected(scope='fc',
inputs=hidden_layers,
num_outputs=action_dim,
weights_initializer=weights_initializer,
a... | magicoder | python |
You are tasked with automating the configuration of network devices using Python and the Netmiko library. You have been provided with an Excel file named "Example4-Device-Details.xlsx" containing details of various network devices. Each row in the Excel file represents a different device and contains the following colu... | ```python
import pandas as pd
from netmiko import ConnectHandler
# Read Excel file of .xlsx format
data = pd.read_excel(io="Example4-Device-Details.xlsx", sheet_name=0)
# Iterate through each row in the Excel file
for index, row in data.iterrows():
device_name = row['Device Name']
ip_address = row['IP Address... | magicoder | python |
You are tasked with creating a custom error handling system for a Rust application. Your goal is to implement a set of custom error types and associated error messages to handle different kinds of errors that may occur during the application's execution.
You are provided with a code snippet that defines two custom err... | ```rust
use thiserror::Error;
use tonic::transport::Error;
use tonic::Status;
#[derive(Error, Debug)]
pub enum CustomError {
#[error("Failed to connect to {service}: {source}")]
ConnectionError {
service: &'static str,
source: Error,
},
#[error("Error returned from {service}: {source}")... | magicoder | rust |
You are tasked with creating a parser for a simplified version of a Rust code snippet. The code snippet provided is a part of a Rust macro invocation. Your task is to write a function that parses the given input and extracts the imported types and derive macros from the macro invocation.
The input consists of a series... | ```rust
fn parse_macro_invocations(input: &str) -> Vec<(Vec<String>, Vec<String>)> {
input
.split(';')
.map(|macro_invocation| {
let parts: Vec<&str> = macro_invocation.trim().split(',').collect();
let imported_types: Vec<String> = parts[0].split_whitespace().map(|s| s.to_str... | magicoder | rust |
You are tasked with creating a preference service class that manages user preferences for a software application. The preference service allows users to set and retrieve preferences, as well as subscribe to preference change events. Your goal is to implement a method for handling preference changes and updating the cor... | ```typescript
// PreferenceService class definition
class PreferenceService {
private preferences: Map<string, any> = new Map();
private preferenceChangeSubscribers: Map<string, ((e: PreferenceChangeEvent) => void)[]> = new Map();
// Method to set a preference
set<T>(name: string, value: T): void {
this.pr... | magicoder | typescript |
You are tasked with implementing a utility function to convert a given project path from UTF-16 encoding to UTF-8 encoding and vice versa. The provided code snippet contains a C++ function that converts a UTF-16 string to a UTF-8 string and sets the converted path in a project instance. Additionally, there is a functio... | ```cpp
#include <string>
#include <codecvt>
#include <locale>
// Function to retrieve the project path in UTF-8 encoding
EXPORT_API std::string GetProjectPathUtf8()
{
// Retrieve the project path in UTF-16 encoding
std::u16string utf16Path = Project::getInstance()->GetProjectPath();
// Convert UTF-16 to U... | magicoder | cpp |
You are tasked with implementing a shell script that processes a series of commands based on a given code snippet. The code snippet contains a sequence of commands and file references, and your goal is to understand and execute these commands in the correct order.
The code snippet provided is as follows:
```
. ${0%03-... | The given code snippet is a series of shell commands that need to be executed in the correct order. Let's break down the commands and their expected behavior:
1. `. ${0%03-meta.sh}setup.sh`: This command sources the `setup.sh` script after performing a parameter expansion on `${0%03-meta.sh}`. The parameter expansion ... | magicoder | shell |
You are tasked with implementing a custom comparator function in JavaScript to sort an array of objects based on a specific property. The custom comparator should be concatenated into the array and used to sort the objects based on the specified property.
You are given an array of objects, where each object represents... | ```javascript
function sortRowsByProperty(rows, property) {
const customComparator = (a, b) => {
if (a[property] < b[property]) {
return -1;
}
if (a[property] > b[property]) {
return 1;
}
return 0;
};
rows.sort(customComparator);
return rows;
}
const rows = [
{ name: 'Alice',... | magicoder | javascript |
You are tasked with creating a web application that allows users to submit feedback forms. The application uses the ASP.NET Core framework, and you need to implement server-side validation for the input fields. The provided code snippet is a part of the feedback form model and demonstrates the use of data annotations f... | ```csharp
using System;
using System.ComponentModel.DataAnnotations;
public class InputModel
{
[Required]
public string Input { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}
public class CustomValidationAttribute : ValidationAttribute
{
private readonly string _all... | magicoder | csharp |
You are tasked with implementing a custom hook in a React application that manages the state of a subscription to a data stream. The hook should utilize the `useRef`, `useState`, and `useEffect` hooks to achieve this functionality.
Your task is to create a custom React hook called `useDataStream` that takes in a `subj... | ```javascript
import { useRef, useState, useEffect } from 'react';
function useDataStream(subject, selector) {
const selectorValue = useRef(selector(subject.getValue()));
const [state, setState] = useState(1);
useEffect(() => {
const subs = subject?.subscribe({
next: (value) => {
selectorValue... | magicoder | javascript |
You are tasked with implementing a function that parses a given SVG (Scalable Vector Graphics) code and counts the occurrences of specific attributes within the code. SVG is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. The function should take the SVG code ... | ```python
import xml.etree.ElementTree as ET
def count_svg_attributes(svg_code: str) -> dict:
attribute_counts = {}
root = ET.fromstring(svg_code)
g_tag = root.find('g')
if g_tag is not None:
for element in g_tag:
for attribute in element.attrib:
if attribute in attr... | magicoder | python |
You are tasked with implementing a notification system for a software application. The system should allow objects to subscribe to notifications about changes in their properties. To achieve this, you need to create a set of classes and interfaces that enable the notification mechanism.
Your task is to implement the `... | ```csharp
// Define the INotifyPropertyChanged interface
public interface INotifyPropertyChanged
{
event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName);
}
// Define the PropertyChangedEventHandler delegate
public delegate void PropertyChangedEventHandler(object sender,... | magicoder | csharp |
You are tasked with creating a program that generates a formatted timestamp based on a given date and time input. The program should take a date and time in the format "yyyy-MM-dd HH:mm:ss" and convert it to a formatted timestamp in the format "EEEE, MMMM d, yyyy 'at' h:mm a". For example, the input "2023-09-15 14:30:0... | ```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimestampGenerator {
public static String generateFormattedTimestamp(String inputDateTime) {
try {
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat outputFormat... | magicoder | java |
You are tasked with implementing a function that generates a random alphanumeric string of a specified length. The function should take an integer `length` as input and return a string of random alphanumeric characters of the given length.
Your task is to implement the `generateRandomString` function, which takes an i... | Here's a Python solution using the `secrets` module to generate a random alphanumeric string:
```python
import secrets
import string
def generateRandomString(length):
alphabet = string.ascii_letters + string.digits
return ''.join(secrets.choice(alphabet) for _ in range(length))
# Example usage
print(generate... | magicoder | python |
You are tasked with testing a React application using Jest and React Testing Library. The application consists of various components, including `GeneralSettings`, `Breadcrumbs`, and `App`. Additionally, the application uses `MemoryRouter` and an `i18n` instance for internationalization.
Your goal is to write a test ca... | ```javascript
import React from 'react';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { i18n } from 'path-to-i18n'; // Replace with the actual path to i18n instance
import App from 'path-to-App'; // Replace with the actual path to App component
import ... | magicoder | javascript |
You are tasked with implementing a Python class that handles the formatting and writing of multiple sequence alignments to a file. The class, named `AlignmentWriter`, should have a method `write_and_format` that takes in a sequence alignment object, a file format, and an output file name. The method should write the fo... | ```python
from io import StringIO
class AlignmentWriter:
def __init__(self, alignment):
self.alignment = alignment
def write_and_format(self, format, output_file, format_options=None):
outfile = StringIO()
if format == "plain":
self.alignment.writeToFile(outfile, format="pl... | magicoder | python |
You are tasked with creating a program that can encrypt and decrypt messages using a simple substitution cipher. The substitution cipher works by replacing each letter in the message with a different letter from the alphabet. For example, 'a' might be replaced with 'c', 'b' with 'd', and so on. To encrypt a message, ea... | ```python
def substitution_cipher(message, key, mode):
result = ""
key_length = len(key)
for char in message:
if char.isalpha():
shift = key.index(char.lower()) if char.islower() else key.index(char.lower()) - key_length
shifted_char = key[(shift + mode) % key_length]
... | magicoder | python |
You are tasked with creating a script to automate the deployment process for a Dockerized application. The script should handle logging into Docker, setting environment variables, and building the Docker image based on the branch being deployed.
Write a bash script named `deploy.sh` that accomplishes the following tas... | ```bash
#!/usr/bin/env bash
docker login -u $DOCKER_USER -p $DOCKER_PASS
export REPO=pageturner/builder
export TAG=$(if [ "$TRAVIS_BRANCH" == "master" ]; then echo "latest"; else echo $TRAVIS_BRANCH ; fi)
docker build -f Dockerfile -t $REPO:$TRAVIS_COMMIT .
```
The provided bash script `deploy.sh` accomplishes the r... | magicoder | shell |
You are tasked with creating a Python unit test for a function that interacts with AWS S3 using the Chalice framework. The function is responsible for reading and writing objects to an S3 bucket. Additionally, it checks if the objects exist in the bucket. The code snippet provided includes a fixture for mocking AWS cre... | ```python
import os
import pytest
from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist
from tests.builders.file import build_gzip_csv
from moto import mock_s3
@pytest.fixture(scope='function')
def aws_credentials():
"""Mocked AWS Credentials for moto."""
os.environ['AWS_ACCESS_KEY_ID'] = 't... | magicoder | python |
You are tasked with creating a Python class to manage a playlist for a music player. The playlist should support adding songs, removing songs, shuffling the order of songs, and playing the next song in the playlist. Additionally, the playlist should be able to keep track of the current song that is playing.
Create a P... | ```python
import random
class MusicPlaylist:
def __init__(self):
self.playlist = []
self.current_index = 0
def add_song(self, song):
self.playlist.append(song)
def remove_song(self, song):
if song in self.playlist:
self.playlist.remove(song)
def shuffle_pl... | magicoder | python |
You are tasked with implementing a custom bitfield data structure in Rust. A bitfield is a data structure that compactly stores bits, allowing efficient manipulation and access at the bit level. Your task is to implement the `BitField` struct using the `bitfield` crate, which provides a convenient way to define bitfiel... | ```rust
use bitfield::bitfield;
#[bitfield]
struct BitField(u128);
impl BitField {
// Set the bit at the specified position to 1
fn set_bit(&mut self, position: usize) {
self.set_bit(position, true);
}
// Set or clear the bit at the specified position based on the value parameter
fn set_b... | magicoder | rust |
You are tasked with creating a script to automate the migration of SCSS files using the `sass-migrator` tool. The script should traverse through the SCSS files in the `govuk-frontend` package and execute the migration process for each file. The `sass-migrator` command is used to convert SCSS syntax to the newer syntax,... | ```bash
#!/bin/bash
# Function to migrate SCSS files using sass-migrator
migrate_scss_files() {
local package_path="$1"
for file in "$package_path"/**/*.scss; do
sass-migrator division "$file" > /dev/null
done
}
# Main script to migrate GOVUK Frontend SCSS files
main() {
echo "Migrating GOVUK Frontend"
... | magicoder | shell |
You are tasked with implementing a thread-safe logging mechanism for a multi-threaded application. The provided code snippet includes a private static String variable `hostHost` and a ReentrantLock `consoleLogLock` for synchronizing access to the console log. Your goal is to create a class that encapsulates the logging... | ```java
import java.util.concurrent.locks.ReentrantLock;
public class Logger {
private static String hostHost;
private static ReentrantLock consoleLogLock = new ReentrantLock();
public void logMessage(String message) {
consoleLogLock.lock();
try {
System.out.println(message);
... | magicoder | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.