query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Python function that processes a FASTA file containing DNA sequences and generates a BED file with information about the gaps in the sequences. The function should take the input FASTA file path and the output BED file path as arguments. The BED file should contain the genomic coordinates... | ```python
from tempfile import NamedTemporaryFile
import re
def generate_gap_bed(input_fasta: str, output_bed: str) -> None:
with open(input_fasta, 'r') as fasta_file, open(output_bed, 'w') as bed_file:
sequence_name = ""
sequence = ""
for line in fasta_file:
if line.startswith(... | magicoder | python |
You are tasked with creating a script to manage environment variables for the WESTPA (Weighted Ensemble Simulation Toolkit for Parallel Algorithms) package within a Conda environment. The script should set up environment variables when the Conda environment is activated and clean up the environment variables when the C... | ```bash
#!/usr/bin/env bash
# Set up WESTPA environment variables when Conda environment is activated
mkdir -p ${PREFIX}/etc/conda/{activate,deactivate}.d
touch ${PREFIX}/etc/conda/activate.d/env_vars.sh
touch ${PREFIX}/etc/conda/deactivate.d/env_vars.sh
cat << EOC >> ${PREFIX}/etc/conda/activate.d/env_vars.sh
#!/usr... | magicoder | shell |
You are given a 10x10 grid representing a game board. Each cell in the grid can contain one of the following characters: '+', 'K', 'P', '#', 'D', '$', or a color code escape sequence. The color code escape sequences are represented as '\033[Xm', where X is a number representing a color. The grid is printed using the Py... | ```python
def parse_game_board(grid):
counts = {}
for row in grid:
for char in row:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts
```
The `parse_game_board` function iterates through each character in the grid and u... | magicoder | python |
You are working on a query strategy module for a machine learning system. The module uses a settings dictionary to determine the query strategy and its parameters. The code snippet provided is a part of the method that handles the query strategy settings. The method checks the query strategy specified in the settings a... | ```python
def max_sampling():
# Implementation of max_sampling function
pass
def process_query_strategy(settings):
method = settings['query_strategy']
if method in ['max', 'max_sampling']:
return max_sampling, "Maximum inclusion sampling"
if method in ['rand_max', 'rand_max_sampling']:
... | magicoder | python |
You are tasked with implementing a function that processes different types of arguments based on their data type. The function takes in a list of arguments and their corresponding types, and based on the type, it performs specific operations to extract the argument value.
The function processes two types of arguments:... | ```python
def process_arguments(args, types, numb):
import numpy as np
if types[numb-1] == 'int':
addr = args[numb-1].ast.args[0]
argRes = int(np.int32(self.state.mem[addr].long.concrete))
elif types[numb-1] == 'charPointer':
addr = args[numb - 1].to_claripy()
value = se... | magicoder | python |
You are working on a deployment script for a cloud-based application. As part of the deployment process, you need to ensure that a private SSH key is securely copied to the appropriate directory, set with the correct permissions, and added to the SSH agent for authentication. Your task is to write a Bash script that ac... | ```bash
#!/bin/bash
private_key="/var/run/secrets/lagoon/sshkey/ssh-privatekey"
ssh_dir="/home/.ssh"
ssh_key_dest="$ssh_dir/id_rsa"
ssh_agent_socket="/tmp/ssh-agent"
if [ -f "$private_key" ]; then
cp "$private_key" "$ssh_key_dest"
chmod 400 "$ssh_key_dest"
eval $(ssh-agent -a "$ssh_agent_socket")
ssh-add "$ss... | magicoder | shell |
You are tasked with creating a program that manages dependencies for a package manager. The package manager uses a configuration file to define the products and dependencies of various packages. Each product can be a library or an executable, and it can have dependencies on other packages.
Your task is to implement a ... | ```swift
func parseConfigurationFile(configuration: String) -> (products: [String: (type: String, targets: [String])], dependencies: [String: String]) {
var products: [String: (type: String, targets: [String])] = [:]
var dependencies: [String: String] = [:]
// Extract products
if let productsRange = co... | magicoder | swift |
You are given a function that takes an integer `x` as input and returns a boolean value. The function is designed to check if the input integer `x` is a palindrome. A palindrome is a number that remains the same when its digits are reversed. For example, 121 is a palindrome, but 123 is not.
The function uses a while l... | ```java
public boolean isPalindrome(int x) {
if (x < 0) {
return false; // Negative numbers are not palindromes
}
int original = x;
int reversed = 0;
while (x > 0) {
int digit = x % 10;
reversed = reversed * 10 + digit;
x = x / 10;
}
return (ori... | magicoder | java |
You are tasked with implementing a Python function that validates whether a given dictionary matches a specified pattern. The pattern is represented by another dictionary, where the keys represent the expected keys in the input dictionary, and the values represent the expected value types for those keys. Your task is t... | ```python
def validate_pattern(pattern: dict, input_dict: dict) -> bool:
for key, value_type in pattern.items():
if key not in input_dict or not isinstance(input_dict[key], value_type):
return False
return True
``` | magicoder | python |
You are tasked with implementing a comment classification system for a website. The system should be able to classify comments into different categories based on their content. You are provided with a code snippet that includes a method signature for classifying comments and a method signature for retrieving statistics... | ```csharp
public class TrainComment
{
public string Content { get; set; }
// Other relevant properties for classification
}
public class CommentClassifier
{
public string ClassifyComment(TrainComment commentToTrain)
{
// Implement the comment classification logic based on the content and other ... | magicoder | csharp |
You are tasked with implementing a C++ template specialization for a type conversion utility. The given code snippet provides a partial implementation of a type conversion system using C++ templates. Your task is to complete the implementation by adding the necessary code to handle the conversion of specific types.
Yo... | ```cpp
#include <string>
namespace jni {
struct fixed_string {
const char* str;
};
}
struct type;
template <typename Type, typename = void>
struct conv;
#define SIMPLE_TYPE(TYPE, JNI_TYPE, CODE) \
template <> \
struct type<TYPE>... | magicoder | cpp |
You are given a directed graph represented as an adjacency list and a starting node. Your task is to implement a breadth-first search (BFS) algorithm to traverse the graph and print the nodes in the order they were visited.
The graph is represented as a dictionary where the keys are the nodes and the values are lists ... | ```python
def bfs(graph, start):
visited = set()
queue = [start]
visited.add(start)
while queue:
node = queue.pop(0)
print(node, end=' ')
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neig... | magicoder | python |
You are tasked with creating a Python class that manages the installation of web drivers for different browsers. Your task is to implement the `EdgeDriverManager` class, which is a subclass of a base driver manager class. The `EdgeDriverManager` class should handle the installation of the Microsoft Edge web driver.
Th... | ```python
from abc import ABC, abstractmethod
from typing import Optional
import requests
import os
class WebDriver(ABC):
@abstractmethod
def install(self, path: Optional[str] = None) -> str:
pass
class EdgeDriver(WebDriver):
def __init__(self, version: str, os_type: str):
self.version = v... | magicoder | python |
You are working on a security system that manages access levels for different users. The code snippet provided is a part of a function that processes and validates input data related to access levels. The function takes a list `val` as input, where `val[1]` is a string representing a username and `val[2]` is the access... | ```python
from typing import List, Union
ACCESS_LEVELS = {
1: 'admin',
2: 'moderator',
3: 'user'
}
def process_access_level(val: List[Union[str, Union[int, str]]]) -> Union[str, int]:
val[1] = val[1].strip() # Strip leading and trailing whitespaces from username
if isinstance(val[2], str): # Che... | magicoder | python |
You are tasked with creating a program to generate a bar chart representing the sales statistics of different fruits. The program should use JFreeChart, a popular Java library for creating charts and graphs. The chart should be created in 3D and display the sales of various fruits. Additionally, the program should enco... | ```java
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.servlet.ServletUtilities;
import javax.servlet.http.HttpSession;
public class FruitSalesChartGenerator {
publi... | magicoder | java |
You are given a Python code snippet that is part of a sliding window pattern matching algorithm. The algorithm is used to find all the starting indices of an anagram of a given pattern in a given string. The code snippet is responsible for updating the window's start and end positions and maintaining a character freque... | ```python
from typing import List
def find_anagrams(str1: str, pattern: str) -> List[int]:
result_indexes = []
char_frequency = {}
for char in pattern:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
window_start = 0
match... | magicoder | python |
You are tasked with creating a Python script that migrates bookmarks from a legacy system to a new system. The legacy system stores bookmarks in a text file, where each line represents a bookmark in the format "url|title|description". The new system requires the bookmarks to be stored in a JSON file with the following ... | ```python
import json
def migrate_bookmarks(legacy_file_path, new_file_path):
bookmarks = []
with open(legacy_file_path, 'r') as legacy_file:
for line in legacy_file:
parts = line.strip().split('|')
if len(parts) == 3:
url, title, description = parts
... | magicoder | python |
You are tasked with implementing a module resolution algorithm for a hypothetical JavaScript module system. The system uses a specific set of rules to resolve module imports and exports. Given a set of module import and export statements, you need to write a function that resolves the final set of exported modules base... | ```javascript
function resolveModules(importStatements, exportStatements) {
const importedModules = {};
const exportedModules = {};
// Process import statements
importStatements.forEach(statement => {
const match = statement.match(/import\s*(?:\*\s*as\s*(\w+)|{([^}]*)})\s*from\s*'([^']*)'/);
if (match)... | magicoder | javascript |
You are tasked with implementing a Python class that simulates a simple client-server communication system. The provided code snippet includes a part of the client-side code, which attempts to receive a message from the server and handle potential errors. Your task is to complete the implementation of the `Client` clas... | ```python
import socket
class Client:
def __init__(self):
self.server_address = ('localhost', 12345)
self.running = True
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self):
try:
self.socket.connect(self.server_address)
except C... | magicoder | python |
You are working on a program to generate reports for invoices. The code snippet provided is a part of the program that writes data to an Excel file. The program uses the `write` method of the `ws1` object to write data to specific cells in the Excel file. The code snippet contains conditional logic and involves writing... | ```python
def simulate_write(row: int, col: int, invoice_origin: str, post_exectas: int) -> str:
if invoice_origin: # If invoice_origin is not empty
return str(invoice_origin) # Write invoice_origin to cell at row, col + 10
elif post_exectas == 1: # If a invoice is reembolsada
return "0" # W... | magicoder | python |
You are tasked with creating a Python function that handles HTTP requests and responses using the `requests` library and Flask. Your function should take in a Flask `request` object and a dictionary of HTTP methods and their corresponding functions. The function should make an HTTP request using the appropriate method ... | ```python
import requests
from flask import make_response
import json
def handle_http_request(request, method):
try:
body = request.get_json()
except json.decoder.JSONDecodeError:
body = None
base = "http://example.com" # Replace with actual base URL
port = 8080 # Replace with actual... | magicoder | python |
You are tasked with creating a C# class that manages a simple inventory system for a small retail store. The class should allow adding, removing, and updating products in the inventory, as well as retrieving information about specific products.
Your task is to implement the `InventoryManager` class with the following ... | ```csharp
using System;
using System.Collections.Generic;
public class InventoryManager
{
private Dictionary<string, int> inventory;
public InventoryManager()
{
inventory = new Dictionary<string, int>();
}
public void AddProduct(string productName, int quantity)
{
if (inventor... | magicoder | csharp |
You are tasked with implementing a class to represent a geometric shape called `SampleHolder`. The `SampleHolder` class should have a method `load_geometry` that takes in the dimensions of the shape and updates its internal state accordingly. Additionally, you need to write a test case to ensure that loading geometry t... | ```python
class SampleHolder:
def __init__(self, name):
self.name = name
self.sides = []
def load_geometry(self, width, height, sides):
self.sides = [width, height, sides]
import pytest
def test_load_geometry_twice_overwrites(empty_bar):
width = 1
height = 10
nsides = 5
... | magicoder | python |
You are tasked with creating a shell script to manage configuration files. The script should allow users to add or update key-value pairs in a configuration file. The script should handle both adding new key-value pairs and updating existing ones.
Your task is to complete the `add_config_value` function in the given s... | ```bash
function add_config_value() {
local key=${1}
local value=${2}
local config_file=${3:-/etc/postfix/main.cf}
[ "${key}" == "" ] && echo "ERROR: No key set !!" && exit 1
if [ -f "${config_file}" ]; then
if grep -q "^${key}=" "${config_file}"; then
sed -i "s/^${key}=.*/${key}=${value}/" "${con... | magicoder | shell |
You are given a Python code snippet that implements the merge sort algorithm. Your task is to complete the implementation by defining the `merge` function and then use the completed merge sort algorithm to sort a given list of integers.
Your task is to:
1. Complete the `merge` function to merge two subarrays of `arr`.... | ```python
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
L = [0] * n1
R = [0] * n2
for i in range(n1):
L[i] = arr[l + i]
for j in range(n2):
R[j] = arr[m + 1 + j]
i = 0
j = 0
k = l
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]... | magicoder | python |
You are tasked with creating a program that analyzes a given text to check if it complies with a set of distribution conditions. The conditions are as follows:
1. Redistributions of source code must retain the copyright notice, list of conditions, and a specific disclaimer.
2. Redistributions in binary form must reprod... | ```python
def check_redistribution_conditions(text):
conditions = [
"Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.",
"Redistributions in binary form must reproduce the above copyright notice, this list of conditions and t... | magicoder | python |
You are tasked with creating a Django view that displays a list of news articles along with their associated categories. The provided code snippet includes a partial implementation of the `NewsListView` class, which is intended to be a subclass of `ListView` and display a list of news articles with their associated cat... | ```python
from .models import News, Category
from common_utils.generic import PreviewCreateView, PreviewUpdateView, DetailUserProtectedView, ListView
from notes.views import NoteCreateBase
from notifications.models import Event
class NewsListView(ListView):
model = News # Define the model attribute to specify the... | magicoder | python |
You are tasked with creating a Python program that parses a given Debian sources.list file and extracts relevant information from it. The sources.list file contains a list of package repositories and their corresponding configurations. Each line in the file represents a repository configuration in the format:
```
deb ... | ```python
class Repository:
def __init__(self, repo_type, mirror_url, distribution, components):
self.repo_type = repo_type
self.mirror_url = mirror_url
self.distribution = distribution
self.components = components
def parse_sources_list(file_path):
repositories = []
with op... | magicoder | python |
You are working on a computer vision project and need to implement a non-maximum suppression (NMS) algorithm for object detection. The NMS algorithm is used to filter out redundant bounding boxes based on their intersection over union (IoU) with respect to each other. You are given a code snippet that processes the out... | ```python
import torch
from torchvision.ops import nms
def multiclass_nms(bboxes, scores, score_thr, nms_thr, max_per_img):
# Filter out bounding boxes with scores below the threshold
valid_mask = scores > score_thr
bboxes = bboxes[valid_mask]
scores = scores[valid_mask]
if bboxes.numel() == 0:
... | magicoder | python |
You are tasked with creating a Python class that interacts with the LeetCode website to retrieve information about problems. Your class should be able to fetch the problem titles and difficulty levels from the website and store them for further processing.
Your task is to complete the `LeetcodeProblems` class by imple... | ```python
import requests
try:
from html.parser import HTMLParser # For Python 3
except ImportError:
from HTMLParser import HTMLParser # For Python 2
try:
import cPickle as pk
except ImportError:
import pickle as pk
class LeetcodeProblems(object):
def get_problems_info(self):
leetcode_ur... | magicoder | python |
You are tasked with implementing a generic function that takes a tuple and returns a new tuple containing the elements of the original tuple in reverse order. You are provided with a code snippet that defines a generic type `Tuple` and associated constants and traits.
Your task is to implement the function `reverse_tu... | ```rust
/// Define the Tuple type with associated constants and traits
struct Tuple<T, const N: usize>([T; N]);
impl<T: Copy + Clone, const N: usize> Tuple<T, N> {
/// Create a new tuple with elements in reverse order
fn reverse(&self) -> Tuple<T, N> {
let mut reversed_array = self.0;
reversed_... | magicoder | rust |
You are tasked with implementing a function that extracts and counts the occurrences of all unique classNames from a given JavaScript code snippet. The classNames are defined within the `className` attribute of JSX elements. The function should return an object mapping each unique className to its count.
For example, ... | ```javascript
function extractClassNamesCount(code) {
const classNamesRegex = /className={["']([^"']+)["']}/g;
const classNamesMap = {};
let match;
while ((match = classNamesRegex.exec(code)) !== null) {
const individualClassNames = match[1].split(' ');
individualClassNames.forEach((className) => {
... | magicoder | javascript |
You are tasked with implementing a matrix factorization algorithm using Python and NumPy. The algorithm aims to factorize a given matrix `v` into the product of two matrices `w` and `h`, such that `v ≈ w * h`. The provided code snippet demonstrates the iterative update process for the feature matrix `h` and the weights... | ```python
import numpy as np
def matrix_factorization(v, num_features, num_iterations):
num_users, num_items = v.shape
# Initialize feature matrix h and weights matrix w with random values
h = np.random.rand(num_features, num_items)
w = np.random.rand(num_users, num_features)
for i in ran... | magicoder | python |
You are tasked with implementing a card game system that includes a class for watching the arena and tracking the hero's player class. The provided code snippet is a part of the system and sets the `hero` property of the `ArenaWatcher` class to the `playerClass` of a card.
Your task is to complete the implementation o... | ```java
public class ArenaWatcher {
private String hero;
// Constructor and other methods are not shown
public String getHeroPlayerClass() {
return hero;
}
}
``` | magicoder | java |
You are tasked with implementing a custom TensorFlow layer that performs a specific operation on two input tensors. The layer takes two input tensors, `left` and `right`, and a keyword argument `batch_size`. Your task is to create a custom layer that concatenates the input tensors along a new dimension and then reshape... | ```python
import tensorflow as tf
class ConcatenateAndReshapeLayer(tf.keras.layers.Layer):
def __init__(self, batch_size, **kwargs):
super(ConcatenateAndReshapeLayer, self).__init__(**kwargs)
self.batch_size = batch_size
def call(self, inputs):
left, right = inputs
concatenated... | magicoder | python |
You are tasked with implementing a simple caching mechanism using Python. Your task is to create a `Cache` class that stores key-value pairs and supports the `get` and `put` operations. The cache should have a maximum capacity and should evict the least recently used item when the capacity is exceeded.
You should impl... | ```python
from collections import OrderedDict
class Cache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key in self.cache:
value = self.cache.pop(key)
self.cache[key] = value # Move the accessed key to... | magicoder | python |
You are tasked with implementing a function that processes product IDs and generates corresponding file paths based on certain rules. The function should take into account the base IDs and utilize a utility function to fetch additional IDs if necessary. Your task is to complete the implementation of the function `gener... | ```python
from typing import List
import utils # Assuming the utility functions are provided in a separate module
def generate_paths(product: str, base_ids: List[str]) -> List[str]:
paths = []
if not base_ids:
return paths
else:
ids = base_ids
if not ids:
return paths
... | magicoder | python |
You are tasked with implementing a data structure called SmoothNumber that maintains a smooth average of the numbers it receives. The smooth average is calculated by taking the average of the last N numbers received, where N is a parameter provided during the initialization of the SmoothNumber.
You need to implement t... | ```rust
struct SmoothNumber {
n: usize,
numbers: Vec<f64>,
}
impl SmoothNumber {
fn new(n: usize) -> SmoothNumber {
SmoothNumber { n, numbers: Vec::new() }
}
fn put(&mut self, num: f64) {
if self.numbers.len() == self.n {
self.numbers.remove(0);
}
self.n... | magicoder | rust |
You are tasked with implementing a function that performs a specific operation on a table of cells. The table is represented as a two-dimensional array, and each cell contains a value. The function should take a table and a specific cell as input, and then perform a multiplication operation using the value of the cell ... | ```typescript
class Table {
// Assume the implementation of the Table class
}
class Cell {
// Assume the implementation of the Cell class
}
type Value = number;
type Error = string;
type Result<T, E> = { success: true, value: T } | { success: false, error: E };
class TableProcessor {
private readonly withCell... | magicoder | typescript |
You are tasked with implementing a Python function that converts a given JSON object into a backward-compatible format. The function should handle nested dictionaries and perform specific transformations on the keys. The transformation rules are as follows:
1. If a key's value is a dictionary, the key should be convert... | ```python
def _backwardCompat(result_json):
bc_json = dict()
for k, v in result_json.items():
if isinstance(v, dict):
bc_json[k[0].lower() + k[1:]] = _backwardCompat(v)
elif k == 'Token':
bc_json['sessionToken'] = v
else:
bc_json[k[0].lower() + k[1:]] ... | magicoder | python |
You are tasked with implementing a sampling algorithm for a Bayesian Variational Autoencoder (B-VAE). The B-VAE model requires a proper mean code representation, but due to the unavailability of factor-pairs during lock-sampling, a new approach is needed. Additionally, you need to build a "sampled list" to keep track o... | ```python
def sample_b_vae(input_data):
sampled_list = [] # Initialize the sampled list
# Implement proper mean code representation for B-VAE
encoded_data = encode(input_data)
mean_code = calculate_mean_code(encoded_data)
# Perform lock-sampling with handling of unavailability of factor-pairs
... | magicoder | python |
You are given a function `binary_operation` that takes a string `binary_string` as input. The function performs a series of operations on the input string and returns the result.
The function `binary_operation` processes the input string as follows:
1. It iterates through each character in the input string and counts ... | ```python
def binary_operation(binary_string: str) -> int:
bzero = 0
bone = 0
new_line = ""
for val in binary_string:
if val == "0":
bzero += 1
else:
bone += 1
if bone > bzero:
new_line += "1"
else:
new_line += "0"
bin... | magicoder | python |
You are tasked with creating a program that analyzes a given text to identify and count the occurrences of specific keywords. The program should read a text file and count the occurrences of each keyword in the file. Keywords are defined as specific words or phrases that are of interest for analysis.
Write a function ... | ```python
from typing import List, Dict
import re
def count_keyword_occurrences(file_path: str, keywords: List[str]) -> Dict[str, int]:
keyword_counts = {keyword: 0 for keyword in keywords}
with open(file_path, 'r') as file:
text = file.read().upper() # Convert the text to uppercase for case-insensiti... | magicoder | python |
You are tasked with creating a Python program to process a folder of images using an object detection model. The program should utilize the YOLO (You Only Look Once) object detection algorithm to detect objects within the images and create a new folder containing the processed images.
Your program should take the foll... | ```python
import os
import shutil
import glob
import argparse
class YoloObjectDetector:
def __init__(self, model_size):
self.model_size = model_size
def main():
parser = argparse.ArgumentParser(description='Object detection on images')
parser.add_argument('input', help='Input image folder path')
... | magicoder | python |
You are given a Python code snippet that appears to be part of a machine learning algorithm. The code snippet includes a function `pla` which seems to implement the Perceptron Learning Algorithm (PLA) for binary classification. The function takes input data `x`, corresponding labels `y`, and an optional parameter `epoc... | To solve this problem, you can create a programming problem that requires the implementation of the Perceptron Learning Algorithm (PLA) to classify linearly separable data. The problem can provide a dataset of points in 2D space, along with their corresponding labels, and ask the students to implement the PLA algorithm... | magicoder | python |
You are tasked with implementing a function to detect whether a given string represents a valid mathematical operation in a specific format. The format for a valid mathematical operation is defined as follows:
- The operation is enclosed within parentheses.
- The operation consists of an operator followed by operands, ... | ```python
def isList(input_string):
stack = []
for char in input_string:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return not stack
def isMath(input_string):
if input_string[0] != '(' o... | magicoder | python |
You are tasked with implementing a simplified version of a SlothComputation class in Python. The SlothComputation class is responsible for performing a computation loop based on the Sloth algorithm. The provided code snippet initializes the SlothComputation object and starts the computation loop. Your task is to create... | ```python
import time
class SlothComputation:
def __init__(self, dealer_connect, pub_addr, pub_type, timeout, identity, sloth_bits, sloth_iterations):
self.dealer_connect = dealer_connect
self.pub_addr = pub_addr
self.pub_type = pub_type
self.timeout = timeout
self.identity ... | magicoder | python |
You are tasked with creating a Python decorator that logs the execution time of a function. Your decorator should be able to handle both synchronous and asynchronous functions. You should also write a unit test to ensure that the decorator works as expected.
Your decorator should log the execution time of the function... | ```python
import time
import asyncio
import pytest
def execution_time_logger(func):
async def wrapper(*args, **kwargs):
start_time = time.time()
result = await func(*args, **kwargs) if asyncio.iscoroutinefunction(func) else func(*args, **kwargs)
end_time = time.time()
execution_time... | magicoder | python |
You are given a string `s` consisting of uppercase English letters, where each letter represents a digit in base-26 numbering system. The mapping is such that 'A' represents 1, 'B' represents 2, and so on up to 'Z' representing 26. Your task is to write a function to convert the given string `s` into its corresponding ... | ```cpp
#include <string>
using namespace std;
int convertBase26ToDecimal(const string& s) {
int result = 0, base = 1;
char c = char('A' - 1);
for (int i = s.size() - 1; i >= 0; --i) {
result += (s[i] - c) * base;
base *= 26;
}
return result;
}
```
The `convertBase26ToDecimal` funct... | magicoder | cpp |
You are tasked with implementing a class factory in Python that dynamically creates a new class based on an existing class. The class factory should take the existing class as a parameter and return a new class with additional functionality.
Your task is to create a Python function that takes the existing class and a ... | ```python
def classfactory(base_class, url):
class ExPerson(base_class):
def __init__(self, name):
super().__init__(name)
self.url = url
return ExPerson
``` | magicoder | python |
You are tasked with creating a Python program to automate the process of scraping and processing lecture links from a specific webpage. The program should use the Selenium library to interact with a web browser and extract the lecture links from the page. Additionally, the program should print the processing status for... | ```python
from selenium import webdriver
# Replace 'user' and 'password' with actual credentials
user = 'your_email@example.com'
password = 'your_password'
# Set up the web browser
browser = webdriver.Chrome()
browser.get('https://www.example.com') # Replace with the actual URL
# Click on the "Log In" link
browser.... | magicoder | python |
You are tasked with implementing a key-value store class in TypeScript. The class should provide methods for inserting, updating, selecting, checking existence, and deleting key-value pairs, as well as bulk operations for inserting, updating, and inserting or updating multiple key-value pairs.
Your task is to implemen... | ```typescript
class KeyValueStore {
private store: Record<string, unknown>;
constructor() {
this.store = {};
}
insertOrUpdate(key: string, value: unknown): void {
this.store[key] = value;
}
select(key: string): unknown | undefined {
return this.store[key];
}
exists(key: string): boolean ... | magicoder | typescript |
You are tasked with creating a Discord bot command that takes a code snippet as input, creates a new sourcebin, and sends the sourcebin URL back to the user. You will need to use the discord.js library to interact with the Discord API and the sourcebin library to create the sourcebin.
Your task is to complete the `cre... | ```javascript
function createSourcebinCommand(message) {
// Extract the code snippet from the user's message
const codeSnippet = message.content.split('```')[1];
// Create a new sourcebin using the sourcebin library
const { url } = await sourcebin.create([
{
name: 'code.js',
content: codeSnippe... | magicoder | javascript |
You are tasked with implementing a function to compare the values of pointers and return a specific result based on the comparison. The function should take in multiple pointers and compare their values with corresponding target pointers. If all comparisons are successful, the function should set two offset variables a... | ```cpp
bool comparePointers(int* rank8_ptr, int* rank8_target_ptr, int* rank1_ptr, int* rank1_target_ptr, int* rank2_ptr, int* rank2_target_ptr, int& offset_first, int& offset_last) {
if (*rank8_ptr == *rank8_target_ptr && *rank1_ptr == *rank1_target_ptr && *rank2_ptr == *rank2_target_ptr) {
offset_last = o... | magicoder | cpp |
You are given a code snippet that involves the manipulation of mathematical expressions using variables and operations. Your task is to create a Python function that can evaluate a given mathematical expression represented as a nested structure of operations and variables.
You need to implement a function `evaluate_ex... | ```python
import numpy as np
def evaluate_expression(expression, variables):
def Dot(a, b):
return np.dot(a, b)
def VSF(func, val):
if func == 'sin':
return np.sin(val)
# Add support for other trigonometric functions if needed
def Add(a, b):
return np.add(a, b)... | magicoder | python |
You are tasked with implementing a class that manages friend presence and profile information in a social networking application. The class provides several methods for interacting with friend data. Your task is to create a method that retrieves the profile image of a friend and to implement a class that uses this meth... | ```csharp
using System;
public class FriendManager
{
// Method to display the profile image of a friend
public void DisplayProfileImage(string friendId)
{
// Assume friendId is used to retrieve friend data
// Example: FriendData friend = GetFriendDataById(friendId);
// Get the prof... | magicoder | csharp |
You are tasked with implementing a custom list adapter in Android that extends the `BaseAdapter` class. The provided code snippet serves as a starting point for the custom adapter. Your task is to complete the implementation of the `ListAdapter` class by adding necessary methods and functionality to support the display... | ```java
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;
public abstract class ListAdapter<T> extends BaseAdapter {
private List<T> mData;
public ListAdapter(List<T> data) {
mData = data;
}
@Overrid... | magicoder | java |
You are tasked with creating a program that analyzes a given text file to count the occurrences of each unique word. For the purpose of this problem, a word is defined as a sequence of alphanumeric characters, excluding any punctuation or whitespace. The program should be case-insensitive, meaning that "Hello" and "hel... | ```python
from typing import Dict
import re
def count_word_occurrences(file_path: str) -> Dict[str, int]:
stop_words = {"the", "and", "is", "it", "a", "an", "in", "on", "at", "to", "of", "for", "with", "as"}
word_counts = {}
with open(file_path, 'r') as file:
text = file.read().lower()
wor... | magicoder | python |
You are tasked with implementing a file transfer manager that handles the reception of files and error handling. The file transfer manager exposes two callback functions: `fileReceived` and `errorHappened`. Your goal is to create a class that utilizes these callbacks to manage the received files and errors.
You need t... | ```java
// FileTransferManager class to handle file reception and error handling
public class FileTransferManager {
private FileReceivedCallback fileReceivedCallback;
private ErrorCallback errorCallback;
// Constructor to set the callbacks
public FileTransferManager(FileReceivedCallback fileReceivedCal... | magicoder | java |
You are tasked with creating a Python class that simulates a simple network switch. The switch should be able to handle incoming and outgoing network traffic between multiple hosts. Your task is to implement the `Switch` class with the following functionalities:
1. Initialize the switch with a given name and default n... | ```python
class Switch:
def __init__(self, switch_name, network_name, grpc_port=BMV_DEFAULT_GRPC_PORT):
self.switch_name = switch_name
self.network_name = network_name
self.grpc_port = grpc_port
self.peer_ports = {}
self.hosts = {}
def add_host(self, host_name, peer_port... | magicoder | python |
You are tasked with implementing a resource management system for a service. The system needs to update the values of various resources based on the service's availability and buffer constraints. You are given a code snippet that demonstrates the usage of a function `update_resource_values` to update the resource value... | ```rust
#[derive(Clone)]
struct ServiceResourceUpdate {
availability: Availability,
buffer_after: i32,
buffer_before: i32,
}
struct Resource {
// Define the fields of the Resource struct
}
impl Resource {
fn update_resource_values(&mut self, update: &ServiceResourceUpdate) {
// Implement t... | magicoder | rust |
You are working on a project that involves importing various architectures from a module called `architectures`. The `architectures` module contains different classes and functions for building neural network architectures. Your task is to create a program that dynamically imports these architectures based on user inpu... | ```python
def main():
try:
architecture_name = input("Enter the name of the architecture to import: ")
architecture_module = __import__('architectures', fromlist=[architecture_name])
architecture_class = getattr(architecture_module, architecture_name)
architecture_instance = architec... | magicoder | python |
You are tasked with implementing a class hierarchy for handling vertex array objects in a graphics rendering engine. The code snippet provided is a part of a factory method that returns a specific implementation of a vertex array based on the chosen renderer.
The `Renderer::Implementation` enum class represents differ... | ```cpp
// VertexArray.hpp
#ifndef VERTEXARRAY_HPP
#define VERTEXARRAY_HPP
#include <iostream>
#include <stdexcept>
// Abstract base class for vertex arrays
class VertexArray {
public:
virtual ~VertexArray() = default;
virtual void bind() const = 0;
virtual void unbind() const = 0;
};
// Concrete class fo... | magicoder | cpp |
You are tasked with creating a custom resource model for managing attachments in a Magento-based application. The resource model should handle operations such as saving and loading attachment objects. Your task is to implement the `_afterSave` and `_afterLoad` methods within the custom resource model class.
The `_afte... | ```php
/**
* Custom resource model for managing attachments
*/
class LCB_Attachments_Model_Resource_Attachment extends Mage_Core_Model_Resource_Db_Abstract
{
/**
* Perform operations after object save
*
* @param Mage_Core_Model_Abstract $object
* @return LCB_Attachments_Model_Resource_Attachme... | magicoder | php |
You are tasked with implementing a Python function that processes flow statistics and generates a formatted report. The function should take a list of flow statistics objects as input and produce a well-structured report displaying the flow name, received frames, and received bytes in a tabular format.
The flow statis... | ```python
from typing import List
class FlowStats:
def __init__(self, name: str, frames_rx: int, bytes_rx: int):
self.name = name
self.frames_rx = frames_rx
self.bytes_rx = bytes_rx
def generate_flow_report(flow_stats: List[FlowStats]) -> None:
if flow_stats:
row_format = "{:>1... | magicoder | python |
You are given a code snippet that appears to be part of a function that manipulates an array called `HexAlphabetReverse`. The code snippet is incomplete and contains some missing parts. Your task is to complete the function based on the given code snippet and the following requirements:
1. The `HexAlphabet` array cont... | ```csharp
public void PopulateHexAlphabetReverse(char[] HexAlphabet, int[] HexAlphabetReverse)
{
const int ErrorPosition = -1;
for (int i = 0; i < HexAlphabetReverse.Length; i++)
{
HexAlphabetReverse[i] = ErrorPosition;
}
for (int i = 0; i < HexAlphabet.Length; ++i)
{
HexAlphab... | magicoder | csharp |
You are tasked with creating a Python class that manages the execution of various tasks based on a set of options. The class should construct a string based on the provided options and then perform the specified task.
You are given the following code snippet as a starting point:
```python
+ option["variableDe... | ```python
class Maneger:
def __init__(self, option):
self.option = option
def construct_string(self):
constructed_string = f"{self.option['variableDependent']}_{self.option['release4test']}_{self.option['modelAlgorithm']}_{self.option['date']}"
return constructed_string
def do(self... | magicoder | python |
You are tasked with implementing a resource management system for a data source in a multi-threaded environment. The data source provides access to various table functions, and it is essential to ensure that the resources are properly released after their usage to prevent memory leaks and resource exhaustion.
Your tas... | ```csharp
public class DataSourceManager
{
private DataSource dataSource;
public DataSourceManager(DataSource dataSource)
{
this.dataSource = dataSource;
}
public async Task<TableResult> ExecuteTableFunctionAsync(string functionName, Parameter parameter)
{
try
{
... | magicoder | csharp |
You are working as a DevOps engineer for a company that is developing a microservices-based application. As part of your responsibilities, you need to manage and monitor various services running on Kubernetes clusters. One of the tasks involves obtaining the URLs for different services and their corresponding ports. Yo... | ```python
import re
def parse_service_urls(output):
service_urls = {}
# Extracting Virtool Server URL
server_port = re.search(r'Virtool Server: http://localhost:(\d+)', output)
if server_port:
service_urls["Virtool Server"] = f"http://localhost:{server_port.group(1)}"
# Extracting... | magicoder | python |
You are tasked with implementing a function to parse and extract data from a file containing sprite information. The file contains data in the following format:
```
Sprite <name>
{
texture = <texture_name>
rect = <x>,<y>,<width>,<height>
<other_data>
}
```
Where:
- `<name>` is the name of the sprite.
- `<textur... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[50];
char texture[50];
int x, y, width, height;
} SpriteData;
SpriteData parseSprite(FILE *fp, const char *name) {
SpriteData sprite;
char line[100];
char texture[50];
int x, y, width, height;
/... | magicoder | c |
You are tasked with implementing a custom neural network architecture for a specific application. The network will be used to classify images of handwritten digits from 0 to 9. To achieve this, you will need to create a multi-layer perceptron (MLP) using the `pylation` library, which provides tools for building and tra... | ```python
from pylation.mlp import MLP
from pylation.relational import Relational
from pylation.optimizers import Adam
from pylation.losses import CategoricalCrossEntropy
from pylation.datasets import MNIST
# Define the MLP architecture
mlp = MLP()
mlp.add_layer(784, activation=None) # Input layer
mlp.add_layer(256, ... | magicoder | python |
You are tasked with implementing a function that calculates the total number of unique paths to reach the bottom-right corner of a grid from the top-left corner. You can only move either down or to the right at any point in time. The grid is represented as a 2D array where 1 indicates an obstacle and 0 indicates an emp... | ```java
public int uniquePaths(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
if (obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) {
return 0; // If the start or end point is an obstacle, no path is possible
}
int[][] dp = new int[m][n];... | magicoder | java |
You are tasked with implementing a simple game simulation involving bots, humans, and agents. The game involves creating instances of these entities and equipping them with different types of guns. Your task is to create classes for `Bot`, `Human`, and `Agent`, as well as classes for different types of guns. Each entit... | ```python
class Bot:
def __init__(self, name, gun_class):
self.name = name
self.gun_class = gun_class
def get_info(self):
return f"{self.name} - Equipped with {self.gun_class().get_type()}"
class Human:
def __init__(self, name, gun_class):
self.name = name
self.gun_... | magicoder | python |
You are tasked with implementing a progress tracking system for a test framework. The system should monitor the collection of test items and display the progress in a visually appealing manner. The code snippet provided is a part of this progress tracking system, which uses the `pytest` library for Python.
Your task i... | ```python
import pytest
from rich.progress import Progress
class TestProgressTracker:
def __init__(self):
self.collect_progress = Progress()
self.collect_task = self.collect_progress.add_task("[cyan]Collecting", total=100)
self.items_per_file = {}
self.status_per_item = {}
... | magicoder | python |
You are tasked with implementing a function to calculate the SHA-512 hash of a given input string using the OpenSSL library in C. The SHA-512 algorithm produces a 64-byte (512-bit) hash value. The code snippet provided declares an array `hash` of type `unsigned char` with a size of `SHA512_DIGEST_LENGTH`, which is a co... | ```c
#include <openssl/sha.h>
#include <stdio.h>
#include <string.h>
char* calculateSHA512(const char* input) {
unsigned char hash[SHA512_DIGEST_LENGTH];
SHA512_CTX sha512;
SHA512_Init(&sha512);
SHA512_Update(&sha512, input, strlen(input));
SHA512_Final(hash, &sha512);
char* hexHash = malloc(S... | magicoder | c |
You are tasked with implementing a custom exception class in Python for handling signal events. Signals are a form of inter-process communication used in Unix-like operating systems to notify a process that a particular event has occurred. Your goal is to create a custom exception class called `SignalException` that wi... | ```python
class SignalException(Exception):
"""Custom exception class for handling signal events in a Python application."""
pass
```
The provided solution implements the `SignalException` class as a subclass of the built-in `Exception` class. The docstring for the `SignalException` class provides a clear and c... | magicoder | python |
You are tasked with creating a Django model and admin interface for managing schedules of courses. The Schedule model represents the schedule for a particular course group on a specific day of the week, including the start and end times. The admin interface should allow easy management of these schedules, including the... | ```python
# models.py
from django.db import models
class CourseGroup(models.Model):
# Define the CourseGroup model fields
class Schedule(models.Model):
WEEK_DAYS = (
('mon', 'Monday'),
('tue', 'Tuesday'),
('wed', 'Wednesday'),
('thu', 'Thursday'),
('fri', 'Friday'),
... | magicoder | python |
You are given a snippet of code that is part of a mobile application's view controller. The code is responsible for setting up buttons and an image view based on the properties of a model object. Your task is to implement a function that calculates the height of an image view based on the width and aspect ratio of the ... | ```swift
func calculateImageViewHeight(width: Float, height: String, isBigImage: Bool, screenWidth: CGFloat) -> String {
var imageHeight: CGFloat = 0
if width != 0 {
if let imageWidth = Float(width), let modelHeight = Float(height) {
imageHeight = CGFloat(modelHeight / imageWidth) * (sc... | magicoder | swift |
You are tasked with implementing a Python function that performs softmax activation on a given set of predictions. Softmax activation is a common operation used in machine learning to convert raw predictions into probabilities. The softmax function takes a vector of arbitrary real-valued scores and normalizes it into a... | ```python
import torch
import torch.nn.functional as F
def softmax_activation(predictions):
if isinstance(predictions, list):
predictions = torch.tensor(predictions)
return F.softmax(predictions, dim=0).tolist()
```
The `softmax_activation` function first checks if the input predictions are in the form... | magicoder | python |
You are given a set of soft constraints represented as function calls in the following format:
```
soft(weight, condition)
```
Where `weight` is a positive integer representing the importance of the constraint, and `condition` is a boolean expression involving absolute differences between variables. The goal is to dete... | ```python
from typing import List, Tuple
import re
def maxWeightWithoutViolation(constraints: List[Tuple[int, str]]) -> int:
max_weight = 0
for weight, condition in constraints:
if all(eval(re.sub(r'x(\d+)', r'\1', condition))):
max_weight = max(max_weight, weight)
return max_weight
# ... | magicoder | python |
You are tasked with creating a Python program that simulates a simple task management system. The program should allow users to add, remove, and list tasks, as well as mark tasks as completed. The tasks should be stored in a list and displayed with their corresponding status (completed or pending).
Your task is to imp... | ```python
class TaskManager:
def __init__(self):
self.tasks = []
def add_task(self, task_name):
self.tasks.append({"name": task_name, "completed": False})
def remove_task(self, task_name):
for task in self.tasks:
if task["name"] == task_name:
self.tasks.... | magicoder | python |
You are tasked with implementing a custom iterator in Rust that generates Fibonacci numbers. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. Your custom iterator should produce an infinite sequence of Fibonacci numbers.
Your task i... | ```rust
use std::ops::{Generator, GeneratorState};
pub struct FibonacciGen<G: Generator<Yield = u64, Return = ()>>(pub G);
impl<G> Iterator for FibonacciGen<G>
where
G: Generator<Yield = u64, Return = ()>
{
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
match unsafe { self.0.resume()... | magicoder | rust |
You are tasked with implementing a greedy algorithm for optimizing a target function in the context of a specific problem domain. The algorithm operates on a fine vector and requires an order parameter to determine its behavior. Your task is to design and implement the greedy algorithm to optimize the target function b... | ```python
def greedy_algorithm_2(self):
# Sort the fine vector based on the target function's value in descending order
sorted_vector = sorted(self.U, key=self.tf_res, reverse=True)
# Initialize an empty list to store the selected elements
selected_elements = []
# Iterate through the sorte... | magicoder | python |
You are tasked with implementing a function that takes a string representing an HTML table and returns the table's data in a structured format. The input string will be in the following format:
```html
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1-1</td>
<td>Data 1-2</td>... | ```python
from bs4 import BeautifulSoup
def parse_html_table(table_str):
soup = BeautifulSoup(table_str, 'html.parser')
table = soup.find('table')
headers = [th.get_text() for th in table.find_all('th')]
data = []
for row in table.find_all('tr')[1:]:
row_data = {}
cells = row.find_a... | magicoder | python |
You are tasked with implementing a function to parse and extract information from a C header file. The header file contains a set of convenience functions for logging messages in the context of OpenCL programming. Your goal is to extract the function names, parameters, and their types from the given code snippet.
You ... | The solution involves using regular expressions to parse the C header file and extract the required information. Here's a Python program that accomplishes this task:
```python
import re
def extract_function_info(header_code):
function_info = {}
function_pattern = r'extern void CL_API_ENTRY (\w+)\((.*?)\);'
... | magicoder | python |
You are tasked with implementing a Python class that manages configuration widgets and their associated units. The class should allow for the addition of configuration widgets and their units, as well as the retrieval of these widgets and units. Additionally, the class should provide a method to display the configurati... | ```python
class ConfigManager:
def __init__(self):
self.unitsWdg = {}
self.cfgWdg = []
self.cfgUnitsWdg = None
def add_widget(self, widget_name, units):
self.unitsWdg[widget_name] = units
def get_widget_units(self, widget_name):
return self.unitsWdg.get(widget_name,... | magicoder | python |
You are tasked with implementing a migration tracking system for a database. The system should keep track of the current version of the database schema and allow for the execution of migration scripts to update the schema. Your task is to write a function that takes a list of migration scripts and applies them to the d... | ```rust
use rusqlite::{Connection, Error};
enum SchemaVersion {
Inside(std::num::NonZeroUsize),
Outside,
}
fn apply_migrations(conn: &Connection, current_version: SchemaVersion, migration_scripts: Vec<&str>) -> Result<(), Error> {
match current_version {
SchemaVersion::Inside(version) => {
... | magicoder | rust |
You are tasked with implementing a function to calculate the power of a given base to a given exponent using an iterative approach. The function should take two integer parameters, `a` and `b`, representing the base and the exponent, respectively. You need to complete the implementation of the `power` function, which s... | ```c
int power(int a, int b)
{
int res = 1;
int base = a;
int exponent = b;
if (exponent < 0) {
base = 1 / base;
exponent = -exponent;
}
while (exponent > 0) {
if (exponent % 2 == 1) {
res *= base;
}
base *= base;
exponent /= 2;
}... | magicoder | c |
You are tasked with creating a Laravel Eloquent model for a medical application that manages blog posts related to different diseases. The model should have relationships with the Menu and App models, and it should include custom query scopes to filter posts by disease and title.
Your task is to implement the Eloquent... | ```php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BlogPost extends Model
{
public function menu()
{
return $this->belongsTo('App\Menu');
}
public function app()
{
return $this->belongsTo('App\App');
}
public function scopeFilterByDisease($query, $... | magicoder | php |
You are tasked with implementing a custom iterable class in Python. The class should allow iteration over its internal data and return both the value and the index of each element when iterated over. Additionally, the class should raise an IndexError if an attempt is made to access an index beyond the length of the int... | ```python
class CustomIterable:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
if index >= len(self): raise IndexError
return self.data[index], index
x = CustomIterable([10, 20, 30, 40, 50])
for v, i in x:
... | magicoder | python |
You are tasked with creating a Python program that simulates a simple message queue system using the Pika library. The program should implement a basic message producer and consumer, where the producer sends messages to a queue, and the consumer retrieves and processes these messages.
Your task is to complete the impl... | ```python
import pika
class MessageProducer:
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
self.channel = self.connection.channel()
self.channel.queue_declare(queue='message_queue')
def send_message(self, message):
self.ch... | magicoder | python |
You are tasked with creating a function that processes a given HTML code snippet to extract and manipulate certain attributes. The HTML code snippet contains an input element and a span element with conditional rendering based on a variable. Your task is to write a function that takes the HTML code as input and returns... | ```python
import re
def process_html_code(html_code: str) -> (str, str):
flag_code = re.search(r'name="flag_code" value="([^"]+)"', html_code).group(1)
modified_html = html_code.replace('flag-icon', 'flag-icon-filled') if flag_code else re.sub(r'<span class="flag-icon"></span>', '', html_code)
return flag_... | magicoder | python |
You are tasked with implementing a function that processes a text corpus obtained from a file. The function should perform various text processing operations and return specific information based on the processed text.
You are provided with a Python function `test_corpus(get_text_from_file)` that takes a single argum... | ```python
import re
from collections import defaultdict
def test_corpus(get_text_from_file):
# Read text content from the file
text = get_text_from_file("path_to_file.txt")
# Convert text to lowercase
text = text.lower()
# Tokenize the text into individual words
words = re.findall(r'\b\w+\b',... | magicoder | python |
You are tasked with creating a script that sets environment variables for a specific project. The script should set the `LD_LIBRARY_PATH`, `LD_INCLUDE_PATH`, `C_INCLUDE_PATH`, `CPLUS_INCLUDE_PATH`, `INCLUDE_PATH`, and `PATH` variables to include the project's `lib` and `include` directories. Additionally, the script sh... | ```bash
#!/bin/bash
# Set LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$(pwd)/lib:${LD_LIBRARY_PATH}
# Set LD_INCLUDE_PATH
export LD_INCLUDE_PATH=$(pwd)/lib:${LD_INCLUDE_PATH}
# Set C_INCLUDE_PATH
export C_INCLUDE_PATH=$(pwd)/include:${C_INCLUDE_PATH}
# Set CPLUS_INCLUDE_PATH
export CPLUS_INCLUDE_PATH=$(pwd)/include:${CP... | magicoder | shell |
You are given a Python code snippet that includes a list `l1` containing integer elements. The code snippet also includes a function `merge_sort` that sorts the list using the merge sort algorithm. The main function calls `merge_sort` to sort `l1` and then compares the sorted list with the result obtained from the buil... | ```python
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = j = k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right... | magicoder | python |
You are tasked with implementing a class that manages the timeout settings for a function. The class should have a property called `timeout` that allows getting and setting the timeout value for the function it manages. The timeout value should be stored in a private attribute `_function["timeout"]`. You need to implem... | ```python
class TimeoutManager:
def __init__(self):
self._function = {"timeout": 0}
@property
def timeout(self):
# Getter method to return the timeout value
return self._function["timeout"]
@timeout.setter
def timeout(self, value):
# Setter method to set the timeout... | magicoder | python |
You are tasked with simulating a thermostat control system for a heating device. The system consists of a heater, a thermostat, and a temperature sensor. The heater's power can be adjusted to regulate the temperature, and the temperature sensor provides the current temperature. The goal is to maintain the temperature c... | ```python
def adjustHeaterPower(currentTemp, thermostat, dy_dx, delta, heater):
if ((currentTemp + 15*dy_dx) > thermostat): # if projected to overshoot thermostat in the next 15 seconds
if delta < -2:
heater.setPower(heater.getPower() - 1) # decrease power if temperature is more than 2 degrees... | magicoder | python |
You are tasked with designing a generic interface for managing virtual folders in a file system. The interface includes properties and constraints for various types of virtual folder results. Your goal is to implement a class that adheres to this interface and provides functionality for managing virtual folders.
The i... | ```csharp
public class VirtualFolderManager<
TVirtualFolderOwnerResult,
TVirtualFolderTimeResult,
TVirtualFolderPermResult,
TVirtualFolderPermAclResult,
TVirtualFolderVolumeStatusResult> : IVirtualFolderManager<
TVirtualFolderOwnerResult,
TVirtualFolderTimeResult,
TVirtualFolderPermResul... | magicoder | csharp |
You are tasked with implementing a simple task execution system using Python's `asyncio` library. The system will involve defining and executing asynchronous tasks using the `@task` decorator provided by the `api` module. The tasks will perform basic operations and interact with a parent task ID.
Your task is to creat... | ```python
from api import task
@task(async=True)
def multiply(arg1, arg2):
print('Passing parent id to end point %s' % multiply.state.parent_id)
return arg1 * arg2
``` | magicoder | python |
You are tasked with implementing a function that takes in a string representing a JSX code snippet and checks if the opening and closing tags for each JSX element are properly balanced. In JSX, elements are enclosed in angle brackets, and each opening tag must have a corresponding closing tag. The opening and closing t... | ```javascript
function checkJSXBalance(jsxCode) {
const stack = [];
const regex = /<(\w+)>|<\/(\w+)>/g;
let match;
while ((match = regex.exec(jsxCode)) !== null) {
if (match[1]) {
stack.push(match[1]);
} else if (match[2]) {
if (stack.length === 0 || stack.pop() !== match[2]) {
retu... | magicoder | javascript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.