query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are working on a data processing script that involves interacting with various external resources. Your task is to create a Python function that performs the following tasks:
1. Read a CSV file named "retracted_exps.csv" containing generic information.
2. Extract specific data from the CSV file and process it.
3. ... | ```python
import subprocess
import requests
import json
import os
import re
import argparse
import logging
import csv
import shutil
def process_data(url):
# Read the "retracted_exps.csv" file and extract relevant information
with open('retracted_exps.csv', 'r') as file:
csv_reader = csv.reader(file)
... | magicoder | python |
You are tasked with creating a Python script to automate the process of loading and unloading a kernel module on a Raspberry Pi. The script should be able to handle the loading and unloading of the module with the given parameters.
Your script should take the following actions:
1. Load the kernel module `rpi_lightpen.... | ```python
import subprocess
def load_kernel_module(module, parameters):
subprocess.run(['sudo', 'insmod', f'./{module}.ko', *parameters.split()])
def unload_kernel_module(module):
subprocess.run(['sudo', 'rmmod', module])
# Load the kernel module rpi_lightpen.ko with gpios=17,22
load_kernel_module('rpi_light... | magicoder | python |
You are tasked with creating a simple command-line interface (CLI) tool to automate the process of committing changes to a Git repository. Your program should mimic the behavior of the given code snippet, interacting with the user to add and commit files to the repository.
Your program should perform the following ste... | ```python
import subprocess
def main():
print("Starting the Git commit process...")
try:
# Check the status of the Git repository
subprocess.run(["git", "status"], check=True)
# Add all modified files to the staging area
subprocess.run(["git", "add", "."], check=Tr... | magicoder | python |
You are working on developing a deep learning model for audio processing. As part of this project, you need to implement a variance predictor module using the given parameters and specifications.
The variance predictor module is a crucial component in speech synthesis systems, as it predicts the variance of the acoust... | ```python
import tensorflow as tf
from tensorflow.keras.layers import Conv1D, Dropout
def build_variance_predictor(fft_conv1d_kernel_size, encoder_dropout, decoder_dropout, variance_predictor_filter_size):
input_shape = (input_length, input_dim) # Define input shape based on your specific input dimensions
# ... | magicoder | python |
You are tasked with implementing a custom namespace management system in C++. The system should allow for the creation, retrieval, and deletion of namespaces, as well as the addition and retrieval of variables within these namespaces. Each namespace can also have sub-namespaces, forming a hierarchical structure.
Your ... | ```cpp
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
class Namespace {
public:
std::string name;
std::unordered_map<std::string, int> variables;
std::vector<Namespace*> children;
Namespace(const std::string& name) : name(name) {}
};
class NamespaceManager {
private:... | magicoder | cpp |
You are tasked with creating a PHP class that represents a document in an Elasticsearch index. Your class should utilize the ONGR ElasticsearchBundle annotations and implement the DocumentInterface. The annotations will define the mapping of the document properties to the Elasticsearch index.
Your task is to create a ... | ```php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ONGR\DemoBundle\Document;
use ONGR\ElasticsearchBundle\Annotation as ES;
use ONGR\ElasticsearchBundle\Document\DocumentInterface;
/**
* @ES\Document(type="product")... | magicoder | php |
You are tasked with creating a script to automate the setup of a Python virtual environment and install necessary packages for a project. The script should activate the virtual environment, install the required packages from a `requirements.txt` file, and then install a package named `dace` in editable mode. The script... | ```python
def setup_environment(DIR):
commands = [
f"source {DIR}/venv/bin/activate",
f"(cd {DIR} && {DIR}/venv/bin/pip install -r {DIR}/requirements.txt)",
f"(cd {DIR} && {DIR}/venv/bin/pip install --editable dace)",
f"source {DIR}/venv/bin/activate"
]
return '\n'.join(comma... | magicoder | python |
You are tasked with implementing a command-line argument parser that supports parsing long-form arguments in the format `--key value`. Each argument may have an optional value associated with it. If no value is provided, the argument should default to a boolean `True`. The parser should also support parsing nested argu... | ```python
import re
import yaml
from typing import List, Dict, Union
def parse_arguments(args: List[str]) -> Dict[str, Union[bool, Any]]:
re_arg = re.compile(r'^--(?P<key>[a-zA-Z_](\w|.|_)*)')
n_args = len(args)
parsed_args = {}
i = 0
while i < n_args:
m = re_arg.match(args[i])
if m... | magicoder | python |
You are tasked with creating a Python function that processes a list of project updates and applies them to a database. The function should take in the project ID and a dictionary of project updates, and then update the corresponding project in the database with the provided changes.
The function signature is as follo... | ```python
from typing import Optional
from pymongo import MongoClient
def update_project(project_id: int, update_project: dict) -> bool:
# Connect to the database
client = MongoClient('mongodb://localhost:27017/')
db = client['Project21Database']
collection = db['projects']
# Find the project in t... | magicoder | python |
You are tasked with implementing a function that calculates the total number of unique ways to reach the top of a staircase. You can climb the staircase by either taking one step or two steps at a time. The function should take the number of steps in the staircase as input and return the total number of unique ways to ... | ```swift
func climbStairs(_ n: Int) -> Int {
if n <= 2 {
return n
}
var dp = Array(repeating: 0, count: n + 1)
dp[1] = 1
dp[2] = 2
for i in 3...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[n]
}
```
The `climbStairs` function uses dynamic programming to ca... | magicoder | swift |
You are tasked with implementing a function to calculate the entropy of a given text or binary data. Entropy is a measure of uncertainty or randomness in a dataset. For text, it measures the average information content per character, while for binary data, it measures the average information content per bit.
You need ... | ```python
from typing import Union
import math
def calculate_entropy(data: Union[str, bytes]) -> float:
if not data:
return 0.0 # Return 0.0 for empty input
if isinstance(data, str): # Calculate entropy for text data
probabilities = [float(data.count(c)) / len(data) for c in set(data)]
... | magicoder | python |
You are tasked with implementing a function to validate and process a license pack for a software product. The license pack is represented by the `LicPack` structure, which contains various fields including `szTlsServerName`, a string representing the name of the TLS server associated with the license pack. Your task i... | ```c
#include <stdio.h>
#include <string.h>
typedef struct {
char szTlsServerName[256];
// Other fields representing the license pack
} LicPack;
char* processLicensePack(LicPack licensePack) {
char domainName[256];
char* ptr = strchr(licensePack.szTlsServerName, '.');
if (ptr != NULL) {
... | magicoder | c |
You are given a code snippet that involves the computation of norms and the timing of operations related to finite element methods. Your task is to create a programming problem that tests the understanding of computational complexity and efficiency in the context of finite element methods.
Write a function `compute_no... | ```python
from dolfin import Timer, norm, project
def compute_norms_and_timings(fp, fm, fd, fb, mu, lmd, g, ls, pc, do_write):
t2 = Timer()
u = fp() # Compute the solution using the finite element method for the primal problem
ul2 = round(norm(u), 5) # Compute the L2 norm of the solution u
uli = roun... | magicoder | python |
You are tasked with implementing a pipeline system for processing abstract syntax trees (ASTs) in Python. The pipeline system consists of a `Pipeline` class with a method for rewriting AST nodes. The `Pipeline` class has an attribute `visitor` which is an instance of the `PipelineVisitor` class. Your goal is to impleme... | ```python
# Implementation of the PipelineVisitor class
class PipelineVisitor:
def __init__(self, activation):
self.activation = activation
def visit(self, node):
# Perform specific operations on the AST node based on the activation
# Example logic:
if self.activation:
... | magicoder | python |
You are tasked with implementing a Python function that generates a sequence of raw shares using a cryptographic library. The function takes a byte array as input and returns an iterator of raw shares. However, there is a critical security vulnerability in the given code snippet that needs to be identified and fixed.
... | The security vulnerability in the given code snippet is that it only checks if the `secret_int` is less than the prime number `prime`. This check is insufficient to ensure the security of the raw shares generation process. To fix this vulnerability, we need to use a secure method for generating raw shares.
One way to ... | magicoder | python |
You are tasked with creating a Python program to simulate an automated car windshield cleaning system. The program should continuously run a function to initialize the windshield cleaning process and then wait for a specific duration before repeating the process. However, the program should be designed to gracefully ha... | ```python
import time
def init_parabrisa():
# Placeholder for the actual windshield cleaning process
print("Initiating windshield cleaning process...")
try:
while True:
init_parabrisa()
print("\n----------------------------------\n")
time.sleep(86400000)
except KeyboardInterrupt:
... | magicoder | python |
You are tasked with debugging a module import issue in a TypeScript project. The project uses the `import` statement to import a module from a file named "bad-module.ts". However, the import statement is encountering an error, and you need to identify and fix the issue.
Given the code snippet:
```typescript
import * a... | The import statement `import * as badModule from "bad-module.ts";` is encountering an error due to the incorrect usage of the file extension in the module specifier. In TypeScript, when importing a module from a file, the file extension should not be included in the module specifier.
To resolve the issue, the import s... | magicoder | typescript |
You are tasked with implementing a variadic function in Java that can accept a variable number of arguments and apply a given closure to them. A variadic function is a function that can take a variable number of arguments. You are provided with a partial code snippet for the `IconVariadicFunction` class, which is inten... | ```java
/**
* Represents a variadic function that applies a closure to a variable number of arguments.
* @param <T> The type of the input arguments.
* @param <R> The type of the result produced by the closure.
*/
public class IconVariadicFunction<T, R> implements VariadicFunction<T, R> {
private Closure<T, R> ... | magicoder | java |
You are tasked with implementing a resource directory search algorithm for a directory utility class in C++. The `DirectoryUtils` class contains member functions to retrieve the working directory and the resource directory, as well as a private member variable `m_resourceDirectory` that stores the result of the resourc... | ```cpp
fs::path DirectoryUtils::searchResourceDirectory(const fs::path& workingDirectory) {
// Start the search from the working directory
fs::path currentDirectory = workingDirectory;
// Traverse up the directory structure until the resource directory is found
while (!currentDirectory.empty()) {
... | magicoder | cpp |
You are tasked with simulating a traffic light system using Python. The traffic light system consists of two lights, r1 and r2, which can be in either an "on" or "off" state. The lights should follow a specific sequence of turning on and off, with a delay of 0.5 seconds between each action. The sequence is as follows:
... | ```python
import time
class TrafficLight:
def on(self):
print("Light is on")
def off(self):
print("Light is off")
def simulate_traffic_lights():
r1 = TrafficLight()
r2 = TrafficLight()
time.sleep(0.5)
r1.off()
time.sleep(0.5)
r2.on()
time.sleep(0.5)
r2.off()
... | magicoder | python |
You are tasked with implementing a Python function that calculates the value of a mathematical function at a specific input. The function is defined as follows:
```python
class TestFunction:
def f(self, x):
# Implementation of the function goes here
pass
```
You need to implement the `f` method of... | ```python
class TestFunction:
def f(self, x):
# Placeholder implementation for the function
return x**2 + 2*x + 1
```
In this solution, the `f` method of the `TestFunction` class is implemented to calculate the value of the function at the given input `x`. The specific implementation provided here i... | magicoder | python |
You are working on a mapping application that requires the manipulation of geographical coordinates. Your task is to implement a function that performs a specific type of coordinate transformation. The function takes as input a 2D array representing a grid of geographical coordinates and two integer values representing... | ```python
def shiftCoordinates(grid, lonShift, latShift):
for i in range(len(grid)):
grid[i][1] += lonShift
if grid[i][1] > 180:
grid[i][1] = -180 + (grid[i][1] - 180)
elif grid[i][1] < -180:
grid[i][1] = 180 + (grid[i][1] + 180)
return grid
```
The `shiftCoordina... | magicoder | python |
You are tasked with implementing a Python function that generates PCM (Pulse Code Modulation) audio data for a given set of parameters. PCM is a method used to digitally represent analog signals, commonly used in audio processing and storage.
The function takes in the following parameters:
- `numCh`: An integer repres... | ```python
import math
import struct
def generate_pcm_data(numCh, peakLevel, sampWidth):
freq1 = 440 # Frequency of the first sine wave component (e.g., A4 note)
freq2 = 660 # Frequency of the second sine wave component (e.g., E5 note)
fade = 0.5 # Amplitude fade factor
sampRate = 44100 # Sample ra... | magicoder | python |
You are tasked with implementing a text processing class that performs various operations on words and text. The class contains the following methods and attributes:
- `__is_not_word(word)`: A private method that takes a string `word` as input and returns `True` if the input is not a valid word, and `False` otherwise.... | ```python
class TextProcessor:
def __init__(self, opencc):
self.opencc = opencc
def __is_not_word(self, word):
# Implementation of __is_not_word method
def __is_redirect(self, text):
# Implementation of __is_redirect method
def __clean(self, text):
# Implementation of ... | magicoder | python |
You are tasked with implementing a class for converting data to an Excel format. The class, `ExcelConvertMap`, is used to map properties of a data object to specific columns in an Excel spreadsheet. The code snippet provided is a part of the `ExcelConvertMap` class, specifically the method for building the mapping.
Yo... | ```csharp
public class ExcelConvertMap
{
private Dictionary<string, ExcelConvertMapBuilder> _props = new Dictionary<string, ExcelConvertMapBuilder>();
public ExcelConvertMap MapProperty<T>(Expression<Func<T, object>> property, string columnName)
{
var propName = GetPropertyName(property);
v... | magicoder | csharp |
You are tasked with implementing a function that takes a string as input and returns the number of unique characters in the string. The function should consider both uppercase and lowercase letters as distinct characters. For example, the string "HelloWorld" contains 10 unique characters: H, e, l, o, W, r, d. The funct... | ```python
def countUniqueCharacters(s):
unique_chars = set()
for char in s:
if char.isalpha():
unique_chars.add(char.lower())
return len(unique_chars)
```
The `countUniqueCharacters` function initializes an empty set to store unique characters. It then iterates through each character in... | magicoder | python |
You are tasked with creating a Python function that parses a given code snippet to extract the author and license information. The code snippet will be in the form of a multi-line string, and the author and license information will be specified within the string. The function should return a dictionary containing the e... | ```python
import re
def extract_info(code_snippet: str) -> dict:
pattern = r"author='(.*?)',\s*license='(.*?)',\s*\)"
match = re.search(pattern, code_snippet)
if match:
author = match.group(1)
license_type = match.group(2)
return {'author': author, 'license': license_type}
else:... | magicoder | python |
You are tasked with creating a C# class that manages a connection to a server using the provided code snippet as a starting point. Your task is to extend the class with additional functionality to handle the connection and data retrieval.
You need to create a class called `ServerConnection` with the following properti... | ```csharp
using System;
using System.Data;
using System.Data.SqlClient;
using System.Net;
public class ServerConnection
{
public IPEndPoint Server { get; set; }
public string ConnectionString { get; set; }
public int Mandant { get; set; }
private SqlConnection connection;
public void Connect()
... | magicoder | csharp |
You are tasked with implementing a function that validates a given string against a set of predefined validation scripts. Each validation script is represented as a string and contains a specific set of rules for validating the input string. The validation function should return true if the input string passes all the ... | ```javascript
function validateString(inputString, validationScripts) {
for (let script of validationScripts) {
if (script === "alpha") {
if (!/^[a-zA-Z]+$/.test(inputString)) {
return false;
}
} else if (script === "numeric") {
if (!/^\d+$/.test(i... | magicoder | javascript |
You are tasked with creating a program that analyzes the frequency of words in a given text. Your program should take a string of text as input and output the frequency of each word in the text. For the purpose of this problem, a word is defined as a sequence of characters separated by spaces. Punctuation marks should ... | ```python
def word_frequency(text):
# Remove punctuation and convert text to lowercase
text = text.lower().replace('.', '').replace(',', '')
words = text.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_co... | magicoder | python |
You are tasked with implementing a basic tree data structure in Python. The tree will consist of nodes, each of which can have a parent and a single child. You need to create a class `TreeNode` with the following methods:
1. `__init__(self, value, parent)`: Initializes a node with a given value and parent. If the node ... | ```python
class TreeNode:
def __init__(self, value, parent=None):
self._value = value
self._parent = parent
self._child = None
def get_child(self):
return self._child
def get_parent(self):
return self._parent
def set_child(self, child):
self._child = ch... | magicoder | python |
You are given a Python code snippet that defines a function `gen()` and then calls it using `print(gen())`. The function `gen()` is supposed to generate a result based on the values of `exist_def` and `no_def` for each element in the lists `exist_param` and `no_param`. However, the code snippet is incomplete and contai... | ```python
def gen():
exist_param = [1, 2, 3]
no_param = ['a', 'b', 'c']
exist_def = "Existential parameter: %s, %s"
no_def = "No parameter: %s, %s"
result = ""
for x in exist_param:
result += exist_def % (x, x) + '\n\n'
for x in no_param:
result += no_def % (x, x) + '\n\... | magicoder | python |
You are tasked with implementing a simplified version of a requestAnimationFrame (RAF) class in TypeScript. The provided code snippet outlines the beginning of the RAF class, which is responsible for managing animation frames in a web application. Your task is to complete the implementation of the RAF class by adding t... | ```typescript
type TimerIdMap = {
timeout: Record<string, number>;
interval: Record<string, number>;
};
export default class RAF {
private timerIdMap: TimerIdMap;
public constructor() {
this.timerIdMap = {
timeout: {},
interval: {},
};
}
private run(type: 'timeout' | 'interval', cb: (... | magicoder | typescript |
You are tasked with creating a Python program that simulates a simple file management system. Your program should implement a class called `FileManager` which allows users to perform basic file management operations such as creating, deleting, and listing files.
The `FileManager` class should have the following method... | ```python
from typing import List
class FileManager:
def __init__(self):
self.files = []
def create_file(self, name: str):
try:
# Simulate file creation
# Add the file to the list of files
self.files.append(name)
print(f"File '{name}' created suc... | magicoder | python |
You are given a code snippet that uses a function `qRound()` to round two different floating-point values `valueA` and `valueB`. The comments in the code snippet indicate the rounded values of `valueA` and `valueB`. Your task is to implement the `qRound()` function and write a program to round floating-point numbers to... | ```cpp
#include <iostream>
int qRound(double value) {
return static_cast<int>(value + 0.5);
}
int main() {
double valueA = 1.6;
double valueB = 2.8;
int roundedValueA = qRound(valueA);
int roundedValueB = qRound(valueB);
std::cout << "Rounded value of " << valueA << ": " << roundedValueA << ... | magicoder | cpp |
You are tasked with creating a Python function that processes a given string to extract and count the occurrences of all unique words in the string. The function should ignore any non-alphabetic characters and treat uppercase and lowercase letters as equivalent. Additionally, the function should return the word counts ... | ```python
import re
def count_unique_words(input_string):
word_counts = {}
words = re.findall(r'\b\w+\b', input_string.lower())
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return dict(sorted(word_counts.items(), k... | magicoder | python |
You are tasked with implementing a thread-safe counter class in C++ using atomic operations. The class should have methods to increment the counter, decrement the counter, and retrieve the current value of the counter.
Your task is to complete the implementation of the `Counter` class by filling in the missing parts o... | ```cpp
#include <atomic>
class Counter {
public:
Counter() : count(0) {}
void increment() {
count.fetch_add(1, std::memory_order_relaxed);
}
void decrement() {
count.fetch_sub(1, std::memory_order_relaxed);
}
int get() const {
return count.load(std::memory_order_relax... | magicoder | cpp |
You are tasked with creating a Python class that processes genomic features from a given data file and performs various operations on them. The class should be able to read data from a specified file, store the features, and provide methods to manipulate and analyze the genomic features.
Your task is to implement the ... | ```python
import os
import numpy as np
import pandas as pd
class GenomicFeatures:
def __init__(self, data_path, features):
self.data_path = data_path
self.features = features
self.genomic_data = None
def read_data(self):
try:
self.genomic_data = pd.read_csv(self.dat... | magicoder | python |
You are tasked with implementing a Python function that generates a bar plot to visualize the results of a backwards optimization process. The function should take several input parameters and produce a plot based on the provided data.
You are given the following function signature and parameter descriptions:
```pytho... | ```python
import matplotlib.pyplot as plt
import numpy as np
def plot_backwards_optimization_results(input_file_name, diff_colour_map_name, max_diff_percentile, plot_soundings, allow_whitespace, plot_panel_names, label_colour_bars, colour_bar_length, top_output_dir_name):
# Load data from input_file_name and perfo... | magicoder | python |
You are tasked with creating a validation middleware for a gaming platform using TypeScript and Fastify. The middleware should ensure that the incoming requests for creating game setups adhere to a specific set of rules. The code snippet provided is a partial definition of a TypeScript class constructor that is part of... | ```typescript
class GameSetupValidationMiddleware implements fastify.FastifyRequest & UserContainer,
GameSetupsCreationQuery,
GameSetupCreationQueryApiV1,
GameSetupCreationQueryApiV1ValidationContext
{
constructor(request: fastify.FastifyRequest & UserContainer,
gameSetupQuery: GameSetupsCreationQ... | magicoder | typescript |
You are tasked with implementing a function to perform Tarjan's algorithm for finding strongly connected components (SCCs) in a directed graph. Tarjan's algorithm is a depth-first search-based algorithm that efficiently finds all SCCs in a graph. The algorithm assigns a unique identifier to each SCC and returns the SCC... | ```cpp
#include <iostream>
// The provided code snippet is a partial implementation of Tarjan's algorithm for finding strongly connected components (SCCs) in a directed graph.
// The missing parts of the dfs function need to be completed to correctly identify the SCCs and return them in a topologically sorted order.
... | magicoder | cpp |
You are tasked with creating a Python function that determines the language code based on a given IP address. The function should take an IP address as input and return the corresponding language code based on a provided mapping file. The mapping file contains ranges of IP addresses and their corresponding language cod... | ```python
import pandas as pd
# import file for ip's to language mapping
df_ip_lang = pd.read_csv('pages/lng_map.csv', names=['ip_from', 'ip_to', 'country_code', 'country_name', 'lang_code'] )
def get_language_code(ip_address):
ip_int = struct.unpack("!I", socket.inet_aton(ip_address))[0] # Convert IP address to... | magicoder | python |
You are tasked with creating a Python function to preprocess and split a dataset for training a machine learning model. The dataset is stored in a MATLAB file and contains two arrays: `dic_label` and `x_dic`. The `dic_label` array is loaded from a file named `dic_label.mat`, and the `x_dic` array is loaded from a file ... | ```python
import scipy.io
import numpy as np
def preprocess_and_split_data(dataPath):
# Load dic_label array from dic_label.mat
dic_label = scipy.io.loadmat('../CSENdata-2D/dic_label' + '.mat')["ans"]
# Load x_dic array from the specified dataPath
Data = scipy.io.loadmat(dataPath)
x_dic = Data... | magicoder | python |
You are given a Python class `Solution` with a method `sortedArrayToBSTRecu` that takes in a sorted array of integers `nums`, a start index `start`, and an end index `end`. The method is intended to convert the sorted array into a height-balanced binary search tree (BST).
The method uses a helper function `perfect_tre... | ```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sortedArrayToBSTRecu(self, nums, start, end):
if start == end:
return None
mid = start + self.perfect_tree_pivot... | magicoder | python |
You are tasked with creating a Python class to manage software tools and their versions. The class should be able to check for the existence of a tool, install it if it is not found, and print the status of each tool. Your task is to implement the `Tool` class and its methods according to the given specifications.
The... | ```python
class Tool:
def __init__(self, tooldir, version):
self.tooldir = tooldir
self.version = version
self.name = self.__class__.__name__
def have(self):
# Implement the logic to check if the tool exists in the specified directory
# Return True if the tool is found, ... | magicoder | python |
You are tasked with implementing a C++ template meta-programming problem. Your goal is to create a meta-function that takes a variadic list of types and returns a new type that is a tuple of the input types.
You are given the following code snippet as a starting point:
```cpp
template<typename... Ret>
struct MakeTuple... | ```cpp
template<typename... Ret>
struct MakeTuple {
typedef std::tuple<Ret...> type;
};
```
The solution is to simply complete the `MakeTuple` meta-function by providing the missing implementation for the `template<typename Ret>` part. The provided code snippet already correctly defines the meta-function to take a... | magicoder | cpp |
You are tasked with creating a script to automate the process of managing snapshots for a cloud infrastructure. The infrastructure uses Docker containers and requires several steps to be executed in a specific order. Your script should handle the following tasks:
1. Run the `cleanup.sh` script to clean up any existing... | ```bash
#!/bin/bash
# Step 1: Run the cleanup script
echo "Running cleanup.sh"
./cleanup.sh
cleanup_exit_code=$?
if [ $cleanup_exit_code -ne 0 ]; then
echo "Cleanup failed with exit code $cleanup_exit_code"
exit 1
fi
# Step 2: Create snapshots using docker-compose
echo "Creating snapshots"
docker-compose run crea... | magicoder | shell |
You are tasked with implementing a user registration system in TypeScript. You are given an interface `User` which represents the structure of user data. The interface has the following properties:
- `id` (optional): A number representing the user's unique identifier.
- `username`: A string representing the user's user... | ```typescript
// Define the User interface
interface User {
id?: number;
username: string;
email?: string;
password: string;
confirmPassword?: string;
}
// Define the ValidationResult type
type ValidationResult = "User registered successfully" | "Username cannot be empty" | "Invalid email address" ... | magicoder | typescript |
You are tasked with implementing a Python function that processes a list of strings representing code snippets and returns the count of occurrences of a specific function call within the snippets. The function call is represented as `result.assert_installed('project', editable=False)`.
The function signature is:
```p... | ```python
from typing import List
import re
def count_function_calls(snippets: List[str]) -> int:
function_call = "result.assert_installed('project', editable=False)"
count = 0
for snippet in snippets:
count += len(re.findall(re.escape(function_call), snippet))
return count
```
The `count_funct... | magicoder | python |
You are tasked with creating a Python program that utilizes a word frequency list to perform various operations on a given text. The word frequency list is stored in a file named "englishwords.freq". Your program should read this file and implement the following functionalities:
1. Calculate the frequency of each word... | ```python
# Import necessary libraries and modules
import re
import cbapi
from freq import *
import requests
# Disable SSL warnings
requests.packages.urllib3.disable_warnings()
# Function to calculate the frequency of each word in the given text
def calculate_word_frequency(text):
# Load the word frequency list f... | magicoder | python |
You are tasked with implementing a simple application status manager in C++. The given code snippet is a part of the application's main loop, which handles different Windows messages and controls the application status based on these messages. The `mStatus` variable is used to track the application's status, and it can... | ```cpp
#include <iostream>
// Define the possible application statuses
enum ApplicationStatus {
APP_RUN,
APP_QUIT,
// Add other statuses as needed
};
class ApplicationStatusManager {
private:
ApplicationStatus mStatus;
public:
// Constructor to initialize the application status
ApplicationSta... | magicoder | cpp |
You are tasked with creating a JavaScript module that exports specific functionalities from other modules. Your task is to implement a function that takes an array of module names and dynamically imports and exports the functionalities from those modules.
You are given the following code snippet as a starting point:
`... | ```javascript
async function dynamicModuleImportExport(moduleNames) {
const exportedFunctionalities = {};
for (const moduleName of moduleNames) {
const module = await import(`./${moduleName}`);
Object.assign(exportedFunctionalities, module);
}
return exportedFunctionalities;
}
```
In this solution, th... | magicoder | javascript |
You are tasked with creating a Python class that manages a playlist of thumbnail images for a media player application. The class should allow adding, removing, and displaying thumbnail images, as well as automatically updating the displayed image at regular intervals.
Your task is to implement the `ThumbnailPlaylist`... | ```python
import os
from kivy.clock import Clock
from kivy.uix.image import AsyncImage
class ThumbnailPlaylist:
def __init__(self):
self.images = []
def add_image(self, image_url):
self.images.append(image_url)
def remove_image(self, image_url):
if image_url in self.images:
... | magicoder | python |
You are tasked with implementing a custom dictionary class in Python that supports both key-based and index-based access. The dictionary should allow the user to access values using either the key or the index, similar to how a regular dictionary allows key-based access and a list allows index-based access.
Your custo... | ```python
class CustomDictionary:
def __init__(self, *args):
self.key_value_pairs = dict(args)
def __getitem__(self, key_or_index):
if isinstance(key_or_index, int):
keys = list(self.key_value_pairs.keys())
if 0 <= key_or_index < len(keys):
return self.ke... | magicoder | python |
You are tasked with creating a Java package for performing physics calculations. The package should include classes for basic mathematical operations commonly used in physics, such as vector manipulation, kinematics, and dynamics. Your task is to create the necessary classes and methods within the `physicsMath` module ... | ```java
// VectorMath.java
public class VectorMath {
public static double[] addVectors(double[] vector1, double[] vector2) {
if (vector1.length != vector2.length) {
throw new IllegalArgumentException("Vector dimensions must be the same for addition");
}
double[] result = new doub... | magicoder | java |
You are tasked with implementing a C++ template meta-programming problem. Your goal is to create a metafunction that determines the value type of an iterator.
You are provided with a code snippet that defines a template metafunction `value_of` within a struct. The `value_of` metafunction takes a type `T` as a template... | ```cpp
#include <iostream>
#include <type_traits>
namespace detail {
template <typename T>
struct is_iterator {
using yes = char;
using no = struct { char _[2]; };
template <typename C>
static yes test(typename std::iterator_traits<C>::iterator_category*);
template <typename>
static no te... | magicoder | cpp |
You are tasked with implementing a function to validate and access shared items from a cloud storage service. The function `SharedItemsAsync` takes a shared link and an optional password as input and returns a `BoxItem` object if the shared link is valid and the user has access to it. If the link is invalid, requires a... | ```csharp
using System;
using System.Threading.Tasks;
public class BoxItem
{
public string Name { get; set; }
public bool IsFolder { get; set; }
// Other properties and methods
}
public interface IBoxService
{
Task<BoxItem> SharedItemsAsync(string sharedLink, string sharedLinkPassword = null);
}
publ... | magicoder | csharp |
You are tasked with creating a Python script to simulate a flight booking system. The system should allow users to search for available flights based on their origin, destination, and date of travel. The flights are stored in a CSV file with the following format:
```
flight_id,origin,destination,date,available_seats,p... | ```python
import csv
def search_flights(origin, destination, date):
with open('flights.csv', 'r') as file:
reader = csv.DictReader(file)
flights = [flight for flight in reader if flight['origin'] == origin and flight['destination'] == destination and flight['date'] == date and int(flight['available... | magicoder | python |
You are tasked with creating a script that automates the process of running a Docker container and executing a specific command within the container. Your script should take three command-line arguments: the working directory, the container name, and the command to be executed within the container.
Write a Python scri... | ```python
import docker
import sys
def run_docker_command(working_dir, container_name, command):
try:
client = docker.from_env()
if not client.ping():
print("Docker daemon is not running. Please start Docker and try again.")
return
client.containers.run(container_na... | magicoder | python |
You are tasked with implementing a Python function that manipulates matrices using the NumPy library. The function should perform the following operations:
1. Extract a submatrix from a given matrix.
2. Create and print identity, zero, and ones matrices.
Your task is to complete the Python function `matrix_operations... | ```python
import numpy
def matrix_operations(arr):
print(arr[0, 3]) # Print the element at the 0th row and 3rd column of the input array arr.
print('Extracting a submatrix') # Print the message "Extracting a submatrix".
subarr = arr[1:3, 1:] # Extract a submatrix from arr using slicing.
print(subarr... | magicoder | python |
You are tasked with implementing a feature extraction class for a natural language processing system. The class, named `GoogleTranslateFeatureExtractor`, is responsible for extracting features from a given context object using Google Translate API. The provided code snippet is a part of the `GoogleTranslateFeatureExtra... | ```python
from nltk.tokenize import word_tokenize
from goslate import Goslate
class NoDataError(Exception):
def __init__(self, data_type, context_obj, feature_extractor):
self.data_type = data_type
self.context_obj = context_obj
self.feature_extractor = feature_extractor
super().__i... | magicoder | python |
You are working on a large-scale enterprise application that utilizes various services for different functionalities. The application is built using TypeScript and Angular framework. The code snippet provided includes imports for several services used in the application.
Your task is to create a TypeScript class that ... | ```typescript
import { WorkerService } from '@app/_services/worker.service'
import { BusinessService } from '@app/_services/business.service'
import { ProjectService } from '@app/_services/project.service';
import { WindowRefService } from '@app/_services/window-ref.service';
import { PackageService } from '@app/_servi... | magicoder | typescript |
You are tasked with implementing a function that performs Optical Character Recognition (OCR) on an image file. The function should take a local file path as input and return the recognized text from the image using OCR technology.
You are provided with the following code snippet as a starting point:
```python
'''... | ```python
import pytesseract
from PIL import Image
import os
def perform_ocr(path):
try:
if os.path.exists(path):
image = Image.open(path)
recognized_text = pytesseract.image_to_string(image)
return recognized_text
else:
return "File does not exist at... | magicoder | python |
You are tasked with creating a Python program to manage a database of people's names. You will need to define a class for the database connection and another class to represent a person's name. The person's name should be unique within the database. Your program should allow for adding new names to the database, retrie... | ```python
class Database:
def connect(self, database_name):
# Implement database connection logic here
pass
class Person(Database):
def add_name(self, name):
# Implement adding a new name to the database
if self.name_exists(name):
raise DuplicateNameError("Name alrea... | magicoder | python |
You are tasked with creating a program that utilizes the Microsoft Azure Cognitive Services Language Understanding (LUIS) Runtime SDK to analyze user input and extract relevant information. The program should take user input in the form of a text query and use the LUIS Runtime SDK to process the query and extract entit... | ```csharp
public async Task<(string topIntent, IDictionary<string, string> entities)> ProcessQueryAsync(string query)
{
var predictionRequest = new PredictionRequest { Query = query };
var predictionResult = await _luisRuntimeClient.Prediction.ResolveAsync("<YOUR_APP_ID>", predictionRequest);
var topIntent... | magicoder | csharp |
You are tasked with creating a TypeScript class that represents an ORM (Object-Relational Mapping) entity for storing options related to questions in a database. The provided code snippet is a starting point for the implementation. Your task is to complete the `OrmOption` class by adding the necessary properties and de... | ```typescript
import { Entity, Column, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from "typeorm"
import { Option } from "../../entities/option"
import { Question } from "../../entities/question"
import { BaseModel } from "./baseModel"
import { OrmQuestion } from "./question"
@Entity("options")
export class OrmOpt... | magicoder | typescript |
You are tasked with creating a program that generates a simple visualization of a bar chart using Python's matplotlib library. The program should take a list of data points and corresponding labels as input and produce a bar chart with labeled bars. The code snippet provided below is a part of the program that places a... | ```python
import matplotlib.pyplot as plt
def generate_bar_chart(data, labels):
# Create a bar chart
fig, ax = plt.subplots()
bars = ax.bar(range(len(data)), data, tick_label=labels)
# Add labels to the bars
for i, bar in enumerate(bars):
height = bar.get_height()
ax.text(bar.get_x... | magicoder | python |
You are working on a quantum computing project and need to implement a quantum circuit to solve a specific problem. The code snippet provided is a part of the quantum circuit implementation using the Qiskit framework in Python. Your task is to understand the given code and write a function to perform a similar quantum ... | ```python
import numpy as np
from qiskit import QuantumCircuit, execute
def execute_quantum_circuit(initvec, state_scale, state_backend, H, sigma):
# Initialize a quantum circuit
check_circuit = QuantumCircuit(state_scale)
# Initialize the quantum circuit with the given initial state vector
check_... | magicoder | python |
You are working on a code editor application and need to implement a feature to mark syntax errors in the code. The code snippet provided is part of a class responsible for updating the status message and marking errors in the code view.
Your task is to implement the `_mark_errors_in_view` method, which takes a `view`... | ```python
def _mark_errors_in_view(self, view, errors):
# Clear any existing error markers and messages
view.clear_error_markers()
# Iterate through the errors list and mark errors in the view
for line_number, error_message in errors:
view.mark_error_at_line(line_number) # Mark the error o... | magicoder | python |
You are tasked with implementing a Python function that simulates a simplified image processing pipeline. The function will receive input parameters related to image processing and is expected to perform a series of operations on a batch of images. Your task is to complete the function according to the given specificat... | ```python
def image_processing_pipeline(num_remaining_images: int, iteration: int, data_sess, infer_sess, images, output_tensor, num_processed_images: int, batch_size: int, warmup_iters: int) -> None:
while num_remaining_images >= batch_size:
np_images = data_sess.run(images)
if iteration > warmup_i... | magicoder | python |
You are tasked with implementing a multi-threaded producer-consumer problem using Java. The producer-consumer problem is a classic synchronization problem where there are two threads involved: a producer thread that produces items and a consumer thread that consumes those items. The threads share a common, fixed-size b... | ```java
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Queue;
import java.util.LinkedList;
class Producer implements Runnable {
// ... (same as in the problem description)
public void run() {
while (true) {
consumer_lock.lock(... | magicoder | java |
You are tasked with implementing a simplified version of a property accessor in C#. Your goal is to create a class that encapsulates a property and provides a way to get and set its value. The property should be accessed through a public property accessor, which internally uses a private field to store the value.
Your... | ```csharp
public class PropertyAccessor
{
private string RouteHandlerInternal;
public string RouteHandler
{
get => RouteHandlerInternal;
set => RouteHandlerInternal = value;
}
}
```
The `PropertyAccessor` class encapsulates the private field `RouteHandlerInternal` and provides a public ... | magicoder | csharp |
You are tasked with implementing a custom `ToStringBuilder` class in Java that mimics the behavior of Apache Commons Lang's `ToStringBuilder` class. The `ToStringBuilder` class should allow for the creation of a string representation of an object's state by appending various fields and their values. Your implementation... | ```java
import java.util.List;
public class ToStringBuilder {
private final StringBuilder stringBuilder;
public ToStringBuilder(Object object) {
this.stringBuilder = new StringBuilder(object.getClass().getSimpleName() + "[");
}
public ToStringBuilder append(String fieldName, Object value) {
... | magicoder | java |
You are tasked with implementing a custom data processing module in a particle physics analysis framework. The framework uses the CMS software suite, and the code snippet provided is a configuration for a module called "TrackOfThingsProducer". This module is responsible for producing a collection of reconstructed parti... | ```cpp
#include <iostream>
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/TrackReco/interface/TrackFwd.h"
class TrackAnalyzer : public edm::... | magicoder | cpp |
You are tasked with implementing a custom marker for a charting library in a mobile application. The charting library provides a `Chart` object with various properties and methods for customizing the appearance and behavior of the chart. The given code snippet initializes the chart and sets some properties, including d... | ```swift
func getChartMarker() -> BalloonMarker {
let marker = BalloonMarker(color: UIColor.blue, font: UIFont.systemFont(ofSize: 12), textColor: UIColor.white, insets: UIEdgeInsets(top: 5, left: 5, bottom: 15, right: 5))
marker.chartView = chart // Set the chart view for the marker
marker.minimumSize = CGS... | magicoder | swift |
You are tasked with implementing a custom logging system in Swift. The system should allow logging messages with different log levels and provide the flexibility to specify a sender for each log message. The log levels should include "debug", "info", "warning", and "error". The sender can be any type of object or nil i... | ```swift
class Logger {
private var logs: [(message: String, level: String, sender: Any?)] = []
func log(message: String, level: String, sender: Any?) {
logs.append((message, level, sender))
}
func debug(message: String, sender: Any?) {
log(message: message, level: "debug", sender: sen... | magicoder | swift |
You are tasked with implementing a tokenizer for a simple arithmetic expression evaluator. The provided code snippet contains a function `tokenize` that takes a string `input` representing an arithmetic expression and tokenizes it into individual elements. The tokenization process involves splitting the input string in... | ```python
def tokenize(input):
import re
# Define token types
tokenType = {
'+': 'ADD',
'-': 'SUB',
'*': 'MUL',
'/': 'DIV'
}
NUM = 'NUM'
# Tokenize the input string
tokenText = re.split("([+-/*])|\s*", input)
tokens = []
for text in tokenText:
... | magicoder | python |
You are tasked with implementing a function to parse a raw data frame and extract specific information from it. The raw data frame is represented as a string `raw_frame`, and the function should return a dictionary `frame` containing the extracted information. The raw data frame consists of various fields, and the func... | ```python
def parse_raw_frame(raw_frame: str, raw_slice: int) -> dict:
frame = {}
i = (raw_slice + 1) / 7
if 1 < i < 11:
if (ord(raw_frame[raw_slice + 1]) & 0x03 == 0x03 and
ord(raw_frame[raw_slice + 2]) in [0xf0, 0xcf]):
frame['text'] = raw_frame[raw_slice + 3:]
... | magicoder | python |
You are tasked with creating a Python function that processes HTML content to extract image URIs and their corresponding source URLs. The function should take a string of HTML content as input and return a list of tuples, where each tuple contains the URI and source URL of an image.
The HTML content will contain image... | ```python
from typing import List, Tuple
from bs4 import BeautifulSoup
def extract_image_info(html_content: str) -> List[Tuple[str, str]]:
uri_img = []
soup = BeautifulSoup(html_content, 'html.parser')
img_tags = soup.find_all('img')
for img in img_tags:
uri_img.append(('html', img.get('src')))... | magicoder | python |
You are tasked with testing a Python Lambda function that interacts with AWS services using the `boto3` library. The function, `lambda_handler`, is responsible for importing security findings from AWS Security Hub. Your goal is to write a unit test for the `lambda_handler` function to ensure that it behaves as expected... | ```python
import json
from unittest import mock
import pytest
from src.findings.import_security_hub_finding import lambda_handler
from .test_fixtures import os_environment_setup
class TestImportSecurityHubFinding:
@mock.patch("boto3.client")
def test_iam_user_creation_event(self, mock_client, os_environment_... | magicoder | python |
You are tasked with implementing a simple text-based terminal emulator. The given code snippet is part of the implementation of the terminal emulator's internal logic. The `clear` method is intended to clear the screen by resizing it to its current dimensions, effectively clearing all content. The `scroll` method is in... | ```python
class TerminalEmulator:
def __init__(self, width, height):
self.w = width
self.h = height
self.screen = [[' ' for _ in range(width)] for _ in range(height)]
self.scroll_region = [0, height - 1, 0, width - 1]
self.x = 0
self.y = 0
def clear(self):
... | magicoder | python |
You are tasked with implementing a function that compares two strings based on a custom collation order. The collation order is defined by a table and a specified collation strength. The function should return -1 if the first string comes before the second string in the custom collation order, 0 if they are equivalent,... | ```cpp
#include <string>
#include <vector>
#include <algorithm>
#include <unicode/coll.h>
int compareStrings(const std::string& str1, const std::string& str2, const std::vector<uint32_t>& table, collation_strength strength) {
UErrorCode status = U_ZERO_ERROR;
UCollator *collator = ucol_openRules(table.data(), ... | magicoder | cpp |
You are tasked with implementing a program to calculate the weight of a word based on the values of its letters. Each letter has a specific value, and the weight of the word is calculated by summing the values of its letters. The program should support the following operations:
1. Add a letter's value to the total wei... | ```java
public class WeightCalculator {
public static int calculateWeight(String word, int multiplier, String op) {
int weight = 0;
for (char letter : word.toCharArray()) {
if (Character.isLetter(letter)) {
int value = Character.toLowerCase(letter) - 'a' + 1;
... | magicoder | java |
You are tasked with creating a Python function that processes stock information and filters it based on a given stock code. The function should take in a stock code and a file path as input, retrieve stock information from an API, save it to a CSV file at the specified path, and then filter the information based on the... | ```python
import ak
import pandas as pd
def process_stock_info(code, path):
# Retrieve stock information
df = ak.index_stock_info()
# Save information to CSV file at the specified path
df.to_csv(path, index=False)
# If a stock code is provided, filter the DataFrame
if code:
df... | magicoder | python |
You are given a code snippet that manipulates a sequence of numbers based on a specific pattern. Your task is to understand the pattern and implement a function that generates the sequence based on the given rules.
The code snippet provided performs the following operations:
- It appends the current number `cur` to a ... | ```python
def generate_sequence(n):
ans = []
cur = 1
layer = 1
while n > 0:
ans.append(cur)
if layer % 2 == 1:
offset = (cur - (1 << (layer - 1))) // 2
layer -= 1
cur = (1 << layer) - 1 - offset
else:
offset = ((1 << layer) - 1 - c... | magicoder | python |
You are given a string `s` consisting of lowercase English letters. The task is to create a function `vowel_game_score(s)` that calculates the score of a vowel game based on the following rules:
- Two players, Stuart and Kevin, play a game with the string `s`.
- The game is played as follows:
- Both players are give... | ```python
def vowel_game_score(s: str) -> str:
vowels = "AEIOU"
Stuart = 0
Kevin = 0
length = len(s)
for i in range(length):
if s[i] in vowels:
Kevin += length - i
else:
Stuart += length - i
if Stuart > Kevin:
return f"Stuart {Stuart}"
elif K... | magicoder | python |
You are tasked with implementing a deep update function that updates a nested dictionary with the values from another dictionary. The deep update function should handle cases where the values are also dictionaries, and merge them recursively. Additionally, if a key exists in both dictionaries and the value is a list, t... | ```python
import copy
def deep_update(dst, src, join_lists=False):
for k, v in src.items():
if k in dst and isinstance(dst[k], dict) and isinstance(v, dict):
deep_update(dst[k], v, join_lists)
elif join_lists and isinstance(v, list) and isinstance(dst[k], list):
dst[k] = dst... | magicoder | python |
You are tasked with implementing a parser for a context-free grammar. The grammar is defined by a set of production rules, each consisting of a non-terminal symbol on the left-hand side (LHS) and a sequence of symbols (terminals and non-terminals) on the right-hand side (RHS). The parser should construct the necessary ... | ```python
def parse_grammar_file(grammar_file):
lnups = {} # Left-hand side non-terminal to RHS rule mapping
rnups = {} # Right-hand side rule to LHS non-terminal mapping
ups = set() # Set of all unique symbols (terminals and non-terminals)
nt_tab = {} # Non-terminal symbol to index mapping
t_ta... | magicoder | python |
You are working on a medical imaging project and need to implement 3D data augmentation techniques to enhance the quality of the input data. You decide to use the Kornia library, which provides a wide range of 3D augmentation functions. Two of the functions you plan to use are `RandomEqualize3D` and `RandomMotionBlur3D... | ```python
# Sample usage of the apply_3d_augmentation function
import torch
# Create a sample 3D image tensor
input_image = torch.rand(32, 64, 64) # Depth: 32, Height: 64, Width: 64
# Apply random equalization with 50% probability and random motion blur with 30% probability
augmented_image = apply_3d_augmentation(in... | magicoder | python |
You are tasked with creating a program to manage a multiplayer online game's portal system. The game world consists of multiple interconnected portals, and players can travel between different locations using these portals. However, due to recent changes in the game, the portals need to be restricted based on certain c... | ```python
class Player:
def __init__(self, name, level):
self.name = name
self.level = level
def sendMessage(self, message):
print(f"{self.name}: {message}")
class Portal:
def __init__(self, destination, requiredLevel):
self.destination = destination
self.requiredL... | magicoder | python |
You are tasked with implementing a function to calculate the size of an image in bytes based on its width, height, and color depth. The color depth is given in bits per pixel (bpp), and the image is assumed to be in RGB format. The size of the image is calculated using the formula: `imageSize = width * height * (bpp / ... | ```java
public int calculateImageSize(int width, int height, int bpp) {
return width * height * (bpp / 8);
}
``` | magicoder | java |
You are tasked with creating a simplified version of the card game Blackjack. In this version, the value of an ace card can be either 1 or 11, and the goal is to determine the best possible score for a given set of cards. The score for a player's hand is calculated by summing the values of the cards, with aces potentia... | ```python
# Calculate the best possible score for the player's hand
for card in your_cards:
if card != 'A':
score += card
else:
if ace_set and score + ace_value <= 21:
score += ace_value
else:
score += 1
# Calculate the best possible score for the dealer's hand
f... | magicoder | python |
You are tasked with creating a URL routing system for a web application using Django. The given code snippet represents a list of URL patterns in a Django application. Each URL pattern is associated with a specific view and has a unique name. Your task is to write a function that takes a URL name as input and returns t... | ```python
def get_view_for_url(url_patterns, url_name):
for pattern in url_patterns:
if pattern[2] == url_name:
return pattern[1]
return None
```
The `get_view_for_url` function iterates through the `url_patterns` list and checks if the URL name matches the given `url_name`. If a match is f... | magicoder | python |
You are tasked with implementing a benchmarking tool to measure the performance of different test cases across various environments. The provided code snippet is a part of the benchmarking tool and is responsible for populating a 2D array `tab` with the results of running `test_func` on different combinations of enviro... | ```python
import time
def bench_one(test_func, env, case, *args, **vargs) -> float:
start_time = time.time()
test_func(*args, **vargs)
end_time = time.time()
return end_time - start_time
```
In the `bench_one` function, we use `time.time()` to measure the start and end time of executing `test_func` wit... | magicoder | python |
You are tasked with creating a Python class that simulates a data source for a Postgres database. The class should be able to connect to the database, execute SQL queries, and provide functionality to discover the schema of the queried tables. Your task is to implement the `PostgresSource` class with the following meth... | ```python
import pandas as pd
import os
class PostgresSource:
def __init__(self, url: str, query: str):
self.url = url
self.query = query
def discover(self) -> dict:
# Execute the SQL query and retrieve the schema of the resulting data
# Assuming the query execution retrieves d... | magicoder | python |
You are given three lists `i`, `j`, and `val`, representing a sparse matrix in the form of coordinate lists. Each element in the `i` list represents the row index, each element in the `j` list represents the column index, and each element in the `val` list represents the value at the corresponding row and column indice... | ```python
from typing import List
def sparse_to_dense(i: List[int], j: List[int], val: List[int], n: int, m: int) -> List[List[int]]:
dense_matrix = [[0 for _ in range(m)] for _ in range(n)]
for idx in range(len(i)):
dense_matrix[i[idx]][j[idx]] = val[idx]
return dense_matrix
# Test the function
i... | magicoder | python |
You are tasked with creating a decorator that logs the execution time of a function. Your decorator should print the elapsed time in milliseconds to the console whenever the decorated function is called. You should use the `time` module to measure the elapsed time.
Your decorator function should have the following sig... | ```python
import time
from functools import wraps
def log_execution_time(f):
@wraps(f)
def wrapper(*args, **kwargs):
start_time = time.time()
result = f(*args, **kwargs)
end_time = time.time()
elapsed_time_ms = (end_time - start_time) * 1000
print(f"Elapsed time: {elapse... | magicoder | python |
You are tasked with creating a C# class that manages delegates and function pointers to handle native function calls. Your goal is to implement a class that sets up a native function delegate and links it to a specific function, allowing for the invocation of the native function from managed code.
Your task is to crea... | ```csharp
using System;
using System.Runtime.InteropServices;
public delegate void NativeFuncDelegate(IntPtr context, IntPtr theStack, IntPtr result);
public class NativeFunctionManager
{
private DelegateHolder<NativeFuncDelegate> actionTickLink;
private unsafe void ActionTickProcessEvent(IntPtr context, Int... | magicoder | csharp |
You are tasked with implementing a task scheduler for a system that supports various task properties. Each task can have multiple properties, such as "KillOnIdleEnd," "DontStartIfOnBatteries," "RunOnlyIfDocked," etc. Each property can be either enabled or disabled for a particular task.
Your goal is to design a data s... | ```python
class TaskProperties:
def __init__(self):
self.properties = {}
def set_property(self, property_name: str, value: bool):
self.properties[property_name] = value
def get_property(self, property_name: str) -> bool:
return self.properties.get(property_name, False)
# Usage exa... | magicoder | python |
You are tasked with implementing a Python class for encrypting data using the MySQL v3.2.3 algorithm. The algorithm involves using a key and the `unhexlify` function to encrypt a portion of the input data. Your task is to complete the implementation of the `MySql323` class by writing the `encrypt_data` method.
The `My... | ```python
from binascii import unhexlify
class BaseAlgorithm:
def __init__(self, data):
self.data = data
def encrypt(self, data):
# Placeholder for the encryption logic
pass
class MySql323(BaseAlgorithm):
name = 'MySQL v3.2.3'
key = '<KEY>'
hex_length = 16
def encrypt... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.