query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are given a function `searchWordIndex(sentence: str, searchWord: str) -> int` that takes in a sentence and a search word as input and returns the index of the first occurrence of the search word in the sentence. The function uses the Knuth-Morris-Pratt (KMP) algorithm to efficiently search for the word within the s... | ```python
def searchWordIndex(sentence: str, searchWord: str) -> int:
if sentence.startswith(searchWord):
return 0
p = KMP(sentence, ' ' + searchWord)
if p == -1:
return -1
return p - 1
def KMP(text, pattern):
lps = computeLPSArray(pattern)
i, j = 0, 0
while i < len(text):
... | magicoder | python |
You are tasked with creating a Python class that generates fake data using the `faker` library and then uses the `factory` library to create instances of a custom class. The custom class should represent a product with attributes such as name, price, and category. Your task is to implement the `ProductFactory` class th... | ```python
from uuid import UUID
import factory
from faker import Factory as FakerFactory
class Product:
def __init__(self, name, price, category):
self.name = name
self.price = price
self.category = category
class ProductFactory:
def __init__(self):
self.fake = FakerFactory.cre... | magicoder | python |
You are working on a Python web application that interacts with an external API to retrieve data about different entities. The application uses a custom session object to make HTTP requests and handle responses. The session object has a method called `get_entity` that is used to retrieve information about a specific en... | ```python
class Entity:
def __init__(self, session, tags):
self._session = session
self.tags = tags
def get_site(self, callback=None):
"""
Retrieve an instance of the site this entity is linked to.
:param callback: Optional callback function to handle the retrieved site ... | magicoder | python |
You are tasked with implementing a custom exception handling mechanism in Python. The given code snippet provides a glimpse of the operations involved in this mechanism. The operations include `vstack`, `bstack`, `raise`, `CustomException`, and `handle`. Your task is to understand and implement a custom exception handl... | ```python
from typing import List, Union
class CustomException(Exception):
def __init__(self, message):
self.message = message
def custom_exception_handler(operations: List[str]) -> Union[str, None]:
stack = []
for operation in operations:
if operation.startswith("CustomException"):
... | magicoder | python |
You are tasked with implementing a job scheduling system for web scraping and email notifications. Your goal is to create a class that manages web scraping jobs and sends email notifications based on a specified interval. You are provided with a partial code snippet for the `LbcJob` class, which represents a job for sc... | ```python
import time
import threading
import scrapper
import email_sender
class LbcJob:
def __init__(self, name, url, interval, recipients):
self.name = name
self.url = url
self.scrapper = scrapper.LbcScrapper(url)
self.interval = interval
self.recipients = recipients
... | magicoder | python |
You are working on a deployment automation script for a cloud infrastructure using Juju, a cloud orchestration tool. Your script is responsible for deploying a bundle configuration defined in a `bundle.yaml` file and ensuring that the `/etc/hosts` file on the target machines is updated with the IP and hostname of each ... | ```python
def generate_hosts_update_command(juju_node_ip, juju_node_hostname, juju_deploy_machine):
return f'juju ssh {juju_deploy_machine} "sudo bash -c \'echo {juju_node_ip} {juju_node_hostname} >> /etc/hosts\'" 2>/dev/null'
# Test the function
print(generate_hosts_update_command("10.0.0.5", "node-1", "machine-1... | magicoder | python |
You are tasked with implementing a function that processes a given JavaScript module and extracts specific information from it. The module represents a payment wizard module invoice action view and contains various properties and methods related to invoice actions. Your goal is to extract and return the name of the exp... | ```javascript
function extractModuleName(codeSnippet) {
// Remove leading and trailing whitespace, semicolon, and 'export =' from the code snippet
const moduleName = codeSnippet.trim().replace(/export\s*=\s*/, '');
return moduleName;
}
``` | magicoder | javascript |
You are tasked with implementing a function that converts a given object into a data representation. The function should handle various types of input, including custom data objects, strings, dictionaries, and iterable objects. Your task is to write the `asdata` function according to the following specifications:
Func... | ```python
class Data:
def __init__(self, data):
self.data = data
def asdata(self, asdata_func):
return asdata_func(self.data, asdata_func)
def asdata(obj, asdata_func):
if isinstance(obj, Data):
return obj.asdata(asdata_func)
elif isinstance(obj, str):
return obj
el... | magicoder | python |
You are working on a city-building simulation game, and you need to implement a function to calculate the total time required for workers to build a specific improvement in the game. The game has various build options, each with its own time requirement, and the total time is affected by game speed and era.
You are gi... | ```python
def calculate_total_build_time(improvement_id: int, game_speed_type: str, start_era: str) -> int:
total_build_time = 0
worker_work_rate = gc.getUnitInfo(gc.getInfoTypeForString('UNIT_WORKER')).getWorkRate()
for iBuild in xrange(gc.getNumBuildInfos()):
BuildInfo = gc.getBuildInfo(iBuild)
... | magicoder | python |
You are tasked with creating a function that processes a given string containing PHP code and extracts all the function calls present in the code. A function call is considered to be any occurrence of a string followed by parentheses, such as `functionName()` or `functionName($arg1, $arg2)`.
Write a function `extractF... | ```php
function extractFunctionCalls($phpCode) {
$pattern = '/(?<!\/\*.*)(?<!\/\/.*)\b\w+\s*\([^)]*\);/';
preg_match_all($pattern, $phpCode, $matches);
return $matches[0];
}
```
The `extractFunctionCalls` function uses a regular expression pattern to match function calls in the given PHP code. The pattern ... | magicoder | php |
You are tasked with implementing a class method in Python that simulates the movement of an object in a 2D space. The method should take in various parameters to define the behavior of the object. The class definition is provided below:
```python
import pygame
from pygame.math import Vector2 as Vec2d
class ObjectMove... | ```python
import math
class ObjectMovement:
# ... (same as in the problem description)
def move_object(self, dt: float):
if self.func == "linear":
# Calculate linear movement
displacement = dt * self.time # Calculate displacement based on speed and time
self.pos +=... | magicoder | python |
You are tasked with implementing a custom PyTorch module called `MeanOfEmbeddings` that calculates the mean of word embeddings for a given input sequence. The `MeanOfEmbeddings` module takes in two parameters: `vocab_size` (the size of the vocabulary) and `emb_dim` (the dimension of the word embeddings). It utilizes th... | ```python
class MeanOfEmbeddings(nn.Module):
def __init__(self, vocab_size, emb_dim):
super().__init__()
self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
def forward(self, x):
# Obtain word embeddings for the input indices
embedded_x = self.emb(x)
# M... | magicoder | python |
You are tasked with implementing a text processing pipeline for a live streaming application. The pipeline will tokenize incoming text data using a specified tokenizer and perform additional processing within a given time constraint. Your task is to design and implement a Python class that encapsulates this text proces... | ```python
import time
import gin
import docker
class TextProcessingPipeline:
def __init__(self, processing_time, tokenizer_path, is_live_stream, is_docker):
self.processing_time = processing_time
self.tokenizer_path = tokenizer_path
self.is_live_stream = is_live_stream
self.is_docke... | magicoder | python |
You are tasked with creating a Python class that simulates a simple countdown timer. The class should utilize threading to run the countdown in the background. Your task is to implement the `CountdownTimer` class with the following specifications:
- The class should have a constructor that takes an integer `seconds` a... | ```python
import threading
import time
class CountdownTimer:
def __init__(self, seconds):
self.seconds = seconds
self._t = threading.Thread(target=self._run_timer)
def _run_timer(self):
while self.seconds > 0:
print(f"Time remaining: {self.seconds} seconds")
tim... | magicoder | python |
You are tasked with creating a Python class that interfaces with Google's Speech-to-Text (STT) service for real-time speech recognition. The class should handle streaming audio data and provide a method for processing the recognized text. Your task is to implement the missing methods in the given class template to achi... | ```python
import rospy
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
class SpeechToText:
def __init__(self, language_code='en-US'):
self.language_code = language_code
self.client = speech.SpeechClient()
self.closed = False
d... | magicoder | python |
You are working for a data science team that is developing a machine learning model for predicting user behavior on an e-commerce platform. The team has been using Python and various libraries for data manipulation and model training. Your task is to create a function that preprocesses and trains a LightGBM model using... | ```python
import pandas as pd
import lightgbm as lgb
from feat_names import names_lgb_20190624_1 as feats
@register(out=m_20190624, inp=[t_tr_te_classify, f_top30, f_si_sim, f_m2_top30, f_m3_top30])
def train_predict_lgb_20190624_1():
# Load data
t_tr_te_classify_data = load_data('t_tr_te_classify')
f_top3... | magicoder | python |
You are tasked with implementing a Python package for geophysical calculations. The package, named "ggtools," contains a subpackage with functions for fitting linear functions and estimating Load Love Numbers (LLNs). Your goal is to create a class that utilizes these functions to perform specific calculations.
Create ... | ```python
import ggtools.ggssubpackage as subpkg
class GeophysicalCalculator:
def __init__(self, a0, a1):
self.a0 = a0
self.a1 = a1
def fit_linear_function(self, T, x):
# Define a linear function f(x) = a0 + a1/T*x to be fitted
fitted_function = subpkg.func(x, self.a0, self.a1,... | magicoder | python |
You are tasked with creating a Swift function that generates a view model for a route detail screen in a navigation app. The function should take an `ActivityDetailConfig` object as input and return a `RouteDetailViewModelTypes` object. The `ActivityDetailConfig` object contains information about the route, such as dis... | ```swift
// Define the protocol for RouteDetailViewModelTypes
protocol RouteDetailViewModelTypes {
var distance: Double { get }
var estimatedTime: TimeInterval { get }
var waypoints: [Waypoint] { get }
// Add other properties and methods as needed
}
// Define the Waypoint struct
struct Waypoint {
l... | magicoder | swift |
You are tasked with implementing a class hierarchy for managing network controllers in a macOS application. The provided code snippet is a part of a Swift class definition for a network controller management system. Your task is to complete the implementation of the `Controller_CanariDefaultNetClassPopUpButton` class, ... | ```swift
class Controller_CanariDefaultNetClassPopUpButton: NSPopUpButton {
private var mController: NetworkController?
// Method to bind the network classes to the pop-up button
func bind_netClasses() {
self.mController = NetworkController()
self.mController?.register()
// Addition... | magicoder | swift |
You are tasked with creating a PHP function that processes a given HTML code and extracts all the classes used in the `div` elements. The function should return an array of unique class names found in the HTML code.
Create a PHP function `extractClasses` that takes a string representing the HTML code as its parameter ... | ```php
function extractClasses($html) {
$classes = array();
$dom = new DOMDocument();
$dom->loadHTML($html);
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
$classAttr = $div->getAttribute('class');
if (!empty($classAttr)) {
$classNames = explode... | magicoder | php |
You are tasked with implementing a registration form for a web application using Angular. The form should include fields for the user to input their name, email, password, and confirm password. Additionally, the form should have validation to ensure that the email is in the correct format, the password meets certain cr... | ```typescript
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './registration-form.component.html',
styleUrls: ['./registration-form.component.css']
})
export class RegistrationFor... | magicoder | typescript |
You are tasked with implementing a Japanese text processing system that involves applying various filters to manipulate and analyze Japanese text data. One of the key components of this system is the implementation of different filters to process the text. Each filter is responsible for performing specific operations o... | ```java
// Base class for Japanese text filters
abstract class JapaneseTextFilter {
abstract String applyFilter(String inputText);
}
// Filter for manipulating numeric elements in Japanese text
class JapaneseNumericFilter extends JapaneseTextFilter {
@Override
String applyFilter(String inputText) {
... | magicoder | java |
You are tasked with implementing 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. The program should also be able t... | ```python
class Account:
next_account_number = 1
def __init__(self):
self.account_number = Account.next_account_number
Account.next_account_number += 1
self.balance = 0
def deposit(self, amount):
if amount > 0:
self.balance += amount
else:
pr... | magicoder | python |
You are tasked with creating a Python function that processes user data from a database and performs specific transformations on the gender and age columns. The function should take a database connection object `conn` as input and return the modified user data as a pandas DataFrame.
The function should perform the fol... | ```python
import pandas as pd
def process_user_data(conn):
# Retrieve user data from the database
cur = conn.cursor()
users = pd.read_sql("select * from User", conn)
# Filter the user data to include specific columns
users = users.filter(regex='UserID|Gender|Age|JobID')
# Convert gend... | magicoder | python |
You are given a text file containing a list of names and their corresponding scores. Each line in the file represents a name followed by a score, separated by a space. The scores are in the range of 0 to 100. Your task is to write a program that reads this file and prints the names and scores with the top three highest... | ```python
# Read the file and store the names and scores in a dictionary
scores = {}
with open('scores.txt', 'r') as file:
for line in file:
name, score = line.strip().split()
scores[name] = int(score)
# Sort the dictionary by scores in descending order
sorted_scores = sorted(scores.items(), key=la... | magicoder | python |
You are tasked with creating a Rust program that reads a configuration file, parses its contents, and then executes a specific action based on the parsed data. The configuration file is expected to be provided as a command-line argument when running the program. The program should handle potential errors gracefully and... | ```rust
use std::env;
use std::fs;
use serde::Deserialize;
struct Cfg {
file_path: String,
}
impl Cfg {
fn new(file_path: String) -> Cfg {
Cfg { file_path }
}
fn parse(&self) -> Result<ParsedData, String> {
let file_content = match fs::read_to_string(&self.file_path) {
Ok(... | magicoder | rust |
You are tasked with implementing a function that evaluates a given mathematical function at a set of specified points. The function takes in an array of evaluation points and returns a 3D array containing the results of the evaluation for each sample at each evaluation point.
You are given the following function signa... | ```python
import numpy as np
def evaluate_function(eval_points: np.ndarray) -> np.ndarray:
"""
Evaluate a mathematical function at specified points.
Args:
eval_points (numpy.ndarray): Numpy array with shape
``(number_eval_points, dim_domain)`` with the
evaluation points.
... | magicoder | python |
You are given a mathematical problem to solve. Given a positive integer `a`, you need to find the highest possible value of `x` such that `2na ≡ x (mod a^2)`, where `n` is a non-negative integer.
Write a function `highest_x_mod_a_squared(a)` that takes in a positive integer `a` and returns the highest possible value o... | ```python
def highest_x_mod_a_squared(a):
if a % 2 == 1:
return a**2 - 1
else:
return a**2 - 2
```
The solution defines a function `highest_x_mod_a_squared` that takes a positive integer `a` as input. If `a` is odd, the function returns `a^2 - 1` as the highest possible value of `x`. If `a` is ... | magicoder | python |
You are tasked with implementing a cost function optimization problem using the Pymanopt library in Python. Pymanopt is a Python toolbox for optimization on manifolds, which provides a high-level interface for optimization algorithms. In this problem, you will be using the Steepest Descent solver to minimize the cost f... | ```python
import autograd.numpy as np
from pymanopt import Problem
from pymanopt.solvers import SteepestDescent
def optimize_cost_function(manifold, initial_guess):
# Define the cost function
def cost(X):
return np.sum(X)
# Instantiate a Pymanopt problem
problem = Problem(manifold=manifold, co... | magicoder | python |
You are tasked with implementing a custom learning rate scheduler for a deep learning model training process. The learning rate scheduler is based on the "One Cycle Policy" proposed by Leslie N. Smith in his paper "Cyclical Learning Rates for Training Neural Networks". The provided code snippet is a part of the initial... | ```python
import math
class CustomOneCycleLR:
def __init__(self,
optimizer,
first_cycle_steps,
cycle_mult=1.0,
max_lr=0.1,
min_lr=0.001,
warmup_steps=0,
gamma=1.0,
last_epoch=-1
... | magicoder | python |
You are tasked with creating a program to simulate the process of randomly splitting a dataset into two subsets based on a given probability threshold. The program should take a dataset as input and randomly assign each record to one of the two subsets based on the probability threshold. Additionally, the program shoul... | ```python
import pandas as pd
import numpy as np
def random_split_and_count(dataset, column, threshold):
np.random.seed(2018)
mask = np.random.rand(len(dataset)) < threshold
subset_1 = dataset[mask]
subset_2 = dataset[~mask]
counts_subset_1 = subset_1[column].value_counts().to_dict()
counts_su... | magicoder | python |
You are tasked with implementing a custom exception class in C++ that can handle variable arguments for message formatting. Your goal is to create a class that allows the user to pass a formatted message string along with variable arguments, similar to the behavior of the `printf` function in C. The class should be abl... | ```cpp
#include <stdio.h>
#include <stdarg.h>
#include <stdexcept>
#include <string>
class opp_runtime_error : public std::runtime_error {
public:
opp_runtime_error(const char *messagefmt, ...) : std::runtime_error("") {
va_list args;
va_start(args, messagefmt);
char buffer[256]; // Assumi... | magicoder | cpp |
You are tasked with creating a Python function that simulates a simplified version of a card game. The game involves a deck of cards, and the function should perform the following actions:
1. Initialize the deck of cards: Create a list representing a standard deck of playing cards. Each card should be represented as a... | ```python
import random
def simulate_card_game(num_cards):
values = [str(i) for i in range(2, 11)] + ['J', 'Q', 'K', 'A']
suits = ['H', 'D', 'C', 'S']
deck = [value + '-' + suit for value in values for suit in suits]
random.shuffle(deck)
return deck[:num_cards]
# Test the function
print(simulate_c... | magicoder | python |
You are tasked with implementing a rule-based access control system using the provided Node class as a wrapper for the rules and associated key. The rules are represented as a list of tuples, where each tuple contains a condition and a permission. The condition is a function that takes a key as input and returns True o... | ```python
class Node:
def __init__(self, rules, key):
self.rules = rules
self.key = key
def check_access(self):
for condition, permission in self.rules:
if condition(self.key):
return permission
return "No access"
# Example usage
rules = [
(lambd... | magicoder | python |
You are tasked with implementing a custom iterator in Rust for a font data structure. The font data is represented by the `FontDataRef` type, and the custom iterator, `Fonts`, will iterate over the font data. The font data is stored in a sequential manner, and the iterator should provide access to the font data element... | ```rust
impl<'a> Iterator for Fonts<'a> {
type Item = u8;
fn next(&mut self) -> Option<Self::Item> {
if self.pos < self.data.len() {
let item = self.data[self.pos];
self.pos += 1;
Some(item)
} else {
None
}
}
}
impl<'a> ExactSizeItera... | magicoder | rust |
You are tasked with implementing a class that manages sampling and orientation of boxes in a 3D space. The provided code snippet initializes the box orientation, retrieves its extents, calculates the sample location, and sets the sample rate. Your task is to create a class `BoxManager` with appropriate member functions... | ```cpp
#include <vector>
enum Orientation { XY, XZ, YZ }; // Enum for box orientation
class BoxManager {
private:
bool _initialized;
double SampleRate;
std::vector<double> minExtents, maxExtents;
public:
BoxManager() : _initialized(false), SampleRate(0.0) {}
void initialize() {
if (_ini... | magicoder | cpp |
You are tasked with implementing a function that checks whether a given string represents a valid ISO 8601 duration. An ISO 8601 duration is a string that represents a time span, such as "P3Y6M4DT12H30M5S" for a duration of 3 years, 6 months, 4 days, 12 hours, 30 minutes, and 5 seconds.
You need to create a function `... | ```javascript
function isValidISO8601Duration(input) {
const durationRegex = /^P(\d+Y)?(\d+M)?(\d+D)?(T(\d+H)?(\d+M)?(\d+S)?)?$/;
return durationRegex.test(input);
}
```
The `isValidISO8601Duration` function uses a regular expression to match the input string against the rules of a valid ISO 8601 duration. The reg... | magicoder | javascript |
You are working on a data processing pipeline for single-cell RNA sequencing data. Your task is to implement a function that processes the output of a statistical analysis and updates the data structure accordingly. The function takes in the following parameters:
- `data`: a data structure containing single-cell RNA se... | ```python
def process_output(data, out, par):
try:
out.index = data.var.index
except ValueError as err:
if str(err) == "cannot specify integer `bins` when input data contains infinity":
err.args = ("Cannot specify integer `bins` when input data contains infinity. Perhaps input data h... | magicoder | python |
You are tasked with creating a Python function that processes proposals and generates feedback for each proposal. The function takes in an instance of a proposal and performs the following actions:
1. Prints a separator line consisting of 20 hyphens ('-').
2. Prints the details of the proposal instance.
3. Prints anoth... | ```python
class Proposal:
def __init__(self, name, details):
self.name = name
self.details = details
class ProposalStatus:
def __init__(self, proposal, reviewer, proposal_status):
self.proposal = proposal
self.reviewer = reviewer
self.proposal_status = proposal_status
c... | magicoder | python |
You are tasked with implementing a class that handles authentication in a Keycloak server. The provided code snippet initializes an `AdminAuth` object with authentication details and then uses it to create a `KeycloakAuthentication` object. Your task is to create the `AdminAuth` and `KeycloakAuthentication` classes wit... | ```java
// AdminAuth class for handling authentication details
public class AdminAuth {
private String realm;
private String token;
private String user;
private Client client;
public AdminAuth(String realm, String token, String user, Client client) {
this.realm = realm;
this.token =... | magicoder | java |
You are given a list of integers representing the daily stock prices of a company. Your task is to write a function to calculate the maximum profit that can be obtained by buying and selling the stock on different days. You can only make one transaction (i.e., buy one and sell one share of the stock), and you must buy ... | ```python
from typing import List
def maxProfit(prices: List[int]) -> int:
if not prices:
return 0
min_price = prices[0]
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_p... | magicoder | python |
You are tasked with implementing a custom signal processing mechanism in Swift. The `SignalProtocol` represents a stream of elements, and you need to extend this protocol with a method that allows pausing the propagation of elements until a specific condition is met.
You are to implement the `pause(when:)` method, whi... | ```swift
extension SignalProtocol {
func pause(when condition: @escaping () -> Bool) -> Signal<Self.Element> {
let signal = Signal<Self.Element> { observer in
var isPaused = false
let disposable = self.observe { event in
if !isPaused {
observer.sen... | magicoder | swift |
You are tasked with implementing a whitelist-based access control system for a web application. The system should allow or deny access to specific controller actions based on a predefined whitelist.
You are given a PHP code snippet that checks if a controller action is set in the request parameters and then initialize... | ```php
class AccessControl {
private $controller_action_whitelist;
public function __construct() {
$this->controller_action_whitelist = array();
}
public function addToWhitelist($action) {
$this->controller_action_whitelist[] = $action;
}
public function removeFromWhitelist($a... | magicoder | php |
You are tasked with implementing a program to find the maximum distance between two nodes in a binary tree. The binary tree is represented using the following Node class:
```csharp
public class Node
{
public int Value { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
```
You n... | ```csharp
public class BinaryTree
{
public int MaxDistanceBetweenNodes(Node root)
{
if (root == null)
return 0;
int[] result = new int[1];
MaxDepth(root, result);
return result[0];
}
private int MaxDepth(Node node, int[] result)
{
if (node == nul... | magicoder | csharp |
You are tasked with creating a program that parses a Cargo manifest file and extracts specific information from it. The Cargo manifest file is used in Rust projects to define metadata about the project, its dependencies, and other configuration details. The manifest file is typically named `Cargo.toml` and is written i... | ```rust
extern crate toml;
use std::fs;
use std::collections::BTreeMap;
#[derive(Debug, Deserialize)]
struct CargoManifest {
version: String,
description: String,
homepage: String,
license: String,
dependencies: BTreeMap<String, Dependency>,
features: BTreeMap<String, Vec<String>>,
}
#[derive... | magicoder | rust |
You are tasked with creating a Python class that manages exceptions and norms for a natural language processing library. The class should handle importing base exceptions and norms from different modules and languages, and provide methods to access and manipulate these linguistic resources.
Your task is to implement t... | ```python
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
class LanguageResources:
def __init__(self):
self.exceptions = {}
self.norms = {}
def import_exceptions(self, exception_names):
for name in exception_n... | magicoder | python |
You are tasked with implementing a custom smart pointer in Rust called `Undropped`. The `Undropped` smart pointer is designed to prevent an object from being dropped when it goes out of scope. This is particularly useful for objects created from standard descriptors, such as files.
The `Undropped` smart pointer is def... | ```rust
use std::fs::File;
use std::os::unix::io::FromRawFd;
#[derive(Debug)]
pub struct Undropped<T>(Option<T>);
impl<T> Undropped<T> {
// Create a new Undropped smart pointer containing the provided object
pub fn new(obj: T) -> Undropped<T> {
Undropped(Some(obj))
}
// Consume the Undropped ... | magicoder | rust |
You are tasked with creating a program that processes a CSV file containing video annotations and extracts specific information from it. The CSV file contains the following columns: 'VideoID', 'Start', 'End', 'WorkerID', 'Source', 'AnnotationTime', and additional columns. The program should read the CSV file, process t... | ```python
import csv
import spacy
from collections import defaultdict
nlp = spacy.load('en')
# Read the CSV file and store the data
data = defaultdict(list)
with open('video_annotations.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
for key, value in row.items():
data... | magicoder | python |
You are tasked with implementing a function to extract a specific portion of WebAssembly (Wasm) module data from a debugging handler. The provided code snippet is part of a larger system for debugging Wasm modules and interacting with a GDB server.
Your task is to complete the implementation of the `GetWasmModuleBytes... | ```cpp
class WasmModuleDebug {
public:
uint32_t GetWasmData(Isolate* isolate, uint32_t offset, uint8_t* buffer, size_t size) {
// Implementation details not provided
}
};
class GdbServer {
public:
uint32_t GetWasmModuleBytes(wasm_addr_t wasm_addr, uint8_t* buffer, size_t size) {
WasmModuleDebug* module_d... | magicoder | cpp |
You are working on a quantum computing library and need to implement a method for converting quantum gates to basic gates. A quantum gate is a fundamental operation in quantum computing, and it can be represented as a unitary matrix. However, not all gates are basic; some can be decomposed into a sequence of basic gate... | ```python
from typing import List, Optional
import numpy as np
class Gate:
def __init__(self, name: str, matrix: np.ndarray, target: int, control: Optional[int] = None):
self.name = name # Name of the gate
self.matrix = matrix # Unitary matrix representing the gate
self.target = target #... | magicoder | python |
You are tasked with creating a script to automate the configuration of monitors based on specific conditions. The script should handle the scenario where the primary monitor is not the built-in display (LVDS-1 or eDP1) and should turn off the built-in display, identify the primary and secondary monitors, and then set t... | ```bash
#!/bin/bash
PRIMARY="LVDS-1" # Replace with the actual primary monitor identifier
SECONDARY="HDMI-1" # Replace with the actual secondary monitor identifier
# Check if the primary monitor is not the built-in display
if [[ "$PRIMARY" != "LVDS-1" ]] && [[ "$PRIMARY" != "eDP1" ]]; then
# Turn off built-in d... | magicoder | shell |
You are tasked with implementing a Python function that processes a given configuration dictionary to create and manipulate data loaders for a data generation task. The function should handle the creation of a temporary directory, saving an array to a file within that directory, and updating the configuration dictionar... | ```python
import os
import numpy as np
from tempfile import TemporaryDirectory
from copy import deepcopy
class DataLoader:
def __init__(self, path, loader):
self.path = path
self.loader = loader
class DataGenerator:
def __init__(self, **kwargs):
# Implementation not provided for DataGe... | magicoder | python |
You are tasked with creating a program that analyzes a given software license text to extract and display the warranty information contained within it. The warranty information includes the types of warranties provided and any limitations or disclaimers associated with them.
Write a function `extract_warranty_info` th... | ```python
def extract_warranty_info(license_text: str) -> dict:
warranty_info = {}
lines = license_text.split('\n')
warranty_type = None
warranty_text = ''
for line in lines:
if line.isupper() and ':' in line:
if warranty_type:
warranty_info[warranty_type] = warr... | magicoder | python |
You are tasked with implementing a class for managing a collection of items in a game inventory system. The class should support adding, removing, and inspecting items. Additionally, it should provide a method for toggling the inspection mode for a specific item.
You are given a partial code snippet for the inventory ... | ```java
public class InventoryManager {
private List<Item> items;
private ItemIconScript referenceToOriginalIcon;
private bool inspectionON;
private GameObject inspectionPoolManager;
public InventoryManager(GameObject inspectionPoolManager) {
this.inspectionPoolManager = inspectionPoolManag... | magicoder | java |
You are given a positive integer `num`. Your task is to write a function that determines whether `num` is an ugly number. An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Write a function `isUgly(num)` that takes in a positive integer `num` and returns `True` if `num` is an ugly num... | ```python
def isUgly(num):
if num <= 0:
return False # Negative numbers and zero are not considered ugly numbers
while num % 2 == 0:
num = num / 2
while num % 3 == 0:
num = num / 3
while num % 5 == 0:
num = num / 5
return num == 1 # If num becomes 1, it means al... | magicoder | python |
You are tasked with creating a program that parses and extracts information from API documentation comments. The comments follow a specific format, as shown in the code snippet below:
```java
/**
* This method retrieves user data.
* @apiSuccess {int} data.id User ID
* @apiSuccess {string} data.name User's name
* @... | ```java
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class APIDocumentationParser {
public static Map<String, Map<String, String>> extractAPISuccessInfo(String apiComments) {
Map<String, Map<String, String>> extractedInfo = new HashM... | magicoder | java |
You are tasked with implementing a generic repository pattern for a data access layer in a C# application. The repository pattern is a design pattern that abstracts the data access logic and provides a way to access data from the database. Your task is to create a generic repository interface and a concrete implementat... | ```csharp
// Define a generic repository interface
public interface IRepository<T>
{
T GetById(int id);
IEnumerable<T> GetAll();
void Add(T entity);
void Update(T entity);
void Delete(T entity);
// Add any additional methods required for data access
}
// Create a concrete implementation for the... | magicoder | csharp |
You are tasked with implementing a class to monitor web traffic and generate alerts when the traffic exceeds a certain threshold. Your task is to complete the implementation of the `TrafficMonitor` class, which has the following requirements:
The `TrafficMonitor` class should have the following attributes:
- `window`:... | ```python
from collections import deque
class TrafficMonitor:
def __init__(self, window_size, alert_threshold):
self.window = deque(maxlen=window_size)
self.hits_per_second = 0
self.alert_threshold = alert_threshold
self.alert = False
def add_hit(self, hits):
self.hits_... | magicoder | python |
You are tasked with implementing a simplified version of an asynchronous file upload manager in Swift. The manager is responsible for uploading files to an internal S3 storage system and handling the result of the upload operation.
You are provided with a partial code snippet that includes a method signature for the `... | ```swift
enum Operation {
case upload
case download
case delete
}
struct InternalS3ObjectDetails {
let fileName: String
let fileData: Data
// Other file details can be included here
}
class S3FileManager {
func uploadFile(operation: Operation, s3Object: InternalS3ObjectDetails, resultHandl... | magicoder | swift |
You are tasked with implementing a custom view layout for a mobile application. The layout consists of a series of items displayed in rows, with each row containing two items. The provided code snippet is a part of the implementation for this custom view layout. The code sets up the display of an item in a row view, po... | ```swift
if lastView == nil {
if line == 1 { // Right side
itemView.frame = CGRect(x: kScreenWidth/2, y: border, width: kScreenWidth/2, height: itemHeight)
} else { // Left side
itemView.frame = CGRect(x: 0, y: border, width: kScreenWidth/2, height: itemHeight)
}
} else {
let xPosition: ... | magicoder | swift |
You are tasked with creating a Python function to automate the process of generating authentication tokens for users in a Docker environment. The function will interact with a shell script `docker-manage-api.sh` to create tokens for specific users. The shell script takes two arguments: the action to perform and the use... | ```python
import subprocess
def generate_auth_token(username: str) -> str:
command = ['./docker-manage-api.sh', 'drf_create_token', username]
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, _ = process.communicate()
return output.decode('utf-8').strip()
```
... | magicoder | python |
You are tasked with implementing a class for estimating the performance of a machine learning model. The class, named `Estimator`, contains a method `GetCurrentIteration()` that returns the current iteration number during the estimation process. Additionally, there is a loop in the code snippet that iterates over a num... | ```cpp
class Estimator {
public:
int GetCurrentIteration() {
// Implementation of GetCurrentIteration() method
// Return the current iteration number
}
bool ValidateClasses() {
bool passed = true;
for (unsigned int i = 0; i < numberOfClasses; ++i) {
// Perform va... | magicoder | cpp |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should keep track of the account holder's name and account balance.
Your task is to implement the `BankAcc... | ```python
class BankAccount:
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.... | magicoder | python |
You are tasked with creating a program that validates user input for a specific format. The input should represent a "Node name" and must adhere to certain rules. The rules for the "Node name" are as follows:
- It can only contain the characters 0-9, a-z, A-Z, underscore (_), and hyphen (-).
- It cannot be empty.
Your... | ```python
import re
def validate_node_name(node_name):
pattern = r'^[0-9a-zA-Z_-]+$'
if re.match(pattern, node_name):
return "Valid Node name"
else:
return "Invalid Node name"
# Test cases
print(validate_node_name("my_Node-123")) # Output: Valid Node name
print(validate_node_name("invalid... | magicoder | python |
You are tasked with implementing a function to retrieve specific attributes of a field in a model. The model is represented by the `HorribleModel` class, and the attributes are accessed using the `get_value` function. The function takes the field name and a list containing attribute keys and their corresponding values ... | ```python
class HorribleModel:
class _meta:
fields = {
"user": {"max_length": 255},
"slug": {"unique": True, "other_attr": "some_value"}
}
def get_value(field_name, attribute_list):
field_attributes = HorribleModel._meta.fields.get(field_name, {})
if not field_a... | magicoder | python |
You are tasked with implementing a synchronization mechanism for a blockchain network. The code snippet provided is part of a unit test for this synchronization mechanism. The test is written in Swift using XCTest framework. The test is checking the synchronization process by verifying the latest downloaded block heigh... | ```swift
func synchronizeBlockchain(targetHeight: Int) -> Int {
var latestDownloadedHeight = 0
let reorgExpectation = XCTestExpectation(description: "Reorg notification received")
let secondSyncExpectation = XCTestExpectation(description: "Second sync notification received")
// Perform synchronization ... | magicoder | swift |
You are tasked with creating a notification system for a mobile application using Android's Notification API. The goal is to display a notification to the user when a certain event occurs in the application. You will need to create a class that encapsulates the logic for building and displaying the notification.
Your ... | ```java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class NotificationHelper {
public void showNotification(Context context, String... | magicoder | java |
You are tasked with creating a Python function that processes Git branch and tag names to generate a tag suffix based on certain conditions. The function should take three parameters: `branch` (string), `tag` (string), and `tag_regex` (regular expression object). The function should follow these rules to determine the ... | ```python
import re
def generate_tag_suffix(branch: str, tag: str, tag_regex: re.Pattern) -> str:
RE_DEVEL_BRANCH = re.compile(r'devel-\d+')
RE_MASTER_BRANCH = re.compile(r'master-\d+')
RE_FEATURE_BRANCH = re.compile(r'feature-\d+')
RE_BUGFIX_BRANCH = re.compile(r'bugfix-\d+')
RE_EXTRACT_BRANCH_AND... | magicoder | python |
You are working on a program that manages Pokémon data. The given code snippet is part of a function that initializes various Pokémon attributes based on their gender and abilities. The function takes three arrays `parent`, `only`, and `genderless`, each containing strings representing Pokémon names. The code snippet i... | ```python
from typing import List, Tuple
def initializePokemonAttributes(parent: List[str], only: List[str], genderless: List[str]) -> Tuple[List[str], List[str], List[str], List[str], List[str], List[str], List[str], List[str]]:
pre_Items = ["" for _ in range(2)]
post_Items = ["" for _ in range(2)]
abilit... | magicoder | python |
You are tasked with creating a Python class that simulates a simple bidding system for an auction. Your class should include functionality for adding bids, retrieving the highest bid, and displaying all bids. Additionally, you need to implement a method to calculate the average bid amount.
Your class should have the f... | ```python
from datetime import datetime
class AuctionBiddingSystem:
def __init__(self):
self.bids = []
def add_bid(self, user, bid_amount, bid_time):
self.bids.append((user, bid_amount, bid_time))
def get_highest_bid(self):
if not self.bids:
return None
highest... | magicoder | python |
You are tasked with creating a program that processes a list of race participants and their corresponding race times. The program should calculate and display the winner of the race based on the fastest time. Additionally, it should output the average race time for all participants.
You are given a code snippet from a... | ```python
# Read race data from file
with open('race_data.txt', 'r') as file:
race_data = [line.strip().split() for line in file]
# Calculate winner and average race time
winner_name = ''
winner_time = float('inf')
total_time = 0
num_participants = len(race_data)
for participant, time in race_data:
time = flo... | magicoder | python |
You are tasked with implementing a custom kernel density estimation (KDE) algorithm for a given dataset. Kernel density estimation is a non-parametric way to estimate the probability density function of a random variable. The algorithm uses a kernel function to smooth the data and estimate the probability density at di... | ```python
import numpy as np
from sklearn.neighbors import KernelDensity
class KernelDensityEstimator:
def __init__(self, kernel='gaussian', bandwidth=1.0):
self._kernel = kernel
self._bandwidth = bandwidth
self._estimators = []
def fit(self, X):
p = X.shape[1]
for feat... | magicoder | python |
You are tasked with creating a program that reads a text file and counts the occurrences of specific words within it. Your program should be able to handle large text files efficiently and accurately count the occurrences of each word.
Write a function `countWordOccurrences` that takes two parameters:
1. `file_path` (... | ```python
import re
def countWordOccurrences(file_path, words):
word_counts = {}
with open(file_path, 'r') as file:
text = file.read().lower() # Read the file and convert to lowercase
text = re.sub(r'[^\w\s]', '', text) # Remove punctuation marks
word_list = text.split() # Split the ... | magicoder | python |
You are tasked with implementing a GPS data publisher for a robotics system. The system is designed to publish GPS data using the ROS (Robot Operating System) framework. The provided code snippet is a part of a Python class method responsible for initializing the GPS publisher. The class has a private attribute `_topic... | ```python
def initialize_gps_publisher(self, node, qos_sensor_reliable):
if 'NavSatFix' in dir(std_msgs.msg):
self.__gps_publisher = node.create_publisher(
std_msgs.msg.NavSatFix, self._topic_name + '/gps', qos_sensor_reliable)
else:
self.__gps_publisher = node.create_publisher(
... | magicoder | python |
You are tasked with implementing a function to parse a string into a floating-point number, similar to the behavior of the standard C library function `strtod`. The function should handle various input cases, including positive and negative numbers, scientific notation, and invalid input.
You are given the following f... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
double my_strtod(const char* str, char** endptr) {
const char* p = str;
char* end = NULL;
double result = 0.0;
bool negative = false;
bool hasDigits = false;
// Skip leading whitespace
while (isspace(*p)) {... | magicoder | c |
You are tasked with implementing a simple command-line assembler for a custom assembly language. The assembler takes assembly code as input and produces machine code as output. The assembly language consists of instructions and labels. Instructions are represented by mnemonics, such as "MOV" for move, "ADD" for additio... | ```python
def assemble(assembly_code):
machine_code = []
label_map = {}
# First pass: Process labels and build label map
line_number = 0
for line in assembly_code:
if line.endswith(":"):
label = line[:-1]
label_map[label] = line_number
else:
line_... | magicoder | python |
You are tasked with implementing a Fraction struct in Rust that can perform basic arithmetic operations. The Fraction struct should support addition, subtraction, multiplication, and division of fractions. Each fraction should be represented by a numerator and a denominator, and the struct should also handle negative f... | ```rust
struct Fraction<T> {
numerator: T,
denominator: T,
is_negative: bool,
}
impl<T> Fraction<T>
where
T: std::ops::Mul<Output = T> + std::cmp::PartialOrd + std::ops::Neg<Output = T> + Copy,
{
fn new(numerator: T, denominator: T, is_negative: bool) -> Self {
Fraction {
numera... | magicoder | rust |
You are tasked with creating a Python class that manages datasets for object detection and segmentation tasks. The class should handle different configurations based on the task type and provide functionality for accessing dataset information and archives.
Your task is to implement the `DatasetManager` class, which sh... | ```python
class DatasetManager(BaseDatasetManager):
def __init__(self, root, task, skip_integrity_check=False):
self._anns_folder = "Annotations" if task == "detection" else "SegmentationClass"
self._split_folder = "Main" if task == "detection" else "Segmentation"
self._categories = _info()... | magicoder | python |
You are tasked with creating a Python program that processes a list of chapters from a book and retrieves information about each chapter from a web service. Your program should be able to handle both successful and unsuccessful requests and provide an option to hide successful requests.
Your program should have the fo... | ```python
import re
import requests
def main(chapters_list_filename, hide_success=True):
try:
with open(chapters_list_filename, 'r') as file:
chapters = file.readlines()
for chapter in chapters:
chapter = chapter.strip()
response = requests.get('http:... | magicoder | python |
You are tasked with creating a Python program to fetch cryptocurrency prices from an API and perform validation on the received data. You will need to implement a function to retrieve the price of a specific cryptocurrency in a specific fiat currency from a given URL. Additionally, you must ensure that the retrieved pr... | ```python
import aiohttp
import json
class CoinPrice:
def __init__(self, fiat, coin, rate):
self.fiat = fiat
self.coin = coin
self.rate = rate
class CoinyQueue:
async def put(self, request):
# Implementation not provided for this problem
class CoinySession:
async def __aen... | magicoder | python |
You are tasked with creating a web application that manages user sessions and authentication. Your task is to implement a PHP class that handles user sessions and provides methods for user authentication and logout.
You are provided with a code snippet from a web page that displays a navigation bar with a user dropdow... | ```php
<?php
class UserSession {
public function startSession() {
session_start();
}
public function authenticateUser($username, $password) {
// Replace this with your actual authentication logic
if ($username === "admin" && $password === "password") {
$_SESSION["nama"] ... | magicoder | php |
You are tasked with designing a protocol-oriented system for presenting items in a list and their details. The system should include protocols for presenting the list of items and for presenting the details of a specific item.
You are provided with a code snippet that defines two functions: `makeItemsPresentable` and ... | ```swift
// Define a protocol for presenting a list of items
protocol ItemsListPresentable {
associatedtype Item
func presentItems(items: [Item])
}
// Define a protocol for presenting the details of a specific item
protocol ItemDetailPresentable {
associatedtype Item
func presentItemDetail(item: Item)
... | magicoder | swift |
You are tasked with creating a Python function that takes a list of strings as input and returns a new list containing only the strings that are palindromes. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization... | ```python
def is_palindrome(s):
# Remove spaces and punctuation, convert to lowercase
s = ''.join(e for e in s if e.isalnum()).lower()
return s == s[::-1]
def find_palindromes(input_list):
palindromes = [word for word in input_list if is_palindrome(word)]
return palindromes
# Test the function wit... | magicoder | python |
You are tasked with creating a Python function that simulates a URL routing system similar to Django's URL dispatcher. The function should take a URL path and match it to a corresponding view function based on the defined URL patterns.
You are given the following code snippet as a reference for the URL patterns:
```py... | ```python
import re
from typing import List, Tuple, Callable, Optional
def resolve_view(url_path: str, urlpatterns: List[Tuple[str, Callable, str]]) -> Optional[str]:
for pattern, view, name in urlpatterns:
if re.match(pattern, url_path):
return name
return None
```
The `resolve_view` func... | magicoder | python |
You are tasked with implementing a modified version of the MinkUNetTwoStream architecture for a 3D semantic segmentation task. The architecture consists of several classes, each representing a different configuration of the network. The provided code snippet includes three classes: MinkUNetTwoStream14, MinkUNetTwoStrea... | ```python
def calculate_total_parameters(network_class: type) -> int:
# Extract the required attributes from the network class
BLOCK = network_class.BLOCK
LAYERS = network_class.LAYERS
PLANES = network_class.PLANES
# Calculate the total number of parameters
total_parameters = 0
in_planes = ... | magicoder | python |
You are tasked with implementing a key-stretching algorithm to enhance the security of password hashing. Key-stretching algorithms are designed to make brute-force attacks against password hashes more difficult by increasing the computational effort required to derive the original password from its hash.
Your task is ... | ```python
import bcrypt
def hash_password(password: str, salt: str, cost_factor: int) -> str:
# Generate the hashed password using jBCrypt algorithm with specified cost factor
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(cost=cost_factor, prefix=b"2a"))
return hashed.decode('utf-8')
```
... | magicoder | python |
You are tasked with creating a Rust program that utilizes the `glenum` crate and the `stdweb` crate to render a simple 2D shape on a web page. The `glenum` crate provides OpenGL enumeration bindings, while the `stdweb` crate enables Rust to interact with JavaScript in the web browser.
Your task is to create a Rust pro... | ```rust
extern crate glenum;
#[macro_use]
extern crate stdweb;
use stdweb::web::{document, IElement, IParentNode};
use stdweb::web::html_element::CanvasElement;
use stdweb::web::CanvasRenderingContext2d;
fn main() {
stdweb::initialize();
let canvas: CanvasElement = document().create_element("canvas").unwrap(... | magicoder | rust |
You are tasked with implementing a class for a neural network in Python using TensorFlow. The given code snippet is a part of the class constructor that initializes the weights and biases for the hidden layers of the neural network. The `self.hidden_layers` list contains the number of neurons in each hidden layer, and ... | The provided solution completes the implementation of the `NeuralNetwork` class by initializing the weights and biases for each hidden layer in the constructor and implementing the `forward_pass` method to perform the forward pass of the neural network using the initialized weights and biases. The constructor initializ... | magicoder | python |
You are tasked with creating a Python program to calculate the fuel efficiency of a car based on various input parameters. The program should take into account the bore, stroke, compression ratio, horsepower, peak RPM, city MPG, and highway MPG of the car. The fuel efficiency will be calculated using the following form... | ```python
def calculate_fuel_efficiency(bore, stroke, compression_ratio, horsepower, peak_rpm, city_mpg, highway_mpg):
fuel_efficiency = (2 * bore * stroke * compression_ratio * horsepower / peak_rpm) + (city_mpg + highway_mpg) / 2
return round(fuel_efficiency, 2)
# Test the function
bore = 3.5
stroke = 2.8
co... | magicoder | python |
You are tasked with implementing a Java method that processes a list of strings and returns the count of strings that contain a specific substring. The method signature is as follows:
```java
public class StringProcessor {
/**
* Counts the number of strings in the list that contain the specified substring.
... | ```java
public class StringProcessor {
/**
* Counts the number of strings in the list that contain the specified substring.
*
* @param strings the list of strings to process
* @param substring the substring to search for
* @return the count of strings containing the specified substring... | magicoder | java |
You are tasked with implementing a custom event system in Java. Your goal is to create a class that manages event handlers and allows other classes to register and handle events. The event system should support multiple event types and allow for the execution of event handlers when events are triggered.
You are provid... | ```java
// The completed Event class with the required functionality
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Event {
private static final Map<Class<? extends Event>, List<EventHandler<? extends Event>>> handlers = new HashMap<>();
publi... | magicoder | java |
You are tasked with creating a script to automate the build process for a software project across different operating systems and architectures. The script should be able to build the project for Windows operating system with three different architectures: amd64, 386, and arm. The build process should produce executabl... | ```bash
#!/bin/bash
os=windows
for arch in "amd64" "386" "arm"; do
GOEXE=.exe CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build -o build/nothing_windows_$arch.exe
done
```
The provided shell script sets the operating system to "windows" and then iterates through the architectures "amd64", "386", and "arm". For each ar... | magicoder | shell |
You are tasked with implementing a distributed machine learning algorithm for training a model on multiple machines. The given code snippet is a part of the algorithm, where each machine computes its local evaluation and updates its parameters based on a global parameter. Your task is to create a function that computes... | ```python
import numpy as np
def compute_eval_global(w_global, machines):
local_evals = np.array([machine.compute_eval(w_global) for machine in machines])
if local_evals.shape[0] == 1:
eval_global = local_evals[0]
else:
eval_global = np.mean(local_evals, axis=0)
return eval_gl... | magicoder | python |
You are tasked with creating a Python function that processes a list of database migration operations and extracts specific information from it. The list contains tuples, where each tuple represents a dependency between two database migrations, and a list of migration operations. Each migration operation is represented... | ```python
def extract_migration_info(dependencies, operations):
alter_field_info = {}
create_model_info = []
for operation in operations:
if isinstance(operation, migrations.AlterField):
alter_field_info['model_name'] = operation.model_name
alter_field_info['field_name'] = o... | magicoder | python |
You are tasked with creating a function that processes cryptocurrency token information and updates a view model accordingly. The function will take in the token's value, decimals, symbol, address, RPC server, and a session object. The function should format the token amount, set the title of the view model, retrieve t... | ```swift
func updateTokenInfo(token: Token, session: Session, assetDefinitionStore: AssetDefinitionStore) {
let amount = EtherNumberFormatter.short.string(from: token.valueBigInt, decimals: token.decimals)
let title = "\(amount) \(token.symbolInPluralForm(withAssetDefinitionStore: assetDefinitionStore))"
to... | magicoder | swift |
You are tasked with implementing a function to parse and extract specific attributes from a given SVG (Scalable Vector Graphics) code snippet. The SVG code snippet is represented as a string and contains attributes such as `stroke-linejoin`, `xmlns`, `height`, `viewBox`, `width`, and `path`. Your task is to create a fu... | ```python
import re
def parseSVGAttributes(svgCode: str) -> dict:
attributes = ["stroke-linejoin", "xmlns", "height", "viewBox", "width"]
attribute_values = {}
for attribute in attributes:
match = re.search(fr'{attribute}="([^"]+)"', svgCode)
if match:
attribute_values[attr... | magicoder | python |
You are tasked with implementing a function that interacts with both Ethereum and Cosmos blockchains. The function takes several parameters, including references to a web3 client, a gRPC client, a batch request mode, an Ethereum address, a Cosmos key, and a Cosmos fee. Your goal is to write the function that makes use ... | ```rust
async fn interact_with_blockchains(
web3: &Web3Client,
grpc_client: &mut GrpcClient,
batch_request_mode: BatchRequestMode,
ethereum_address: EthereumAddress,
cosmos_key: CosmosKey,
cosmos_fee: CosmosFee,
) -> Result<InteractResult, InteractError> {
// Perform actions on Ethereum bloc... | magicoder | rust |
You are tasked with creating a reinforcement learning agent to solve the Pendulum-v0 environment using the Proximal Policy Optimization (PPO) algorithm. The environment is set up to have 2 parallel instances (NUM_ENVS = 2) for training efficiency. The code snippet provided initializes the environment, sets the random s... | ```python
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import gym
from torch.distributions import Categorical
from touchstone.environments.make import make_vec_envs
# Define the PPO agent
class PPOAgent:
def __init__(self, state_dim, action_dim, hidden_dim=64, lr=3e-4, gamma=0.... | magicoder | python |
You are tasked with creating a class that manages different types of social media buttons and their corresponding actions. The class should handle the click events of these buttons and execute the appropriate actions based on the button type. You are given a code snippet that demonstrates the handling of SNS (Social Ne... | ```swift
// Define the SNSButton class hierarchy
@objc class SNSButton {}
@objc class InstagramButton: SNSButton {}
@objc class NaverMapButton: SNSButton {}
// Implement the SNSButtonManager class
class SNSButtonManager {
@objc func handleSNSButtons(_ sender: SNSButton) {
switch sender {
case is ... | magicoder | swift |
You are tasked with implementing a function to parse a specific binary format used for encoding data. The format uses variable-length encoding to represent integers. The provided code snippet is part of a larger function responsible for parsing a message in this format. Your task is to complete the implementation of th... | ```cpp
void ParseEncodedData(const uint8_t* buffer, size_t buffer_size) {
if (buffer_size == 0) {
// Handle error: buffer is empty
return;
}
const uint8_t* ptr = buffer;
uint64_t value = 0;
int shift = 0;
while (true) {
if (ptr >= buffer + buffer_size) {
// ... | magicoder | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.