query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a program that can efficiently count the occurrences of a given word in a large text file. Your program should be able to handle very large files and provide accurate results in a timely manner. Your program should take as input a file path and a target word, and it should output the c...
To efficiently count the occurrences of a given word in a large text file, we can use a memory-efficient approach by reading the file line by line and processing each line individually. We can use Python for this implementation. ```python def count_word_occurrences(file_path, target_word): count = 0 with open(...
magicoder
python
You are working on a cryptocurrency project that involves note encryption and decryption. The code snippet provided is a part of the Zcash cryptocurrency library and includes declarations for `NoteEncryption` and `NoteDecryption` classes. Your task is to implement a function to generate a random 256-bit unsigned intege...
```cpp #include <iostream> #include <cstdint> #include <array> // Define the uint256 type typedef std::array<uint8_t, 32> uint256; // Define the ZCNoteEncryption class template<size_t NoteSize> class NoteEncryption { public: NoteEncryption(const uint256 &hSig, unsigned char nonce) { // Constructor impleme...
magicoder
cpp
You are tasked with implementing a rate limiter module for a web application. The rate limiter should restrict the number of requests a client can make within a specified time window. To achieve this, you need to create a rate limiter module that enforces a maximum request limit per client within a given time frame. Y...
```rust use std::collections::HashMap; use std::time::{Duration, Instant}; pub struct RateLimiter { request_limit: u32, time_window: Duration, client_requests: HashMap<String, Vec<Instant>>, } impl RateLimiter { pub fn new(request_limit: u32, time_window: Duration) -> Self { RateLimiter { ...
magicoder
rust
You are tasked with creating a utility function that combines the functionality of two existing utility functions for working with images in a web application. The existing utility functions are `getCanvas` and `loadImage`, both of which are imported from the `~utils/dom` module. Your task is to create a new utility f...
```javascript import { getCanvas } from '~utils/dom/getCanvas'; import { loadImage } from '~utils/dom/loadImage'; async function loadAndDrawImage(imageUrl, canvasId) { const canvas = getCanvas(); // Create a new canvas element const ctx = canvas.getContext('2d'); // Get the 2D rendering context const image = aw...
magicoder
javascript
You are tasked with creating a Python function that processes a list of package repositories and returns the name of the repository with the highest priority. Each repository is represented as a string in the format "name-priority", where "name" is the repository name and "priority" is a numerical value indicating its ...
```python from typing import List def highest_priority_repository(repositories: List[str]) -> str: max_priority = float('-inf') max_repo_name = '' for repo in repositories: name, priority = repo.split('-') priority = int(priority) if priority > max_priority: max_pri...
magicoder
python
You are tasked with implementing a data augmentation pipeline for a computer vision model using the provided code snippet as a reference. The code snippet is part of a class constructor that initializes the data augmentation pipeline for a model. Your task is to create a function that applies the specified data transfo...
```python def apply_augmentation(transform_data, tta_mapper, batch_size): # Apply the specified data transformations using the provided parameters augmented_images = [] # Assuming `dataset_dict` is the dataset dictionary containing images and other relevant information augmented_dataset_dicts = tta...
magicoder
python
You are tasked with implementing a function that checks whether a given string contains a valid HTML closing tag. A valid closing tag must start with "</" followed by a tag name and end with ">". The tag name should consist of only lowercase letters and may contain hyphens. Additionally, the tag name should match the o...
```python def is_valid_closing_tag(tag: str, opening_tag: str) -> bool: if tag[:2] != "</" or tag[-1] != ">": return False closing_tag_name = tag[2:-1] opening_tag_name = opening_tag[1:-1] return closing_tag_name == opening_tag_name ```
magicoder
python
You are tasked with implementing a validation system for a scheduling application. The application allows users to define scheduling rules using a cron expression, and depending on the type of trigger selected, additional validation rules need to be applied. Your task is to create a validation system that enforces the...
To solve this problem, you can extend the validation system by adding rules for the cron expression and the repeat count based on the provided conditions and dependencies. Here's a possible solution in TypeScript: ```typescript class ValidatorsFactory { static required(errorMessage: string) { return (value...
magicoder
typescript
You are tasked with implementing a plugin system for a web server application. The server has the ability to load plugins, and each plugin can define its own routes for handling various requests. The code snippet provided shows the process of creating routes for different components of the server, such as user manageme...
To solve this problem, you can implement a plugin system using a combination of dynamic module loading and a defined interface for route registration. Here's a high-level solution outline: 1. Plugin Loading: - Implement a mechanism for dynamically loading plugins into the server. This can be achieved using a modula...
magicoder
python
You are working on a script to set up symbolic links for various configuration files in a user's home directory. The script should create symbolic links for the `.clang-format`, `.gdbinit`, `.gitconfig`, and `.bashrc` files from a specified directory (`$DIR`) to the user's home directory. If a symbolic link already exi...
```bash #!/bin/bash # Check if the directory argument is provided if [ -z "$1" ]; then echo "Usage: $0 <directory>" exit 1 fi DIR=$1 # Remove existing symbolic links and create new ones rm -f ~/.clang-format ln -s "$DIR/.clang-format" ~/.clang-format rm -f ~/.gdbinit ln -s "$DIR/.gdbinit" ~/.gdbinit rm -f ...
magicoder
shell
You are tasked with implementing a function that simulates the behavior of a selection mechanism in a software application. The function should take in an array of items and a boolean flag indicating whether the selection should be toggled or set to a specific state. The function should then update the selection state ...
```typescript function updateSelection(items: any[], toggle: boolean): any[] { if (toggle) { // Toggle the selection state of all items return items.map(item => !item.selected); } else { // Set the selection state of all items to the opposite of the current state return items.map...
magicoder
typescript
You are working on a project that involves processing and exporting layers from a PSD (Photoshop Document) file. The code snippet provided is a part of a shell script that performs some operations related to exporting layers from a PSD file using a tool called `psd-exporter`. The script echoes the results of a test, ex...
```python import subprocess import os import hashlib # Define the paths and filenames psd_file = "data/test.psd" output_dir = "my_layers" layout_dir = "test" format_string = "my_image_%04u.bmp" output_xlayermap = "my.xlayermap" # Invoke psd-exporter to export layers from the PSD file subprocess.run(["psd-exporter", p...
magicoder
python
You are tasked with creating a Python program that manages a list of people's names. The program should allow users to add, remove, and display the names in the list. Additionally, it should provide the functionality to search for a specific name in the list. Your task is to implement the following functions: 1. `add...
```python import argparse class PeopleManager: def __init__(self): self.people = [] def add_person(self, name): self.people.append(name) def remove_person(self, name): if name in self.people: self.people.remove(name) else: print(f"{name} not found i...
magicoder
python
You are tasked with implementing a shader system for a 3D game engine. The provided code snippet is a part of a method that iterates through a list of pairs, where each pair consists of a building and a corresponding 3D model. The method sets shader inputs for each model based on the properties of the associated buildi...
```python class ShaderSystem: def __init__(self, pairs): self.pairs = pairs def calculate_final_colors(self): alpha = 0.5 # Constant blending factor for pair in self.pairs: building = pair[0] np = pair[1] resource_color = RESOURCES[building.resourc...
magicoder
python
You are tasked with implementing a simple key-value store in Python using a dictionary. The key-value store should support setting default values for keys that have not been explicitly set. Your task is to create a class `KeyValueStore` with the following requirements: 1. The class should have a class variable `DEFAUL...
```python class KeyValueStore: DEFAULTS = {} @classmethod def set_default(cls, key, value): cls.DEFAULTS[key] = value def __init__(self): self.store = {} def get(self, key): return self.store.get(key, self.DEFAULTS.get(key)) def set(self, key, value): self.sto...
magicoder
python
You are tasked with implementing a function that processes an input image according to a series of conditions. The function takes an image as input and performs the following operations: 1. If the image has more than 3 channels, only the first 3 channels are retained. 2. If a scaling factor other than 1.0 is provided,...
```python import numpy as np import cv2 from typing import Tuple def process_image(image: np.ndarray, scale: Tuple[float, float]) -> np.ndarray: # If we have too many channels, only show 3 of them if len(image.shape) > 2 and image.shape[2] > 3: image = image[:, :, 0:3] if scale != (1.0, 1.0): ...
magicoder
python
You are tasked with implementing a custom routing system for a web application framework. The provided code snippet is a part of a Python web framework and defines a class `StaticFiles` that handles static file serving. The `get` method of this class is responsible for serving static files based on the provided URL par...
```python from some_module import get_current_registry # Assuming the required function is imported from a module class StaticFiles(Resource): def get(self, **kwargs): req_registry = get_current_registry() if not kwargs: file_path = "index.html" else: keys = sorted...
magicoder
python
You are tasked with implementing a Python function that performs matrix multiplication using a custom linear operator. The linear operator is defined by a given set of weights and a domain, and the matrix multiplication involves a set of input vectors and corresponding coefficients. The function takes in the following...
```python import numpy as np from scipy.sparse.linalg import LinearOperator def custom_matrix_multiplication(domain, zipped, ys): d = len(domain) X = np.zeros(domain) for (w, ax), z in zip(zipped, ys): tmp = tuple([1 if k in ax else domain[k] for k in range(d)]) X += w * z.reshape(tmp) ...
magicoder
python
You are tasked with implementing a neural network layer using PyTorch. The layer involves several operations including matrix multiplication, transposition, activation functions, and softmax. Your goal is to write a Python function that takes an input tensor `x` and performs the necessary operations to produce an outpu...
```python import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class CustomLayer(nn.Module): def __init__(self, input_size, hidden_size): super(CustomLayer, self).__init__() self.W_s1 = nn.Parameter(torch.randn(hidden_size, input_size)) self...
magicoder
python
You are tasked with creating a script to automate the installation and setup of a Buildkite agent on a Linux system. The Buildkite agent is a small, reliable, and cross-platform build runner that makes it easy to run automated builds on your own infrastructure. Your script should perform the following tasks: 1. Update...
```bash #!/bin/bash # Update the package list sudo apt update # Install the screen utility sudo apt-get install screen -y # Set the Buildkite agent token TOKEN="<KEY>" # Download and execute the Buildkite agent installation script bash -c "curl -sL https://raw.githubusercontent.com/buildkite/agent/master/install.sh...
magicoder
shell
You are tasked with implementing a function that processes a list of app descriptors and performs various operations based on the type of each descriptor. The function should handle the addition of new native applications, check for the existence of native applications, and commit a specific action to a cauldron. You a...
```typescript class AppProcessor { private cauldron: Cauldron; constructor(cauldron: Cauldron) { this.cauldron = cauldron; } public async processAppDescriptors(appDescriptors: AnyAppDescriptor[]): Promise<void> { for (const descriptor of appDescriptors) { if (descriptor instanceof AppPlatformDesc...
magicoder
typescript
You are tasked with implementing a Python decorator that modifies the behavior of a given function. The decorator should wrap the output of the function in a fixed-width format before returning it. The fixed-width format should ensure that the output is limited to 80 characters per line. Your task is to complete the i...
```python class FixedWidthWriter: def __init__(self, text, width): self.text = text self.width = width def format_output(self): # Implement the logic to format the text to fit the specified width # Ensure that the output is limited to 80 characters per line # Return the ...
magicoder
python
You are tasked with creating a Python module that simulates a simple banking system. The module should include classes for a Bank, Account, and Transaction. The Bank class should be responsible for managing accounts and processing transactions, the Account class should represent a bank account with a balance and owner ...
```python class Account: def __init__(self, acc_number, owner_name, initial_balance=0): self.acc_number = acc_number self.owner_name = owner_name self.balance = initial_balance def deposit(self, amount): if amount > 0: self.balance += amount return f"Depo...
magicoder
python
You are tasked with implementing a function that checks if a given input is of a specific type. The function should take in two parameters: the input value and a type flag. If the type flag is set to true, the function should only check if the input is of the specified type. If the type flag is set to false, the functi...
```go import "reflect" func checkType(input interface{}, targetType reflect.Type, typeOnly bool) bool { inputType := reflect.TypeOf(input) if typeOnly { return inputType == targetType } else { return inputType.AssignableTo(targetType) } } ```
magicoder
go
You are tasked with implementing a generic class in TypeScript that represents a global object with a specific type for its properties. The class should allow adding, retrieving, and deleting properties, as well as providing a method to check if a property exists. You are given the following code snippet as a starting...
```typescript type GLobalObject<T = any> = Record<string, T> class TypedGlobalObject<T> { private globalObject: GLobalObject<T> = {}; addProperty(key: string, value: T): void { this.globalObject[key] = value; } getProperty(key: string): T | undefined { return this.globalObject[key]; } deleteProp...
magicoder
typescript
You are tasked with creating a Python script to automate the installation and initialization process of a Frappe application using the `frappe-bench` tool. The script should perform the following steps: 1. Install the `frappe-bench` package using `pip3`. 2. Check the successful installation of `frappe-bench` by displa...
```python import subprocess # Install frappe-bench package subprocess.run(['sudo', '-H', 'pip3', 'install', 'frappe-bench']) # Check installation success print("Testing frappe-bench installation...") subprocess.run(['bench', '--version']) # Initialize Frappe application init_command = ['bench', 'init', '--frappe-bra...
magicoder
python
You are working on a data acquisition system that communicates with a device using a custom protocol. The provided code snippet is a part of a Python class method that interacts with the device to read and process data. The method is responsible for sending a command to the device, reading the response, and then proces...
```python class DataAcquisitionSystem: def __init__(self, device): self.device = device def acquire_data(self, start, num): self.device.write("XMA? %d,%d" % (start, num)) # Send command to the device self.device.values_format = visa.double # Set the format of received values s...
magicoder
python
You are tasked with implementing a utility function for managing deep learning model state dictionaries. The function should handle three specific operations: building a model from a configuration, loading a state dictionary onto a model of the same size, and fixing the state dictionary of a model trained with differen...
```python import torch def manage_model_state_dict(operation: str, model, config=None, state_dict=None, dp_epsilon=None) -> None: if operation == "build_from_config": if config is None: raise ValueError("Configuration object is required for building the model.") model = build_model_from...
magicoder
python
You are tasked with implementing a Python function that processes a list of file paths and returns a dictionary containing the count of files with unique extensions. The function should ignore case sensitivity when comparing file extensions. The function signature is: ```python def count_unique_extensions(file_paths: ...
```python from typing import List, Dict import os def count_unique_extensions(file_paths: List[str]) -> Dict[str, int]: extension_counts = {} for file_path in file_paths: _, file_extension = os.path.splitext(file_path) file_extension = file_extension.lower() # Convert to lowercase for case-ins...
magicoder
python
You are tasked with implementing a function to calculate the total number of internal sectors in a given 2D grid. An internal sector is defined as a contiguous area of the grid that is completely surrounded by filled cells. The grid is represented as a 2D array of characters, where 'X' represents a filled cell and '.' ...
```python def countInternalSectors(grid): def is_internal_sector(i, j): if i <= 0 or j <= 0 or i >= len(grid) - 1 or j >= len(grid[0]) - 1: return False return grid[i-1][j] == 'X' and grid[i+1][j] == 'X' and grid[i][j-1] == 'X' and grid[i][j+1] == 'X' count = 0 for i in range(1,...
magicoder
python
You are tasked with creating a Swift data structure to manage migration callbacks for a software development kit (SDK). The SDK has various events and properties associated with it, and you need to design a suitable data structure to handle these callbacks. Your task is to create a Swift struct or class that can store...
```swift // Define the data structure for migration callbacks struct MigrationCallbackReady { let eventName: String let eventType: String let sdkVersion: String let selectedSDKReason: String let user: User // Assuming User is another data structure representing user information // Initialize th...
magicoder
swift
You are tasked with creating a script to automate the process of updating a GitHub repository. Your script should perform the following steps: 1. Print a message indicating that the GitHub repository is being updated. 2. Change the working directory to a subdirectory named "public". 3. Add all changes in the "public" d...
```bash #!/bin/bash echo -e "\033[0;32mUpdating GitHub repo.\033[0m" cd public || { echo "Error: 'public' directory not found"; exit 1; } git add . git commit -m "update site" git push --force origin HEAD:master ``` The provided bash script accomplishes the required steps to update the GitHub repository. It first p...
magicoder
shell
You are tasked with implementing a simple game using Rust. The game involves flags, game moves, kinds, and stats. You are provided with a code snippet that imports modules from the `game` crate. Your task is to create a function that processes game moves and updates the game state accordingly. You are given the follow...
```rust use crate::game::{Flag, Game, GameMove, Kind, Stat}; fn process_move(game: &mut Game, game_move: &GameMove) { match game_move.kind { Kind::Capture => { // Update game state to reflect the captured flag let captured_flag = &game_move.flag; game.capture_flag(captur...
magicoder
rust
You are tasked with implementing a class method that processes a video file and generates screenshots based on specified quantiles. Additionally, the method should support uploading the generated screenshots to an image hosting service and a PTP image hosting service, if specified. You are given a Python class method ...
```python import os import logging class VideoProcessor: def __init__(self, imguploader, ptpimguploader, mkvpath, resultdir, pipeline): self.imguploader = imguploader self.ptpimguploader = ptpimguploader self.mkvpath = mkvpath self.resultdir = resultdir self.pipeline = pipel...
magicoder
python
You are given a list of data points `X` and a reference distribution `reference_distribution`. Your task is to calculate the Mahalanobis distance for each data point in `X` with respect to the reference distribution. The Mahalanobis distance is a measure of the distance between a point and a distribution. It is a mult...
```python import numpy as np def calculate_mahalanobis_distance(X, reference_distribution): # Calculate the mean and covariance matrix of the reference distribution mean = np.mean(reference_distribution, axis=0) covariance_matrix = np.cov(np.array(reference_distribution).T) mahalanobis = [] for x ...
magicoder
python
You are tasked with implementing a function to prepare a log record header in a logging system. The function `prepare_lrh` takes in five parameters: `csn` (commit sequence number), `checkpoint_csn` (checkpoint commit sequence number), `tsn` (transaction sequence number), and `rec_type` (record type). The function is re...
```rust use crc32; #[derive(Debug)] struct LogRecordHeader { lsn: u64, tsn: u64, csn: u64, checkpoint_csn: u64, rec_type: RecType, crc32: u32, } #[derive(Debug)] enum RecType { // Define record types here } impl LogRecordHeader { fn new() -> LogRecordHeader { LogRecordHeader {...
magicoder
rust
You are tasked with creating a Python script to process a given text using the spaCy library. Your script should perform the following tasks: 1. Install the necessary dependencies using conda and pip. 2. Download the English language model and the large English language model for spaCy. 3. Execute a bash script to down...
```python import subprocess # Install pathlib using conda subprocess.run(["conda", "install", "--yes", "pathlib"]) # Install spacy using conda-forge channel subprocess.run(["conda", "install", "-c", "conda-forge", "spacy"]) # Download the English language model for spaCy subprocess.run(["python", "-m", "spacy", "dow...
magicoder
python
You are working on a project that involves processing a series of satellite images using Google Earth Engine (GEE). The code snippet provided is a part of the image processing pipeline. Your task is to complete the pipeline by implementing the missing functionality for exporting the processed images to Google Drive. Y...
```python export_list = [] coeff_list = [] for i in range(NO_OF_IMAGES): iInfo = S3.get(i).getInfo() iInfoProps = iInfo['properties'] atmVars = atm_corr_image(iInfoProps) corrCoeffs = get_corr_coef(iInfoProps, atmVars) coeff_list.append(corrCoeffs) # Process the images and store them in exp...
magicoder
python
You are tasked with creating a Python script to automate the process of cracking passwords using the Hashcat tool. Hashcat is a popular password cracking tool that uses the power of GPUs to crack passwords through brute force, rule-based, and dictionary attacks. Your script will need to interact with Hashcat, manage di...
```python import os HASHCAT_DIR = "C:\\hashcat-5.1.0" HASHCAT_EXE = "hashcat64.exe" LOG_FILE = "crack_log.txt" DICT_DIR = "./dicts" def load_dict_list(): for r, d, f in os.walk(DICT_DIR): return f def parse_log(): result = {} with open(LOG_FILE, "r") as f: for line in f.readlines(): ...
magicoder
python
You are tasked with creating a class that represents a website user's visit history. The class should track the time of the user's last visit and provide methods to update and retrieve this information. You are provided with a code snippet that includes a private member variable `$timeLastVisit` of type `DateTime`. Yo...
```php class UserVisitHistory { /** * @var DateTime */ private DateTime $timeLastVisit; public function __construct() { $this->timeLastVisit = new DateTime(); // Initialize with current date and time } public function updateLastVisit(DateTime $newVisitTime) { $this->timeL...
magicoder
php
You are tasked with creating a command-line interface for a chatbot. The chatbot has a set of predefined commands stored in a dictionary called `cmds`. The code snippet provided is a part of the command processing logic. The snippet is written in Python and uses the `html` module for escaping HTML characters. The snip...
```python # Define the initial set of commands cmds = { '.start': 'Start the chatbot', '.help': 'List all the commands', '.info': 'Display chatbot information' } # Asynchronous function to handle user messages async def handle_message(message): command_prefix = '.' # Define the command prefix if m...
magicoder
python
You are tasked with creating a script to automate the execution of a series of commands for processing network packet capture files using a program called "asterix". The script should update tests by running the "asterix" program with various options and input files, and then redirect the output to specific files. The...
```bash #!/bin/bash exec="../../obj/main/release/asterix" config="../config/asterix.ini" output_dir="../sample_output" echo Updating tests $exec -d $config -L > "$output_dir/filter.txt" $exec -d $config -P -j -f ../sample_data/cat_062_065.pcap > "$output_dir/cat_062_065_json.txt" $exec -d $config -R -j -f ../sample_...
magicoder
shell
You are tasked with creating a reinforcement learning algorithm to train an agent to navigate a grid environment. The environment is represented by a grid with `nx` cells, and the agent can move between cells by taking actions. The agent's policy is represented by a function `policy(s)` that takes the current state `s`...
```python import numpy as np def train_agent(env, policy, x2d): # Initialize Q-table with zeros Q = np.zeros((env.nx, len(env.actions))) # Set hyperparameters alpha = 0.1 # Learning rate gamma = 0.9 # Discount factor epsilon = 0.1 # Epsilon-greedy exploration parameter # Train the agen...
magicoder
python
You are tasked with implementing a Python function that performs encryption using a given cipher algorithm. The function should handle different encryption modes and initialization vectors (IVs) based on the input parameters. The function should encrypt a given message using the provided key and return the resulting ci...
```python def encrypt_message(message, key, mode_no, iv=None): try: if iv is not None: cipher_text = cipher.encrypt(message, key, mode_no, iv) else: cipher_text = cipher.encrypt(message, key, mode_no) except TypeError: cipher_text = cipher.encrypt(message, key) ...
magicoder
python
You are tasked with implementing a function that processes a series of protocol buffer messages. The function should handle the merging of sub-messages and building partial messages based on the given code snippet. The code snippet provided is a part of a larger program that processes protocol buffer messages. It show...
```java public void processProtocolBufferMessage(MyProtocolBufferMessage inputMessage) { // Implementing the processProtocolBufferMessage function switch (inputMessage.getTagNumber()) { case 73: { com.google.protobuf.StringValue.Builder subBuilder = null; if (phoneNumberVerificat...
magicoder
java
You are tasked with implementing a note-taking application using Python. Your goal is to create a class `NoteRepository` that allows users to create and manage notes within different notebooks. The `NoteRepository` class should have a static method `create` that enables users to create a new note within a specified not...
```python import uuid class NoteRepository: notes = {} @staticmethod def create(user, notebook_id, title, content): """ Create a new note """ note_id = str(uuid.uuid4()) new_note = { 'user': user, 'notebook_id': notebook_id, 'title': title, ...
magicoder
python
You are tasked with understanding and optimizing a build process for a software project. The build process is currently using a combination of CMake and Ninja to compile and install the software. Your goal is to identify potential improvements to the build process and suggest modifications to the given code snippet. T...
The given code snippet is a part of a build script that uses CMake to configure the project and then uses Ninja to build and install the project. The snippet includes options passed to CMake and the subsequent use of Ninja to build and install the project. To optimize the build process, the following improvements can ...
magicoder
shell
You are tasked with implementing a simplified version of the Fragment management system in an Android application. The application has a main activity that can display different fragments based on user interactions. The code snippet provided is a part of the logic responsible for managing the display of the "Settings" ...
```java import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; public class FragmentManager { private FragmentManager fragmentManager; public FragmentManager(FragmentManager fragmentManager) { this.fragmentManager = fragmentManager; } public void add...
magicoder
java
You are tasked with creating a Python function that simulates a data preprocessing pipeline for a machine learning project. The pipeline consists of several steps, including loading data, dropping redundant columns, reshaping the data, encoding categorical columns, and performing data sampling. Additionally, the code s...
```python import pandas as pd from sklearn.preprocessing import LabelEncoder from imblearn.over_sampling import SMOTE def load_data(): # Placeholder for loading data from a source # Returns train_data and test_data pass def drop_redundant(df): # Placeholder for dropping redundant columns from the Data...
magicoder
python
You are tasked with creating a program to manage a custom voice model for a speech synthesis service. The custom voice model contains words and their translations, and it has a limit of 20,000 entries. Your program should allow users to update the metadata of the voice model, including the name, description, and the wo...
```python class CustomVoiceModel: def __init__(self, model_id, metadata, word_translations): self.model_id = model_id self.metadata = metadata self.word_translations = word_translations def update_model(self, new_metadata, new_word_translations): # Update metadata self.m...
magicoder
python
You are tasked with creating a program that analyzes a given source code file to count the occurrences of specific license-related comments. In this problem, you are to focus on counting the occurrences of the phrases "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE" and "GNU General Public License" within the comm...
```python def count_license_comments(source_code: str) -> int: lines = source_code.split('\n') count = 0 in_comment = False for line in lines: if line.startswith('##'): if "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE" in line: count += 1 if "GNU G...
magicoder
python
You are tasked with implementing a function that calculates the total area of a series of rectangles on a 2D plane. Each rectangle is represented by its top-left and bottom-right coordinates. The total area is the sum of the individual areas of the rectangles, excluding any overlapping regions. You need to write a fun...
```typescript function calculateTotalArea(rectangles: Array<[number, number, number, number]>): number { let totalArea = 0; const areaMap: Map<string, number> = new Map(); for (const rect of rectangles) { const [x1, y1, x2, y2] = rect; for (let i = x1; i < x2; i++) { for (let j ...
magicoder
typescript
You are tasked with implementing a function to calculate the MD5 hash of a given input string. The MD5 (Message Digest Algorithm 5) is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. The hash is typically represented as a 32-character hexadecimal number. The function should take ...
```swift import Foundation import CommonCrypto func calculateMD5(_ input: String) -> String { guard let data = input.data(using: .utf8) else { return "" } var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in _ ...
magicoder
swift
You are tasked with creating a custom control in WPF (Windows Presentation Foundation) that displays a list of items in a specific format. The control should be named `CustomListBox` and should inherit from the `ListBox` class. The `CustomListBox` should have the following features: 1. Each item in the list should be d...
```csharp using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace CustomControls { public class CustomListBox : ListBox { public CustomListBox() { // Set the ItemTemplate to a custom DataTemplate FrameworkElementFactory panelFactory = n...
magicoder
csharp
You are tasked with implementing a clustering algorithm using the ROCK (RObust Clustering using linKs) method. The ROCK algorithm is a density-based clustering algorithm that can identify clusters of arbitrary shapes and sizes in a dataset. The algorithm is implemented using the following code snippet: ```python sampl...
```python from sklearn.cluster import DBSCAN import numpy as np class rock: def __init__(self, radius, cluster_numbers, threshold, ccore): self.radius = radius self.cluster_numbers = cluster_numbers self.threshold = threshold self.ccore = ccore def process(self, sample): ...
magicoder
python
You are tasked with implementing a function to encode two ASCII digits into a single Unicode character. The function should take two ASCII digits as input and return the corresponding Unicode character after performing a specific calculation. You are given the following code snippet as a starting point: ```cpp namespa...
```cpp #include <optional> namespace { struct CBC_HighLevelEncoder { static bool isDigit(wchar_t c) { return c >= L'0' && c <= L'9'; } }; std::optional<wchar_t> EncodeASCIIDigits(wchar_t digit1, wchar_t digit2) { if (!CBC_HighLevelEncoder::isDigit(digit1) || !CBC_HighLevelEncoder::isDigit(digit2)) { ...
magicoder
cpp
You are tasked with implementing a Python function that builds a nearest neighbor search tree based on the dimensionality of the input data. The function should create a KDTree for low-dimensional data (3 or fewer dimensions) and a BallTree for high-dimensional data (more than 3 dimensions). The choice of distance metr...
```python import numpy as np from sklearn.neighbors import KDTree, BallTree def build_tree(x): """Builds a nearest neighbor search tree based on the dimensionality of the input data.""" if x.shape[1] <= 3: metric = 'euclidean' else: metric = 'minkowski' # 'chebyshev' tree = BallTree(...
magicoder
python
You are tasked with implementing a custom window procedure for a property page in a Windows application. The custom window procedure should handle specific messages and perform appropriate actions based on the message type. You are given the following code snippet as a starting point: ```cpp return CPropertyPage::Wind...
```cpp LRESULT CALLBACK CustomWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: // Perform initialization tasks when the window is created // ... break; case WM_COMMAND: // Handle commands from contr...
magicoder
cpp
You are tasked with implementing a function to calculate the Discrete Cosine Transform (DCT) of a given image using the Fast Fourier Transform (FFT) library. The input image is represented as a 2D array of real numbers, and the DCT is to be computed along both dimensions. The code snippet provided is a part of a larger...
```cpp #include <vector> #include <fftw3.h> std::vector<std::vector<double>> calculateDCT(const std::vector<std::vector<double>>& inputImage, int width, int height) { // Initialize FFTW plans and arrays fftw_plan plan; int n = width * height; double* in = (double*) fftw_malloc(sizeof(double) * n); ...
magicoder
cpp
You are given a 6x6 grid representing a chessboard. Each cell of the grid is denoted by its row and column indices, both ranging from 0 to 5. The grid is represented as a 2D array with 6 rows and 6 columns. Your task is to write a function that, given the row and column indices of a cell on the chessboard, returns the...
```python def knight_moves(row, col): possible_moves = 0 moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)] for move in moves: new_row = row + move[0] new_col = col + move[1] if 0 <= new_row < 6 and 0 <= new_col < 6: possible_moves += 1 ...
magicoder
python
You are tasked with creating a script to automate the process of assigning roles to users in a web application's authentication system. The script will interact with the authentication server's API using the `curl` command and process the JSON responses using `jq`. Your task is to complete the script by adding the nec...
```bash # Assign role to user role_assignment_response=$(curl --location --request POST "http://localhost:8180/auth/admin/realms/project_a/users/$id/role-mappings/realm" \ --header "Authorization: Bearer $access_token" \ --header "Content-Type: application/json" \ --data '{ "realm": "project_a", "userId": "'"$id"'"...
magicoder
shell
You are tasked with implementing a function that parses and processes SVG icon data to extract specific information. The SVG icon data is represented as a React component, and the function should extract the display name and the number of paths in the icon. Write a function `parseSVGIcon` that takes the SVG icon data ...
```javascript function parseSVGIcon(svgIconData) { const { displayName, props } = svgIconData; const pathCount = props.children[0].props.children.length; return { displayName, pathCount }; } // Test the function with the provided SVG icon data const svgIconData = { type: 'svg', props: { children: [ ...
magicoder
javascript
You are tasked with implementing a custom asynchronous file reader in C#. Your task is to create a class `CustomFileReader` that provides a method `ReadFileAsync` to read the contents of a file asynchronously and return the content as a string. The `CustomFileReader` class should utilize the `System.IO` namespace for f...
```csharp using System; using System.IO; using System.Text; using System.Threading.Tasks; public class CustomFileReader { public async Task<string> ReadFileAsync(string filePath) { try { using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShar...
magicoder
csharp
You are tasked with implementing a user management system for a web application. The system should allow for the creation, retrieval, updating, and deletion of user records. The user records should include fields for the user's name, email, and role. Additionally, the system should enforce the following role-based acce...
```python def get_users(): # Assume this function retrieves the list of user records from the database # and returns it as a list of dictionaries pass def get_user(user_id): users = get_users() for user in users: if user['id'] == user_id: return user raise ValueError("User n...
magicoder
python
You are tasked with implementing a class that manages the initialization and closing of Kafka consumer instances for processing messages from different topic partitions. The class should provide methods for initializing the consumer and closing the consumer connection. The `Initialize` method should return a dictionary...
```csharp using Confluent.Kafka; using System; using System.Collections.Generic; public class KafkaConsumerManager : IKafkaConsumerManager { private readonly ConsumerConfig _consumerConfig; private IConsumer<Ignore, string> _consumer; public KafkaConsumerManager(ConsumerConfig consumerConfig) { ...
magicoder
csharp
You are tasked with creating a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number, and the program should support multiple accounts. Your task is to implement the `Bank`...
```python from typing import Dict, Union import click class Bank: def __init__(self): self.accounts: Dict[int, Dict[str, Union[str, float]]] = {} def create_account(self, name: str, initial_balance: float) -> int: account_number = len(self.accounts) + 1 self.accounts[account_number] = ...
magicoder
python
You are tasked with implementing a function that constructs a child realm map based on the given component declaration. A child realm map is a data structure that maps child monikers to their respective realms. Each realm is associated with a child component and contains information about the component's execution envi...
```rust use std::collections::HashMap; use std::sync::Arc; struct ChildMoniker { name: String, // Other fields and methods as needed } struct ComponentDecl { children: Vec<ChildComponent>, // Other fields and methods as needed } struct ChildComponent { name: String, url: String, startup: ...
magicoder
rust
You are tasked with creating a word cloud generator using Python. A word cloud is a visual representation of text data, where the size of each word indicates its frequency or importance within the text. Your task is to implement a function that takes a string of text as input and generates a word cloud based on the fre...
```python from wordcloud import WordCloud import matplotlib.pyplot as plt from PIL import Image import numpy as np def create_wordcloud(text, image_path=None): # Generate word cloud wordcloud = WordCloud(width=800, height=400, background_color='white', max_words=200, colormap='viridis').generate(text) ...
magicoder
python
You are tasked with implementing a function to manipulate the visibility of a view in an Android application. The function should take in an integer array representing the visibility states of multiple views and return the number of views that are set to `ViewStates.Gone`. The function signature is: ```java public int...
```java public int countGoneViews(int[] visibilityStates) { int count = 0; for (int state : visibilityStates) { if (state == ViewStates.Gone.ordinal()) { count++; } } return count; } ``` The `countGoneViews` function iterates through the input array of visibility states and ...
magicoder
java
You are tasked with creating a simple CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) image generator using PHP. Your task is to write a PHP script that generates a random 6-character alphanumeric string, places it on a JPEG image, and then displays the image as a CAPTCHA. Your PHP...
```php <?php session_start(); $captchanumber = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz'; $captchanumber = substr(str_shuffle($captchanumber), 0, 6); $_SESSION["code"] = $captchanumber; $path = base_url().'img/1.jpg'; // Assuming base_url() returns the base URL of the website $image = imagecre...
magicoder
php
You are tasked with creating a script that will organize and execute a series of startup scripts based on specific criteria. The startup scripts are named in a specific format: `start_<name>.sh`. Your script should be able to identify and execute these startup scripts based on the following rules: 1. If the script name...
```python from typing import List def execute_startup_scripts(script_names: List[str]) -> List[str]: executed_scripts = set() result = [] for script in script_names: if script.startswith("start_") or script.endswith(".sh") or "unum" in script: if script not in executed_scripts: ...
magicoder
python
You are tasked with implementing a function that converts an integer to a string without using any built-in conversion functions or libraries. Your function should take an integer as input and return a string representation of that integer. You should not use any external libraries or functions that directly convert in...
```c #include <stdio.h> #include <stdlib.h> char* intToString(int num) { int temp = num; int count = 0; while (temp != 0) { temp /= 10; count++; } char* result = (char*)malloc((count + 1) * sizeof(char)); if (result == NULL) { return NULL; // Memory allocation failed ...
magicoder
c
You are given a list of tuples, where each tuple represents a test case for a license plate validation system. Each tuple contains the following elements: 1. A string representing a license plate number. 2. An integer representing the expected result of the validation test. 3. A tuple of tuples, where each inner tuple ...
```python def validate_license_plate(test_cases): def calculate_average_confidence(substring, confidence_scores): total_score = sum(confidence_scores) average_score = total_score / len(confidence_scores) if len(confidence_scores) > 0 else 0 return average_score def is_valid_license_plat...
magicoder
python
You are working on a project that involves linear algebra computations using Python's NumPy library. As part of this project, you need to create a function that performs a specific matrix operation. The operation involves replacing a specific column of a given matrix with a given vector and then calculating the determi...
```python import numpy as np def replace_column_and_calculate_det(matrix, column_index, vector): # Create a copy of the original matrix to avoid modifying the input matrix modified_matrix = np.copy(matrix) # Replace the specified column with the given vector modified_matrix[:, column_index] = vect...
magicoder
python
You are tasked with implementing a simple caching mechanism for an Apollo Client in a web application. The provided code snippet includes a function `getClient` that is responsible for retrieving the Apollo Client instance from the window object using a predefined key `APOLLO_KEY`. Your task is to extend this code to i...
```typescript import { ApolloClient } from "apollo-client"; const APOLLO_KEY = "__lwcapolloc_client__"; export function getClient(): ApolloClient | undefined { return getCachedClient() || (window as any)[APOLLO_KEY]; } export function setClient(client: ApolloClient): void { (window as any)[APOLLO_KEY] = clie...
magicoder
typescript
You are tasked with implementing a class that manages the configuration and staging of sandbox environments for a software deployment system. The class should provide methods for configuring a node, performing a preflight check, generating a unique key, configuring a sandbox, and staging the configured sandbox. You ne...
```python class DeploymentManager: def __init__(self): self.unique_key = None def configure(self, node): # Configure the node for deployment # Implementation details here pass def preflight(self): # Perform preflight checks # Implementation details here ...
magicoder
python
You are given a singly linked list and a positive integer `k`. Your task is to rotate the linked list to the right by `k` places. This means that the last `k` nodes of the linked list will be moved to the front, and the rest of the elements will move to the right. For example, if the linked list is `1 -> 2 -> 3 -> 4 -...
```python class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def Display(head): current = head while current: print(current.value, end=" -> ") current = current.next print("None") def RotateLinkedList(head, k): if not head or...
magicoder
python
You are tasked with implementing a function that converts a given number of seconds into a human-readable format. The function should take an integer value representing the number of seconds and return a string with the humanized value. The humanized value should be in the form of weeks, days, hours, minutes, and secon...
```python def describe_seconds(value: int) -> str: weeks = value // 604800 value %= 604800 days = value // 86400 value %= 86400 hours = value // 3600 value %= 3600 minutes = value // 60 seconds = value % 60 time_units = [ (weeks, "week"), (days, "day"), (hour...
magicoder
python
You are tasked with creating a Python class that simulates a smart home device adapter for controlling various smart home devices. The adapter class should be able to register new devices and provide a method to control these devices. You are provided with a code snippet that shows a dictionary `moes_adapters` contain...
```python class SmartHomeAdapter: def __init__(self): self.devices = {} def register_device(self, device_name, device_class): self.devices[device_name] = device_class def control_device(self, device_name, command): if device_name in self.devices: device = self.devices[d...
magicoder
python
You are tasked with developing a program to analyze a given text and extract specific information from it. The text contains a series of rules and guidelines for a system called CONTA. Each rule is numbered and followed by a statement. Your program needs to extract the rule numbers and the corresponding statements from...
```python def extract_rules(text): rules = [] lines = text.split("<br/>") # Split the text into lines for line in lines: parts = line.split(".") # Split each line by the period to extract the rule number if len(parts) > 1: rule_number = int(parts[0]) # Extract the rule number ...
magicoder
python
You are tasked with creating a Rust program that processes images using the `imagefmt` crate and accepts command-line arguments using the `docopt` crate. Your program should read an input image file, convert it to grayscale, and save the grayscale image to a specified output file. Your program should accept the follow...
```rust extern crate imagefmt; extern crate docopt; extern crate rustc_serialize; use docopt::Docopt; use imagefmt::{ColFmt, ColType}; static USAGE: &str = " Usage: grayscale_converter --input <input_file> --output <output_file> grayscale_converter (-h | --help) Options: -h, --help Show this help...
magicoder
rust
You are tasked with creating a Python function that processes data from multiple files and generates a summary report. The function should read data from a set of files, perform calculations, and produce a report based on the processed data. You are given a code snippet that iterates through unique run IDs and reads d...
```python import os import pandas as pd def generate_summary_report(dash, wd, f_suffix): summary_report = {} for run_id in dash['run_id'].unique(): file_path = f"{wd}/jules_run/{run_id}/namelists/output/{run_id}{f_suffix}" if os.path.exists(file_path): print(f"Reading {run_id}") ...
magicoder
python
You are tasked with implementing a priority queue data structure in C++. The priority queue should support the following operations: 1. `del_pdq`: Delete the highest priority element from the priority queue. 2. `snd_pdq`: Insert an element into the priority queue with a specified priority. 3. `psnd_pdq`: Insert an ele...
```cpp #include <iostream> #include <queue> #include <unordered_map> // Define a structure to hold the element and its priority struct Element { int value; int priority; }; // Custom comparator for the priority queue struct Compare { bool operator()(const Element& e1, const Element& e2) { return e...
magicoder
cpp
You are given a list `head_medica` containing a single string element. The string consists of comma-separated medical class codes, where each code is in the format "Class-{number}-{code}". The number and code are separated by a hyphen. The task is to write a function `count_medical_codes` to count the occurrences of ea...
```python def count_medical_codes(head_medica: list) -> dict: codes = head_medica[0].split(',') code_count = {} for code in codes: code = code.split('-')[-1] if code in code_count: code_count[code] += 1 else: code_count[code] = 1 return code_count ```
magicoder
python
You are working as a DevOps engineer for a company managing a large number of virtual machines (VMs) in a vSphere environment. Your task is to automate the process of powering on VMs that are currently in a powered-off state using Ansible. You have been provided with a JSON file, `vmfact.json`, containing information ...
```bash # Extract UUIDs of powered-off VMs and store in poweredOff.txt jq '.virtual_machines' vmfact.json | grep poweredOff | awk -F: '{print $2}' | sed -n 's/^.*"\(.*\)".*$/\1/p' > poweredOff.txt # Count the number of powered-off VMs p=$(wc -l poweredOff.txt | awk '{ print $1 }') # Check if there are more than one V...
magicoder
shell
You are working on a project that involves computing tree decompositions for a graph-based model. The code snippet provided is part of a test suite for the tree decomposition computation module. The `tree_decomp` is computed using the `compute_tree_decomposition()` method of `td_comp`, and then it is asserted that the ...
```python class Graph: def __init__(self, vertices, edges): self.vertices = vertices self.edges = edges class TreeDecomposition: def __init__(self, bags, width): self.bags = bags self.width = width def is_valid_tree_decomposition(graph, tree_decomposition): # Check if every...
magicoder
python
You are tasked with creating a Java program that manages the scheduling of appointments for a medical clinic. The program should utilize the Java Time API for handling date and time operations, and it should integrate with the Spring Framework for dependency injection and transaction management. Your task is to implem...
```java import java.time.*; import java.util.*; import org.springframework.context.annotation.*; import org.springframework.transaction.annotation.*; @Component public class AppointmentScheduler { private Map<Integer, Appointment> appointments = new HashMap<>(); private int nextAppointmentId = 1; @Transa...
magicoder
java
You are tasked with creating a script to automate the deployment of a software application. The script should handle the copying of the application executable to a parent directory based on certain conditions. Your script should check if a directory named "Release" exists. If it does, the script should copy the file "...
```bash #!/bin/bash if [ -d "Release" ]; then cp Release/Tsuka.exe .. else cp Tsuka* .. fi ``` The script first checks if the "Release" directory exists using the conditional statement `if [ -d "Release" ]`. If the directory exists, it copies the file "Tsuka.exe" from the "Release" directory to the parent dir...
magicoder
shell
You are tasked with implementing a hash map data structure with a remove method. The hash map is represented as a linear probing hash table, and the remove method should take a hash value and a closure to determine equality. The closure will be used to compare keys and values in the hash map. Your task is to implement...
```rust impl<K, V> HashMap<K, V> { pub fn remove(&mut self, hash: u64, mut eq: impl FnMut((&K, &V)) -> bool) -> Option<(K, V)> { unsafe { for pos in self.probe_mod(hash) { let group = Group::load(self.mod_ctrl(pos)); for bit in group.match_byte(h2(hash)) { ...
magicoder
rust
You are tasked with creating a Python class that simulates a simple 1D wave propagation using the Clawpack library. The code snippet provided is a part of a larger program that sets up the solver for the simulation. Your task is to complete the implementation of the simulation class by adding methods to initialize the ...
```python import pyclaw class WaveSimulation: def __init__(self, solver_type): if solver_type == 'claw': self.solver = pyclaw.ClawSolver1D() elif solver_type == 'sharpclaw': self.solver = pyclaw.SharpClawSolver1D() else: raise Exception('Unrecognized valu...
magicoder
python
You are tasked with creating a Bash script that processes a given directory and its subdirectories to find all files with a specific file extension. Your script should then calculate the total size of all these files and print the result in a human-readable format. Your Bash script should accept two command-line argum...
```bash #!/bin/bash # Check if the correct number of arguments are provided if [ "$#" -ne 2 ]; then echo "Usage: $0 <directory_path> <file_extension>" exit 1 fi # Assign command-line arguments to variables directory_path="$1" file_extension="$2" # Find all files with the specified extension and calculate the...
magicoder
shell
You are tasked with creating a Python function that processes a given text file and extracts the license information from it. The text file contains a software license agreement in the form of comments, similar to the code snippet provided. Your function should read the file, extract the license information, and return...
```python def extract_license_info(file_path: str) -> str: with open(file_path, 'r') as file: lines = file.readlines() license_info = '' for line in lines: if line.strip().startswith('#'): license_info += line.replace('#', '').strip() + ' ' else: ...
magicoder
python
You are tasked with implementing a Java program to process a collection of words and count the frequency of each word. Your program should read a text file containing words separated by spaces and output the count of each unique word in the file. Additionally, the program should ignore punctuation and be case-insensiti...
```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class WordFrequencyCounter { public static void main(String[] args) { String fileName = "input.txt"; // Replace with the actual file name Map<String, ...
magicoder
java
You are working on a Python project for managing data related to livestock farming. The project has a package named `ganaderia` which contains several modules for different aspects of livestock management. The given code snippet is from a file named `__init__.py` within the `ganaderia` package. It is importing three mo...
```python from typing import List import importlib import inspect def get_all_classes(package_name: str) -> List[str]: imported_modules = [module for module in dir(importlib.import_module(package_name)) if not module.startswith('__')] classes = [] for module_name in imported_modules: module = impor...
magicoder
python
You are tasked with implementing a function that creates and runs a set of subprocesses based on a given configuration. The configuration specifies the details of the subprocesses to be created and run. Each subprocess is expected to perform a specific task based on the configuration provided. You are given the follow...
```python import subprocess def create_and_run(subs, config): for sub in subs: command = config[sub]['command'] args = config[sub]['args'] env = config[sub]['env'] subprocess.Popen([command] + args, env=env) ``` In the solution, the `create_and_run` function iterates throug...
magicoder
python
You are tasked with creating a Python class that generates a graph using the Kivy library. The class should have a method called `build` which initializes and returns a Kivy layout containing a graph with a sinusoidal plot. Your task is to complete the `build` method by creating the necessary Kivy widgets and adding a...
```python from kivy.uix.boxlayout import BoxLayout from kivy.garden.graph import Graph, MeshLinePlot from kivy.uix.label import Label from math import sin class GraphBuilder: def build(self): b = BoxLayout(orientation='vertical') graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5, ...
magicoder
python
You are tasked with creating a Java program that processes a given source code to extract specific model content declarations. The program should utilize regular expressions to identify and extract the model content declarations from the source code. You are provided with a code snippet that includes the declaration o...
```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class ModelContentExtractor { private String declareModelContent; private JavaClassSource source; private static final String CHECK_FIELD_REGEX = "(DataSinkBuilder|ProcessingElementBuilder)\\.create\\((.*?),(.*?)\\)"; priva...
magicoder
java
You are tasked with implementing a blockchain data structure in Python. A blockchain consists of a series of blocks, each containing a list of transactions and a reference to the previous block. Each block also has a hash size and a challenge level associated with it. The hash size represents the size of the hash used ...
```python import hashlib class Block: def __init__(self, prev_block, transaction): self.prev_block = prev_block self.transaction = transaction self.hash_size = self.__get_hashSize() self.challenge_level = self.__get_challengeLevel() def __get_hashSize(self): # Calculate...
magicoder
python
You are tasked with creating a script to automate the process of uploading files to Dropbox using a custom uploader script. The script should create a specific subfolder in Dropbox and then upload files to that subfolder. You are given a code snippet that partially demonstrates this process. The code snippet provided ...
```bash #!/bin/bash # Download the dropbox_uploader.sh script curl -Os "https://raw.githubusercontent.com/andreafabrizi/Dropbox-Uploader/master/dropbox_uploader.sh" chmod +x dropbox_uploader.sh # Define the uploader command uploader="./dropbox_uploader.sh" # Create subfolders in Dropbox and upload files for subfolde...
magicoder
shell
You are tasked with implementing a synchronous wrapper for asynchronous methods in C#. The goal is to create a method that can call an asynchronous method and return its result synchronously. You need to ensure that the synchronous wrapper does not block the calling thread and handles any exceptions thrown by the async...
```csharp using System; using System.Globalization; using System.Threading; using System.Threading.Tasks; public static class AsyncHelper { private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Defa...
magicoder
csharp