query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a command-line utility that converts a CSV file to a JSON file. The utility should accept command-line arguments for the input CSV file path, the output JSON file path, and an optional flag to overwrite the output file if it already exists.
You are provided with a Python class `CsvToJs... | ```python
import csv
import json
import os
class CsvToJson:
def __init__(self):
self._csv_path = None
self._json_path = None
self._overwrite = False
def get_arguments(self):
super(CsvToJson, self).get_arguments()
if 'csv_path' in self._args:
self._csv_path ... | magicoder | python |
You are tasked with implementing a function to determine whether a given location code is a subnational level 1 code. In this context, a subnational level 1 code is a code that represents a specific region within a country. The location code is a string that consists of a letter followed by 6 digits. The letter represe... | ```python
def is_subnational1(location_code):
if len(location_code) != 7:
return False # Location code length should be 7 (1 letter + 6 digits)
country_code = location_code[0]
region_code = location_code[1:]
if not (country_code.isalpha() and country_code.isupper()):
return False # C... | magicoder | python |
You are tasked with implementing a simplified version of the `connect` function from the popular React-Redux library. The `connect` function is used to connect a React component to the Redux store, providing it with the necessary state and dispatch props. Your goal is to create a function that mimics this behavior by c... | ```typescript
// Define the connect function
function connect(mapStateToProps, mapDispatchToProps) {
return function (WrappedComponent) {
return class ConnectedComponent extends React.Component {
// Implement the logic to subscribe to the Redux store and pass props to the WrappedComponent
render() {
... | magicoder | typescript |
You are tasked with implementing a user authentication system for a web application. The system should validate user credentials and return the corresponding user ID if the credentials are correct. You are given a Python code snippet that includes an assertion for the `get_user_id` method of the authentication model. Y... | ```python
class AuthenticationModel:
def __init__(self):
# Assume user credentials are stored in a dictionary where the key is the username and the value is the password
self.user_credentials = {
'test01': 'password123',
'user123': 'securepass',
# Additional user ... | magicoder | python |
You are tasked with creating a custom Django admin interface for managing sessions in a conference management system. The provided code snippet is a part of the Django admin configuration. The `Session` model represents the individual sessions or talks scheduled at the conference. The `SessionAdmin` class is registered... | The issue in the code snippet is that the `list_display` attribute is referencing an invalid field name 'objects'. To display the session objects correctly in the admin interface, the correct field name should be used. Assuming that the `Session` model has a field named 'title' that represents the title of the session,... | magicoder | python |
You are tasked with implementing a class for handling thick matrices in a scientific computing library. The provided code snippet is the beginning of the class definition, including the declaration of a private member variable `m_matGen` of type `PhaseMatrix` initialized to the result of a `zero()` method call. Additio... | ```java
public class ThickMatrix {
private String identifier;
private double length;
private PhaseMatrix m_matGen;
public ThickMatrix(String strId, double dblLen, PhaseMatrix matPhiSub) {
this.identifier = strId;
this.length = dblLen;
this.m_matGen = matPhiSub;
}
// Add... | magicoder | java |
You are given a partially filled 9x9 Sudoku grid. The goal is to fill the grid with numbers from 1 to 9 such that every row, column, and 3x3 subgrid contains all the digits from 1 to 9 without repetition. You need to implement a function `solveSudoku` that takes the partially filled grid as input and fills it with the ... | ```java
public class SudokuSolver {
public boolean solveSudoku(int[][] grid) {
return solve(grid);
}
private boolean solve(int[][] grid) {
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
if (grid[row][col] == 0) {
for (... | magicoder | java |
You are tasked with implementing a program to simulate the evolution of a polymer chain based on a set of rules. The polymer chain is represented as a string of characters, and the rules dictate how the characters interact and change over a series of steps.
You are given a function `RunSteps` that takes the following ... | ```python
def RunSteps(steps, polymer, rules):
for _ in range(steps):
new_polymer = ''
i = 0
while i < len(polymer):
current_char = polymer[i]
if current_char in rules:
new_polymer += rules[current_char]
else:
new_polymer +=... | magicoder | python |
You are tasked with creating a program to manage a stock inventory system. The inventory is stored in a file, and the program should allow users to search for specific items by their item code and display the corresponding details.
You are given a code snippet that includes a file operation to close a file, a comment... | ```python
def search_item_by_code(item_code, records_file):
with open(records_file, "r") as file_object:
file_data = file_object.readlines()
for line in file_data:
record = line.strip().split(',')
if record[0] == item_code:
return f"Item Code: {record[0]}\nIte... | magicoder | python |
You are tasked with creating a Python function that processes data using parallel processing and Pandas dataframes. Your function will take in a list of arguments and a function to apply to each argument in parallel. The function should handle potential errors and return a concatenated dataframe with optional column an... | ```python
import pandas as pd
from multiprocessing import Pool
from requests.exceptions import ConnectionError, HTTPError
def parallel_process_data(function, arguments, n_threads, columns_name=None, index_name=None):
"""
Apply the given function to the list of arguments in parallel using multiple threads.
... | magicoder | python |
You are tasked with implementing a program that reads a text file and counts the occurrences of each word in the file. The program should then output the top N most frequently occurring words along with their counts.
Your program should ignore common English stop words such as "the", "and", "of", "in", etc. The stop ... | ```python
from typing import List, Tuple
import re
from collections import Counter
def top_n_words(file_path: str, n: int) -> List[Tuple[str, int]]:
with open(file_path, 'r') as file:
text = file.read().lower()
with open('stopwords.txt', 'r') as stop_words_file:
stop_words = stop_words_fil... | magicoder | python |
You are tasked with implementing a C++ function that validates an X.509 certificate using the given code snippet as a starting point. The X.509 certificate is represented by the `net::x509_certificate` class, and the validation process involves checking the certificate's expiration date and verifying its signature agai... | ```cpp
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util.h"
#include "net/ssl/ssl_info.h"
namespace {
bool validateCertificate(const net::x509_certificate& certificate, const net::x509_certificate& caCertificate) {
// Check certificate expiration
if (certificate.not_after() < net::x509_util:... | magicoder | cpp |
You are tasked with implementing a function that reads a file in chunks and calculates the total number of bytes read. The function should take a file object and a chunk size as input and return the total number of bytes read from the file. The provided code snippet is a part of the solution and demonstrates how the re... | ```python
def calculate_total_bytes_read(file_obj, chunk_size):
total_bytes_read = 0
while True:
data = file_obj.read(chunk_size)
read_size = len(data)
if not read_size:
break
total_bytes_read += read_size
return total_bytes_read
```
The `calculate_total_bytes_re... | magicoder | python |
You are tasked with creating a Bash script that generates a QR code image based on an email input. The script should take an email as a command-line argument, or use a default email if no argument is provided. The QR code should have a black foreground color and a white background. The script should then make a POST re... | ```bash
#!/usr/bin/env bash
email='<DEFAULT_EMAIL>'
if test $# -ge 1
then
email=$1
fi
curl -H "content-type: application/json" -d "{\"email\": \"$email\", \"color\": [0,0,0], \"background\": [255,255,255]}" https://m7cwj1fy7c.execute-api.us-west-2.amazonaws.com/test/qr | grep -o 'data.*",' | sed 's/..$//'
```
The pro... | magicoder | shell |
You are tasked with implementing a class for controlling Model Specific Register (MSR) fields in a system. The class, `MSRFieldControl`, is responsible for writing a value to a specific MSR field with certain configurations. The code snippet provided is a part of a unit test for the `MSRFieldControl` class. Your task i... | ```cpp
#include <memory>
#include <cstdint>
// Define the MSRIO class
class MSRIO {
public:
virtual void write_msr(int cpu, uint64_t offset, uint64_t value, uint64_t mask) = 0;
};
// Define the MSR class
class MSR {
public:
enum m_function {
M_FUNCTION_SCALE
};
};
// Define the MSRFieldControl cl... | magicoder | cpp |
You are given a sequence of N integers. Your task is to find the maximum score that can be obtained by selecting a subsequence of K integers from the given sequence. The score of a subsequence is calculated as the sum of the absolute differences between each pair of adjacent integers in the subsequence. You need to imp... | ```cpp
#include <iostream>
#include <algorithm>
using namespace std;
long long int maxScore(int N, int K, long long int* numbers) {
sort(numbers + 1, numbers + N + 1);
long long int maxScore = 0;
for (int i = 1; i <= N - K; i++) {
maxScore += min(numbers[i + K] - numbers[i], numbers[i + K] - number... | magicoder | cpp |
You are tasked with implementing a class that manages type bindings for a dependency injection container. The class, named `TypeBinder`, is responsible for binding types to their respective accessors and lifetime managers. The `bind_type` method is used to bind a type to an accessor and a lifetime manager. The `binded`... | ```python
from typing import Type, Union, Iterable
import collections
class TypeBinder:
def __init__(self):
self.container = {}
def _sanitize_accessor(self, accessor: Type) -> str:
return accessor.__name__ if isinstance(accessor, type) else accessor
def _bind_type(self, accessor: Type, li... | magicoder | python |
You are tasked with creating a script to automate the deployment process for a software project. The script should handle different modes of deployment and copy necessary infrastructure files to the working directory. Your task is to write a Bash script that accomplishes these requirements.
The script should perform t... | ```bash
#!/bin/bash
# Set SKUBA_MODE variable
SKUBA_MODE=release
# Append make command based on SKUBA_MODE
if [ "$SKUBA_MODE" = "release" ]; then
cmd+="make release"
else
cmd+="make install"
fi
# Evaluate cmd variable to execute make command
eval "$cmd"
# Disable shellcheck warning SC2086
# shellcheck disable=S... | magicoder | shell |
You are tasked with implementing a simple routing system for a web application. The routing system should be able to match incoming requests to specific handlers based on the requested URL. Additionally, the system should support middleware for handling common tasks such as authentication, logging, and caching.
Your t... | ```python
class Router:
def __init__(self):
self.routes = []
def addRoute(self, path, handler):
self.routes.append((path, handler))
def addMiddleware(self, middleware):
if not hasattr(self, 'middlewares'):
self.middlewares = []
self.middlewares.append(middleware... | magicoder | python |
You are tasked with creating a Python function that simulates the process of fetching movie data from Rotten Tomatoes and storing it in a database. The function should handle checking if the movie data is already present in the database, fetching the data from Rotten Tomatoes, and then storing it in the database if it'... | ```python
import time
def fetch_and_store_movie_data(handle):
# Assume the existence of a database connection and a cursor object
# Check if we already have the movie data in the database
sql = "SELECT id FROM rt_dvd WHERE handle = %s" % handle
cursor.execute(sql)
row = cursor.fetchone()
if row... | magicoder | python |
You are tasked with implementing a macro to measure the time taken to execute a given block of code. The macro should take the name of the measurement and the block of code as input, and it should output the time taken to execute the block in milliseconds. Your task is to create a macro `measure!` that accomplishes thi... | ```rust
macro_rules! measure {
($name:expr, $b:block) => {{
let start = time::PreciseTime::now();
let v = $b;
let end = time::PreciseTime::now();
println!("{} took: {} ms", $name, start.to(end).num_milliseconds());
v
}};
}
fn main() {
let opengl = OpenGL::_3_2;
... | magicoder | rust |
You are tasked with creating a program to manage the opening hours of various businesses. The opening hours are defined using a tuple of 7 elements, each representing a day of the week (starting from Monday). Each element in the tuple can have one of three values: 0, 1, or 2.
- 0 represents closed
- 1 represents open ... | ```python
from typing import Tuple
def get_opening_hours(hours: Tuple[int, int, int, int, int, int, int], day: int) -> str:
day_hours = hours[day]
if day_hours == 0:
return "Closed"
elif day_hours == 1:
return "Open all day"
else:
return "Open from 09:00 to 17:00" # Replace wit... | magicoder | python |
You are tasked with implementing a function to calculate the Rayleigh number for natural convection heat transfer in a vertical channel. The Rayleigh number (Ra) is a dimensionless number used in fluid dynamics to characterize the flow patterns in a fluid due to buoyancy forces relative to viscous forces. It is defined... | ```python
import math
def calculate_rayleigh_number(g, beta, T_hot, T_cold, H, nu, alpha):
Ra = (g * beta * (T_hot - T_cold) * H**3) / (nu * alpha)
return Ra
# Example usage
g = 9.81 # m/s^2
beta = 3.5e-3 # 1/K
T_hot = 400 # K
T_cold = 300 # K
H = 0.1 # m
nu = 1.5e-6 # m^2/s
alpha = 2.5e-5 # m^2/s
pri... | magicoder | python |
You are given a directed graph represented as an adjacency matrix. An adjacency matrix is a 2D array where the entry at index (i, j) represents the weight of the edge from node i to node j. The diagonal of the adjacency matrix represents self-loops, i.e., edges from a node to itself.
Your task is to write a function t... | ```python
from typing import List
def check_self_loop_sum(adj: List[List[int]]) -> bool:
self_loop_sum = sum(adj[i][i] for i in range(len(adj)))
return self_loop_sum == 0
```
The `check_self_loop_sum` function takes an adjacency matrix `adj` as input and calculates the sum of weights of all self-loops in the g... | magicoder | python |
You are tasked with implementing a Python function that calculates the shortest path between two nodes in a directed graph using Dijkstra's algorithm. The graph is represented as an adjacency list, and the function should return the shortest path as a list of nodes and the total distance of the path.
You are given the... | ```python
from collections import defaultdict
import heapq
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v, w):
self.graph[u].append((v, w))
def dijkstra(graph, start, end):
pq = [(0, start, [])]
visited = set()
while pq:
(cost, nod... | magicoder | python |
You are tasked with creating a Python program to automate the process of logging into a website using the `pyautogui` library. The program should simulate the process of typing in the username and password fields and pressing the "tab" key to move between the fields. Your task is to write a Python function that takes t... | ```python
import pyautogui
import time
def automate_login(username, password):
print("Typing now!")
pyautogui.typewrite(username)
pyautogui.typewrite(['tab'])
pyautogui.typewrite(password)
pyautogui.typewrite(['tab'])
pyautogui.typewrite(password)
pyautogui.typewrite(['enter'])
# Exam... | magicoder | python |
You are tasked with developing a Python script to validate USB endpoint configurations for different USB device classes. The script should ensure that the endpoint numbers for Communication Device Class (CDC), Mass Storage Class (MSC), and Human Interface Device (HID) are not set to 0, as this is not allowed by the USB... | ```python
def validate_usb_endpoints(args):
if args['cdc_ep_num_notification'] == 0:
raise ValueError("CDC notification endpoint number must not be 0")
elif args['cdc_ep_num_data_out'] == 0:
raise ValueError("CDC data OUT endpoint number must not be 0")
elif args['cdc_ep_num_data_in'] == 0:
... | magicoder | python |
You are tasked with simulating the creation of a 3D scene using Rust programming language. Your goal is to implement a function that generates a random scene of spheres with different materials and properties. The scene will be rendered using ray tracing techniques.
You are provided with a code snippet that demonstrat... | ```rust
use rand::prelude::*;
use std::rc::Rc;
use std::f64::consts::PI;
// Define a struct to represent a 3D point
#[derive(Clone, Copy)]
struct Point3 {
x: f64,
y: f64,
z: f64,
}
impl Point3 {
fn new(x: f64, y: f64, z: f64) -> Point3 {
Point3 { x, y, z }
}
fn distance(&self, other: ... | magicoder | rust |
You are tasked with implementing a class that represents a media item and provides methods for converting the item to a view model and generating a string representation.
You are given a partial code snippet for the media item class, which includes the assignment of a property `Mediaid` and an overridden `ToString` me... | ```csharp
using System;
public class MediaItem
{
public int MediaId { get; set; }
public string From { get; set; }
public string Folder { get; set; }
public long Timestamp { get; set; }
public MediaItem(int mediaId, string from, string folder, long timestamp)
{
MediaId = mediaId;
... | magicoder | csharp |
You are tasked with implementing a command-line argument parser for a simulation program. The program can accept both Lua script options and non-Lua test options. The provided code snippet demonstrates the registration of various command-line options using the `FLAGS::Register` function. The options include script file... | ```cpp
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
// Define a struct to hold the parsed command-line options
struct CommandLineOptions {
std::string scriptFileName;
std::vector<std::string> inlineStrings;
int testNumber;
bool is3D;
bool runDiffTest;
double ... | magicoder | cpp |
You are tasked with implementing a custom exception handling mechanism for a simple file processing application. The application is designed to read a file, process its contents, and perform specific actions based on the data. However, the application should handle exceptions gracefully and provide meaningful error mes... | ```java
// Custom exception class for file processing errors
public class FileProcessingException extends Exception {
public FileProcessingException(String message) {
super(message);
}
}
public class FileProcessor {
public void processFile(String filePath) {
try {
// Code for re... | magicoder | java |
You are tasked with creating a script to automate the installation of R packages for a specific project. The script should install the required packages using the R command line interface and handle any necessary permissions.
Write a bash script that installs the following R packages using the R command line interface... | ```bash
#!/bin/bash
echo "install.packages(c('devtools', 'shinyAce', 'editR'), repos='http://cran.us.r-project.org')" | sudo R --no-save
```
The provided bash script uses the `echo` command to send the installation command to the R command line interface. The `sudo` command is used to run the installation with elevat... | magicoder | shell |
You are tasked with implementing a custom backward function for a neural network layer. The forward function `UpsamplingBilinear2d.forward` takes an input tensor `input` and upsamples it to a specified output size using bilinear interpolation. The backward function `UpsamplingBilinear2d.backward` is responsible for com... | ```python
class UpsamplingBilinear2d(Function):
@staticmethod
def forward(ctx, input, output_size):
# Implementation of forward pass
# ...
@staticmethod
def backward(ctx, ggI, output_size, _):
# ggI: gradient of the loss with respect to the output
# output_size: size of ... | magicoder | python |
You are tasked with creating a Python script that automates the process of starting a web server using Gunicorn with specific configurations. Gunicorn is a popular WSGI HTTP server for Python web applications. Your script should take input parameters for the server binding address, the number of worker processes, the l... | ```python
import subprocess
def start_gunicorn_server(bind_address, workers, log_level, access_logfile, error_logfile, wsgi_module):
# Validate input parameters
if not isinstance(workers, int) or workers <= 0:
raise ValueError("Number of workers must be a positive integer")
valid_log_levels = ["de... | magicoder | python |
You are tasked with implementing a Python class that represents an expression in a programming language. The given code snippet is a partial implementation of a class called `RValueExpression`, which inherits from another class `LValueExpression`. The `RValueExpression` class is intended to represent an expression that... | ```python
import ast
class LValueExpression:
def __init__(self):
pass
class RValueExpression(LValueExpression):
def __init__(self):
super().__init__()
self.qualifiers = []
def add_qualifier(self, qualifier):
self.qualifiers.append(qualifier)
class ConstQualifier:
def ... | magicoder | python |
You are tasked with creating a class that manages different types of image processing widgets in a medical imaging application. The given code snippet initializes several image processing widgets, each associated with a specific type of operation. The widgets are constructed with a `timeNavigationController` object, wh... | ```cpp
#include <iostream>
#include <string>
class ImageProcessingManager {
private:
mitk::SliceNavigationController* timeNavigationController;
public:
ImageProcessingManager(mitk::SliceNavigationController* controller) : timeNavigationController(controller) {}
void performOperation(const std::string& op... | magicoder | cpp |
You are tasked with creating a custom function registry for a template engine. The template engine uses the Twig library, and you need to define custom functions that can be used within the templates. Each custom function should be associated with a specific method of a given class and should be marked as safe for all ... | ```php
<?php
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class CustomFunctionExtension extends AbstractExtension
{
public function getFunctions(): array
{
return [
new TwigFunction(
'getCustomText',
[$this, 'getCustomText'],
... | magicoder | php |
You are tasked with implementing a function to determine the similarity between two HTTP tokens. HTTP tokens are sequences of characters that are used in various parts of the HTTP protocol, such as headers and URIs. The similarity between two tokens is defined as follows:
- If two tokens differ only by non-letter chara... | ```rust
use std::collections::HashSet;
#[derive(Debug, PartialEq)]
enum TokenSimilarity {
Identical,
SameLetters,
Distant,
}
fn http_token(token: &str) -> String {
token.to_string()
}
fn determine_similarity(token1: &str, token2: &str) -> TokenSimilarity {
let set1: HashSet<char> = token1.chars()... | magicoder | rust |
You are tasked with implementing a script to split a SQL file into individual SQL statements and save each statement into separate files. The script should read a given SQL file, separate the statements by semicolon, and save each statement into a new file named in ascending order.
You need to write a Bash script that... | ```bash
#!/bin/bash
# Check if the input file is provided
if [ -z "$1" ]; then
echo "Usage: $0 <input_sql_file>"
exit 1
fi
# Check if the input file exists
if [ ! -f "$1" ]; then
echo "Error: Input file not found"
exit 1
fi
# Read the input SQL file, split the statements by semicolon, and save each s... | magicoder | shell |
You are tasked with implementing a simplified version of a command-line interface (CLI) framework in Python. The provided code snippet demonstrates the usage of a custom CLI library called "zup" and defines two command functions: `config` and `ls`. The `zup` library is used to create command-line commands and handle th... | ```python
class CustomCLI:
def __init__(self):
self.commands = {}
def command(self, func):
# Decorator function to register command functions
self.commands[func.__name__] = func
return func
def execute(self, command, args):
# Execute the appropriate command function... | magicoder | python |
You are tasked with creating a Python function that processes a list of photo data and returns a dictionary containing specific information about the photos. Each photo is represented as a dictionary with the following keys: "id", "count", and "url". The "id" key contains a string representing the photo's unique identi... | ```python
def process_photos(photos: list) -> dict:
total_photos = len(photos)
view_counts = [photo["count"] for photo in photos]
highest_views_photo = max(photos, key=lambda x: x["count"])
lowest_views_photo = min(photos, key=lambda x: x["count"])
average_views = sum(view_counts) / total_photos
... | magicoder | python |
You are tasked with implementing a method to generate the full property path of an object in a nested structure. The method should take into account the object's hierarchy and return the complete path to the property as a string.
You are given a PHP class with a method `getFullPropertyPath()` that needs to be complete... | ```php
/**
* @return string
*/
public function getFullPropertyPath()
{
$fullPath = $this->propertyPath;
if (!empty($fullPath)) {
$fullPath .= '.';
}
$properties = array_keys($this->data);
foreach ($properties as $property) {
if (is_array($this->data[$property])) {
$nest... | magicoder | php |
You are tasked with simulating a network setup using a bash script. The script provided sets up and cleans up a simulated network environment. The script uses various functions to create and delete network components. The `create_veth_subnet` function creates a specified number of virtual Ethernet pairs and assigns the... | ```bash
setup_network() {
create_veth_subnet 3 2
add_routers 2
del_bridges 1
}
``` | magicoder | shell |
You are tasked with implementing a class that can extract a specific code structure from a given source code. The class should have a method `Extract` that takes a string `TagToFind` as input and returns an object of type `ICodeStruct`. The `ICodeStruct` interface represents a code structure and is already defined.
Th... | ```csharp
public class CodeExtractor
{
private string sourceCode;
public CodeExtractor(string sourceCode)
{
this.sourceCode = sourceCode;
}
public ICodeStruct Extract(string TagToFind)
{
// Implementing the logic to extract the code structure based on TagToFind
// Assum... | magicoder | csharp |
You are tasked with implementing a parallel data retrieval system for the Minecraft Pi API. The goal is to create a class, `ParallelGetter`, that can efficiently retrieve block data from the Minecraft Pi API in parallel using multiple connections.
The `ParallelGetter` class should have the following properties and met... | ```python
import timeit
class Connection:
"""Mock Connection class for demonstration purposes"""
def __init__(self, address, port):
self.address = address
self.port = port
class ParallelGetter:
"""Get block data from the Minecraft Pi API in parallel"""
def __init__(self, address="local... | magicoder | python |
You are tasked with creating a Python package that includes a router module. The router module is responsible for routing requests to different endpoints within the package. Your goal is to implement a function that adds a new endpoint to the router.
You are provided with the following code snippet as a starting point... | ```python
# router.py
class Router:
def __init__(self):
self.endpoints = {}
def add_endpoint(self, endpoint_name, handler_function, methods):
if endpoint_name in self.endpoints:
self.endpoints[endpoint_name]['handler'] = handler_function
self.endpoints[endpoint_name]['m... | magicoder | python |
You are tasked with creating a Python function that takes in the file path of an image and returns the dimensions (width and height) of the image. You are not allowed to use any external libraries or modules to accomplish this task. You must read the image file and extract its dimensions using only built-in Python func... | ```python
def get_image_size(file_path):
with open(file_path, 'rb') as f:
f.seek(163) # Seek to the start of the 24th byte
a = f.read(2) # Read the width
b = f.read(2) # Read the height
width = (b[0] << 8) + a[0] # Calculate the width
height = (b[1] << 8) + a[1] # Calcul... | magicoder | python |
You are tasked with implementing a class that manages sequences of dimensions for a given set of variables. The class should handle the generation of sequences based on the provided dimensions and variables. Your task is to complete the implementation of the `SequenceManager` class by filling in the missing parts of th... | ```python
class SequenceManager:
def __init__(self, dims, cvars):
self.dims = dims
self.cvars = cvars
self.seq_in = []
self.seq_out = []
def generate_sequences(self):
gen = [0] * len(self.dims)
j = len(self.dims) - 1
while j >= 0:
if gen[j] <=... | magicoder | python |
You are tasked with implementing a cookie caching system for a web application. The system should store cookies in a cache and retrieve them efficiently when requested. The cache should have a maximum capacity, and when it reaches its limit, the least recently used cookie should be evicted to make space for the new one... | ```python
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.head = Node(0, 0)
self.tail = Nod... | magicoder | python |
You are working on a CAD (Computer-Aided Design) software and need to implement a function to convert 3D control points to a 2D LWPOLYLINE (lightweight polyline) and add it to the existing document. The existing document is represented by a variable `msp` which is the model space of the CAD drawing. The 3D control poin... | ```python
def add_lwpolyline_to_doc(msp, all_control_points):
# Remove z axis from control points and convert to 2D points
points2d = [(point[0], point[1]) for point in all_control_points]
# Add LWPOLYLINE to the existing document
msp.add_lwpolyline(points=points2d, dxfattribs={'color': 1, 'layer':... | magicoder | python |
You are tasked with creating a Python program that simulates a simple banking system. The program should allow users to create accounts, log in, deposit money, withdraw money, and view their balance. Additionally, the program should log all transactions using the Python logging module.
Your task is to implement the `B... | ```python
import logging
class BankingSystem:
def __init__(self):
self.accounts = {}
self.logger = logging.getLogger("banking_system")
self.logger.setLevel(logging.INFO)
formatter = logging.Formatter('[%(levelname)s] - %(message)s')
console_handler = logging.StreamHandler()
... | magicoder | python |
You are tasked with implementing a QuotesService class in TypeScript for a financial application. The QuotesService is responsible for fetching and managing asset quotes from a storage system. The class has a constructor that takes in a QuotesStorage instance, a RepoService instance, a minimum date for quotes, and a Da... | ```typescript
import { QuotesStorage } from './quotes-storage';
import { AssetQuote } from '../types/asset-quote';
export const QUOTES_MIN_DATE = new InjectionToken('QUOTES_MIN_DATE');
@Injectable()
export class QuotesService {
private quotesMapPromise: Promise<Map<string, AssetQuote>> = null;
constructor(p... | magicoder | typescript |
You are tasked with implementing a simple text editor for a digital notebook. The notebook consists of multiple pages, each containing a grid of rows and columns. The text editor provides the following operations:
1. `write(int const & page, int const & row, int const & col, Direction dir, string const & str)`: Writes... | ```cpp
#include <iostream>
#include <vector>
enum Direction {
RIGHT,
DOWN
};
class DigitalNotebook {
private:
std::vector<std::vector<std::string>> pages;
public:
DigitalNotebook(int numPages, int rows, int cols) {
pages.resize(numPages, std::vector<std::string>(rows, std::string(cols, ' ')))... | magicoder | cpp |
You are tasked with implementing a Python class that handles authentication for a cloud service. The class, named `CloudAuthService`, is responsible for reading and processing service account information from a file or a base64-encoded string. Your task is to complete the implementation of the `CloudAuthService` class ... | ```python
import base64
class CloudAuthService:
def __init__(self, provider_options):
self.provider_options = provider_options
def _get_provider_option(self, option_name):
return self.provider_options.get(option_name, None)
def read_service_account_info(self):
if self._get_provide... | magicoder | python |
You are tasked with implementing a function to determine the number of bytes required to encode a given Unicode code point in UTF-8 format. The UTF-8 encoding uses a variable number of bytes to represent Unicode code points, based on the range in which the code point falls. The encoding rules are as follows:
- For cod... | ```python
def utf8EncodingBytes(code_point: int) -> int:
if code_point <= 0x007F:
return 1
elif code_point <= 0x07FF:
return 2
elif code_point <= 0xFFFF:
return 3
elif code_point <= 0x10FFFF:
return 4
else:
raise ValueError("Invalid Unicode code point")
```
T... | magicoder | python |
You are tasked with debugging a Python program that simulates a chatbot called SkyViewBot. The program seems to be encountering an error, and your goal is to identify and fix the issue. The code snippet provided is a part of the main function of the program. Your task is to identify the potential error and correct it t... | The issue in the provided code snippet is that the `return retval` statement is outside the `main` function, which causes a syntax error. To fix this issue, the `return retval` statement should be indented to be inside the `main` function. Additionally, the `sys` module needs to be imported for the program to work corr... | magicoder | python |
You are tasked with designing a routing system for a web application using Laravel framework. The given code snippet represents the routes defined in the `web.php` file of a Laravel application. Each route maps to a specific controller method and may have additional attributes like route names.
Your task is to create ... | ```php
function getControllerMethod($routeName) {
$routes = [
'log.create' => 'Mypage\LogController@add',
'log.edit' => 'Mypage\LogController@edit',
'log.update' => 'Mypage\LogController@update',
'log.delete' => 'Mypage\LogController@delete',
'log.index' => 'Mypage\LogControl... | magicoder | php |
You are tasked with creating a Python function that simulates a simplified version of a web page testing scenario. The function should take a list of actions as input and perform them sequentially. Each action can be one of the following types:
1. Click on a hyperlink using its XPath.
2. Click on an element with a spec... | ```python
from typing import List, Union, Tuple
def test_webpage(actions: List[Union[Tuple[str, str], str]]) -> int:
# Simulate web page testing scenario
# Assume self.driver and self.data.page_loading are available
count = 0
for action in actions:
if isinstance(action, tuple):
if ... | magicoder | python |
You are tasked with implementing a Python function that can parse and convert a string representation of numbers into their numerical form. The function should handle various formats of numbers, including integers, floats, and comma-separated numbers. Additionally, the function should be able to handle both regular str... | ```python
def parse_numbers(*args):
result = []
for arg in args:
if isinstance(arg, str):
# Replace any commas with empty strings and convert to float
num = float(arg.replace(',', ''))
result.append(num)
elif isinstance(arg, unicode):
# If the inpu... | magicoder | python |
You are tasked with implementing a copy constructor for the `Shader` class in an OpenGL-based application. The `Shader` class represents an OpenGL shader and is defined with the following attributes and methods:
Attributes:
- `bool original`: A boolean flag indicating whether the shader is an original or a copy.
- `GL... | ```cpp
// The new copy constructor for this thingy.
Shader(const Shader& other) : original(false) {
// Generate a new shader ID for the copied shader
glGenShader(id);
// Copy the shader source code from the original to the copied shader
GLint length;
glGetShaderiv(other.id, GL_SHADER_SOURCE_LEN... | magicoder | cpp |
You are tasked with implementing a Rust function that performs a specific cryptographic operation using the given code snippet as a reference. The code snippet contains hexadecimal values and assertions related to cryptographic key generation. Your task is to write a function that generates a spending key and a proof g... | ```rust
fn generate_keys() -> (Vec<u8>, Vec<u8>) {
let spending_key: Vec<u8> = SPENDING_KEY_GENERATOR.to_vec();
let proof_key: Vec<u8> = PROOF_GENERATION_KEY_GENERATOR.to_vec();
(spending_key, proof_key)
}
fn main() {
let sapling_generators = SaplingGenerators {
skb: SPENDING_KEY_GENERATOR,
... | magicoder | rust |
You are tasked with implementing a custom UIControl subclass in Swift that allows setting a value for a specific control state. The provided code snippet demonstrates the usage of an unsafe bit cast to invoke a method for setting a value for a control state. Your task is to create a method within the UIControl subclass... | ```swift
// Custom UIControl subclass
class CustomControl: UIControl {
// Method to set value for a specific control state
func setValue(_ value: Any?, forControlState state: UIControl.State) {
// Implement the logic to set the value for the specified control state
// For example, you can u... | magicoder | swift |
You are tasked with creating a program that processes a file containing information about views and stars for various resources in a web application. The file contains data in the following format:
```
<filename>resources/views/yonetim/layouts/partials/sidebar.blade.php<gh_stars>0
<div class="list-group">
```
Each li... | ```python
import re
# Read the file and extract data
file_path = 'path_to_file.txt' # Replace with the actual file path
with open(file_path, 'r') as file:
lines = file.readlines()
total_stars = 0
max_stars = 0
max_stars_filename = ''
total_content_length = 0
# Process each line to calculate total stars, identif... | magicoder | python |
You are tasked with simulating the rendering of a scene using ray tracing. The given code snippet represents a part of a ray tracer program, where spheres are defined with their respective properties. The spheres are defined using the following format: `Sphere(radius, position, emission, color, material)`. The material... | ```cpp
#include <vector>
#include <cmath>
Vec calculateRayColor(const Vec& origin, const Vec& direction, const std::vector<Sphere>& spheres,
const Vec& ambientColor, const Vec& lightPosition, const Vec& lightColor,
double diffuseCoeff, double specularCoeff, double shininess)... | magicoder | cpp |
You are tasked with implementing a function that will parse and extract data from an HTML snippet. The HTML snippet contains a list of items, each represented by a `<div>` element with a specific class. Your task is to extract the content of these items and return them as an array of strings.
You are given the followi... | ```javascript
function extractItems(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const items = doc.querySelectorAll('.item');
const extractedItems = Array.from(items).map(item => item.textContent);
return extractedItems;
}
// Test the function with the given ... | magicoder | javascript |
You are tasked with implementing a C++ header file for a toy compiler's abstract syntax tree (AST) declaration. The provided code snippet is the beginning of the header file, which includes the declaration of the AST declaration class.
Your task is to complete the implementation of the AST declaration class by adding ... | ```cpp
#pragma once
#include <toy_compiler/munster/ast/decl/decl.hpp>
#include <vector>
#include <string>
namespace toy_compiler::munster::ast {
class ASTDeclaration : public ASTNode {
public:
enum class DeclarationType {
Variable,
Function,
Class
// Add... | magicoder | cpp |
You are tasked with implementing a class for training a neural network model. The class includes methods for initializing parameters, clipping gradients, and performing operations after each training iteration. Your task is to complete the implementation of the class by adding the missing parts of the code.
You are gi... | ```python
class ModelTrainer:
def __init__(self, grad_clip=None, mean_teacher=None):
self.grad_clip = grad_clip
self.mean_teacher = mean_teacher
def clip_grads(self, params):
if self.grad_clip is not None:
clip_grad.clip_grad_norm_(
filter(lambda p: p.require... | magicoder | python |
You are tasked with implementing a class that represents a collection of styles for a user interface. The styles are defined by a unique identifier, a name, and a list of points. Your task is to create a C++ class called `StyleCollection` that encapsulates this functionality.
The `StyleCollection` class should have th... | ```cpp
#include <QUuid>
#include <QString>
#include <QPointF>
#include <QList>
#include <QMap>
#include <algorithm>
struct Style {
QUuid id;
QString name;
QList<QPointF> points;
};
class StyleCollection {
public:
StyleCollection() {}
void addStyle(const QString& name, const QList<QPointF>& points... | magicoder | cpp |
You are tasked with creating a program that calculates the remaining time in days, weeks, and months until a person reaches the age of 90. The program should take the user's current age as input and then output the remaining time in days, weeks, and months.
Write a Python program that takes the user's age as input and... | ```python
# Prompt the user to enter their age
age = input("Enter your age: ")
# Validate the input to ensure it is a positive integer
while not age.isdigit() or int(age) <= 0:
age = input("Please enter a valid age as a positive integer: ")
age = int(age)
# Calculate the remaining time until the user reaches the... | magicoder | python |
You are tasked with writing a Python function that processes a series of SQL commands and performs substitutions based on a given list of tuples. The SQL commands are stored in a string, and the substitutions are represented as tuples containing a search string and a replacement string.
You need to implement the `proc... | ```python
from typing import List, Tuple
def process_sql_commands(sql_commands: str, substitutions: List[Tuple[str, str]]) -> str:
modified_commands = []
# Split the SQL commands based on semicolon delimiter
commands = sql_commands.split(';')
for command in commands:
modified_command ... | magicoder | python |
You are tasked with creating a Roman numeral formatter class that can convert integers to their Roman numeral representation. The Roman numeral system uses combinations of letters to represent numbers. The following are the basic Roman numerals and their corresponding values:
- I: 1
- V: 5
- X: 10
- L: 50
- C: 100
- D:... | ```csharp
public class RomanNumeralFormatter
{
private static readonly string[] Thousands = { "", "M", "MM", "MMM" };
private static readonly string[] Hundreds = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
private static readonly string[] Tens = { "", "X", "XX", "XXX", "XL", "L", "LX", "... | magicoder | csharp |
You are given a positive integer `n`. Your task is to write a function that calculates the sum of the squares of all the odd digits in the binary representation of `n`.
For example, if `n` is 21, its binary representation is 10101. The odd digits are 1, 1, and 1, and their squares are 1, 1, and 1, respectively. Theref... | ```python
def sum_of_odd_digits_squares(n: int) -> int:
result = 0
bit_place = 0
while n > 0:
if n & 1 == 1:
if bit_place % 2 == 0: # Check if the bit place is odd
result += 1 # Add the square of the odd digit
n >>= 1 # Right shift to consider the next bit
... | magicoder | python |
You are tasked with implementing a class for a rock sampling robot in a grid-based environment. The robot can move in four directions (up, down, left, and right) and can collect rock samples at its current location. The robot's state is represented by its position in the grid and the collected rock samples.
The provid... | ```cpp
#include <iostream>
#include <vector>
// Define the ROCKSAMPLE_STATE structure to hold the robot's position and rock samples
struct ROCKSAMPLE_STATE {
int x; // x-coordinate of the robot
int y; // y-coordinate of the robot
std::vector<bool> rockSamples; // Vector to track collected rock samples
}... | magicoder | cpp |
You are tasked with creating a Python program that simulates a simple game of rock-paper-scissors. The program should allow a user to play against the computer and keep track of the score. The game should continue until the user decides to quit.
Your program should follow these rules:
- The computer should randomly se... | ```python
import random
def get_user_choice():
while True:
user_choice = input("Enter your choice (rock, paper, or scissors), or 'q' to quit: ").lower()
if user_choice in ['rock', 'paper', 'scissors', 'q']:
return user_choice
else:
print("Invalid choice. Please enter... | magicoder | python |
You are tasked with implementing a Python function that filters out hidden files and directories from a given dictionary. Hidden files and directories are those whose names start with a dot ('.'). The function should take a dictionary as input and return a new dictionary containing only the non-hidden items.
The funct... | ```python
def filter_hidden(x: dict) -> dict:
if not isinstance(x, dict):
raise TypeError("Input must be a dictionary")
filtered_dict = {}
for key, value in x.items():
if not key.startswith('.'):
if isinstance(value, dict):
filtered_dict[key] = filter_hidden(valu... | magicoder | python |
You are tasked with implementing a physics simulation system for applying friction to moving objects. The system includes a struct `ApplyBaseFrictionSystem` with a field `velocity_margin` representing the minimum velocity at which friction should be applied. Additionally, there is a method `with_velocity_margin` to set... | ```rust
impl ApplyBaseFrictionSystem {
// ... (previous code remains unchanged)
/// Apply friction to the given velocities based on the velocity margin.
pub fn apply_friction(&self, velocities: &mut Vec<f32>) {
for velocity in velocities.iter_mut() {
if *velocity < self.velocity_margin ... | magicoder | rust |
You are tasked with creating a Python class that manages a graphical user interface (GUI) for a text editor application. The class should include methods for adding tabs, frames, and labels to the GUI. Your task is to implement the `add_content_tool` method, which adds content to the "tool" tab of the GUI.
The `add_co... | ```python
import tkinter as tk
from tkinter import ttk
class TextEditorGUI:
def __init__(self, root):
self.root = root
self.tabs = ttk.Notebook(self.root)
self.tabs.grid(row=0, column=0)
self.tool = ttk.Frame(self.tabs)
self.tabs.add(self.tool, text=' Tool ')
self.... | magicoder | python |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for creating a new account, depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should be able to handle multiple accounts and ensure that account numbers are uniq... | ```python
class BankingSystem:
def __init__(self):
self.accounts = {}
def create_account(self, account_number, initial_balance):
if account_number > 0 and account_number not in self.accounts and initial_balance >= 0:
self.accounts[account_number] = initial_balance
return... | magicoder | python |
You are tasked with implementing a library management system that processes a series of commands to borrow and return books. The system reads input from the standard input, where each line represents a command. The input consists of the following types of commands:
1. `END`: Marks the end of a set of commands. There w... | ```java
import java.util.Scanner;
import java.util.TreeMap;
class Book {
private boolean isBookBorrowed;
public Book(boolean isBookBorrowed) {
this.isBookBorrowed = isBookBorrowed;
}
public boolean getIsBookBorrowed() {
return isBookBorrowed;
}
public void setIsBookBorrowed(b... | magicoder | java |
You are tasked with implementing a custom Python class that can dynamically generate SQL queries based on the provided model and fields. Your class should be able to generate a SELECT query for the specified fields from the given model.
You need to create a Python class `SQLQueryBuilder` with the following specificati... | ```python
class SQLQueryBuilder:
def __init__(self, model, fields):
self.model = model
self.fields = fields
def generate_query(self):
field_list = ', '.join(self.fields)
return f"SELECT {field_list} FROM {self.model};"
# Test the SQLQueryBuilder class
query_builder = SQLQueryBu... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple 2D robot navigation system. The robot is placed on a grid and can move in four directions: up, down, left, and right. The robot's position is represented by its x and y coordinates on the grid. The class should provide methods to move the robot in ... | ```python
class RobotNavigator:
def __init__(self, x, y):
self.x = x
self.y = y
def move_up(self):
self.y += 1
def move_down(self):
self.y -= 1
def move_left(self):
self.x -= 1
def move_right(self):
self.x += 1
def get_position(self):
... | magicoder | python |
You are tasked with creating a program that handles signals in a multi-threaded environment. Your program should define a signal handler using the `sigaction` function and handle the `SIGINT` signal. Additionally, the program should create a new thread and demonstrate how the signal handler behaves in the presence of m... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
void my_handler(int signal) {
printf("Signal %d received\n", signal);
}
void defining_sigaction() {
struct sigaction sa;
sa.sa_handler = my_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
... | magicoder | c |
You are tasked with implementing a Python function to perform Hermite interpolation. Hermite interpolation is a method for constructing a polynomial interpolant given function values and derivatives at specific points. The goal is to create a function that takes in the given function values, their derivatives, and the ... | ```python
import numpy as np
def hermite_matrices(tau_given, tau_eval):
n = len(tau_given)
m = len(tau_eval)
Ai = np.zeros((n, n))
Bi = np.zeros((n, n))
Ad = np.zeros((n, m))
Bd = np.zeros((n, m))
for i in range(n):
Ai[i, i] = 1
Bi[i, i] = 1
for j in range(n):
... | magicoder | python |
You are tasked with creating a Python program that simulates the behavior of the `cp` command in Unix-like operating systems. The `cp` command is used to copy files and directories from a source location to a destination location. Your program should be able to handle both individual files and entire directories, and i... | ```python
import os
import shutil
import sys
def copy_file(src, dst):
try:
shutil.copy2(src, dst)
print(f"File '{src}' copied to '{dst}'")
except FileNotFoundError:
print(f"Error: Source file '{src}' not found")
except PermissionError:
print(f"Error: Permission denied for fi... | magicoder | python |
You are given a rectangular cake of size n x n, and you need to cut it into pieces. The cake is to be cut horizontally and vertically to form smaller rectangular pieces. The number of horizontal cuts is represented by the integer h, and the number of vertical cuts is represented by the integer v. The goal is to maximiz... | ```java
public static int maxPiecesWithoutFrosting(int n, int h, int v) {
// Calculate the number of pieces without frosting
int piecesWithoutFrosting = (h + 1) * (v + 1);
// Calculate the total number of pieces
int totalPieces = (n + 1) * (n + 1);
// Return the maximum number of pieces without fros... | magicoder | java |
You are tasked with implementing a database migration script for a course management system. The script should perform the following operations on the "Courses" table:
1. Drop the column "Author_Id" from the table.
2. Rename the column "Author_Id1" to "Author_Id".
3. Alter the data type of the "Author_Id" column to an... | ```sql
-- SQL migration script for the "Courses" table
-- Drop the column "Author_Id" from the table
ALTER TABLE dbo.Courses
DROP COLUMN Author_Id;
-- Rename the column "Author_Id1" to "Author_Id"
EXEC sp_rename 'dbo.Courses.Author_Id1', 'Author_Id', 'COLUMN';
-- Alter the data type of the "Author_Id" column to an in... | magicoder | sql |
You are tasked with creating a program to analyze Java source code and identify certain patterns related to method names and their usage. Specifically, you need to implement a method that processes a given class and its methods to extract information about mutators and accessors.
Your task is to implement the `visitDe... | ```java
import java.util.List;
public class PropertyInfoAnalyzer {
private List<String> errors;
private List<Mutator> mutators;
public void visitDestination(Class<?> type, Method method) {
if (PropertyInfoResolver.MUTATORS.isValid(method)) {
String propertyName = config.getDestinationNameTransformer()... | magicoder | java |
You are tasked with creating a command-line tool for encrypting and decrypting messages using a custom key. The tool should support various options for key generation, encryption, and decryption. Your task is to implement the logic for parsing command-line arguments and handling the encryption and decryption operations... | ```python
import sys
import getopt
def print_help():
# Implementation of the help message
pass
def encrypt(phrase, key, custom_options):
# Implementation of the encryption logic
pass
def decrypt(phrase, key, custom_options):
# Implementation of the decryption logic
pass
def main(argv):
t... | magicoder | python |
You are tasked with creating a Python script that utilizes the `puppetlabs-python_task_helper` module to execute a task using Bolt, a task runner and orchestrator. The task to be executed is named `common::pytask` and it requires passing a parameter `name` with the value `'Bob'` to the task. The script should handle th... | ```python
import subprocess
# Step 1: Install the puppetlabs-python_task_helper module using bolt puppetfile install
install_command = "bolt puppetfile install --boltdir ."
subprocess.run(install_command, shell=True, check=True)
# Step 2: Execute the common::pytask task using Bolt
execute_command = "bolt task run com... | magicoder | python |
You are tasked with implementing a configuration management system for a plugin-based authentication module in a Python application. The provided code snippet is part of this system and involves the registration and retrieval of authentication configuration settings.
The `get_auth_config` function is used to retrieve ... | ```python
class AuthConfig:
def __init__(self, settings):
self.settings = settings
def get_config(config_class):
# Retrieve the configuration settings for the specified class
# This could involve fetching settings from a database or a configuration file
# For demonstration purposes, let's assum... | magicoder | python |
You are given a Python code snippet that is intended to calculate the sum of even numbers entered by the user. However, the code contains a logical error. Your task is to identify the error and fix the code to achieve the intended functionality.
The original code snippet is as follows:
```python
cont = 0
for n in rang... | ```python
soma = 0 # Initialize the variable to store the sum of even numbers
for _ in range(6): # Loop to prompt the user to enter 6 integers
n = int(input('Enter an integer value: ')) # Prompt the user to enter an integer
if n % 2 == 0: # Check if the entered number is even
soma = soma + n # Add ... | magicoder | python |
You are given a Python code snippet that involves the use of NumPy and PyTorch libraries for processing predictions in a machine learning model. Your task is to understand the code and implement a function that achieves the same result using NumPy operations.
The given code snippet performs the following operations:
1... | ```python
import numpy as np
def calculate_left_cosine(left_pred_conf, left_pred_orientation):
left_argmax = np.argmax(left_pred_conf, axis=1)
left_orient = left_pred_orientation[np.arange(len(left_pred_orientation)), left_argmax]
left_cos = left_orient[:, 0]
return left_cos
# Test the function with t... | magicoder | python |
You are tasked with implementing a simplified version of a task execution service in Python. The service will be responsible for executing various tasks and handling their results. The `TaskExecutionService` class will have methods for submitting tasks, executing them, and retrieving their results.
Your task is to imp... | ```python
class TaskExecutionService:
def __init__(self):
self.tasks = []
def submit_task(self, task_function, *args, **kwargs):
self.tasks.append((task_function, args, kwargs))
def execute_tasks(self):
self.results = []
for task in self.tasks:
task_function, ar... | magicoder | python |
You are working on a deployment script for a server using Vagrant and SSH. Your task is to write a Bash script that automates the process of generating an SSH key pair, starting a Vagrant virtual machine, and retrieving the IP address of the server.
Your script should perform the following steps:
1. Generate an RSA SS... | ```bash
#!/bin/bash
# Generate RSA SSH key pair
ssh-keygen -t rsa -f ./id_rsa -q -N ""
# Start Vagrant virtual machine
vagrant up
# Retrieve IP address of the server
IP_SERVER=$(vagrant ssh server -c "ip address show enp0s8 | grep 'inet ' | sed -e 's/^.*inet //' -e 's/\/.*$//'" | tr -d "\n\r")
echo "IP address of t... | magicoder | shell |
You are tasked with creating a custom two-way property view attribute for a time picker in an Android application. The attribute should be responsible for synchronizing the selected hour of the time picker with a model property. The time picker is represented by the class `TimePicker`, and the model property is of type... | ```java
import org.robobinding.property.ValueModel;
import org.robobinding.viewattribute.ViewListenersAware;
import org.robobinding.viewattribute.property.TwoWayPropertyViewAttribute;
public class TwoWayCurrentHourAttribute implements TwoWayPropertyViewAttribute<TimePicker, Integer>, ViewListenersAware<TimePickerListe... | magicoder | java |
You are tasked with implementing a custom scheduler for a task management system. The scheduler should be able to handle task scheduling on different threads based on the availability of resources. Your task is to create a class that manages the scheduling of tasks using RxJava's scheduling capabilities.
You are provi... | ```java
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
public class CustomScheduler {
private Scheduler mainThreadScheduler;
private Scheduler computationThreadScheduler;
private Scheduler ioThreadScheduler;
public Cu... | magicoder | java |
You are tasked with implementing a Python function that calculates the coherence of a given matrix. Coherence is a measure of the linear dependence between columns of a matrix and is widely used in signal processing, statistics, and machine learning. The coherence of a matrix is defined as the maximum absolute value of... | ```python
import numpy as np
def calculate_coherence(mat: np.ndarray) -> float:
"""
Calculate the coherence of the input matrix.
Parameters
----------
mat : (N, M) np.ndarray
The input matrix :math:`\boldsymbol{A}`.
Returns
-------
float
Coherence value of the input ma... | magicoder | python |
You are tasked with implementing a Python class that represents a neural network model. The class should have an `__init__` method that initializes the model with default values for the number of input channels and the name of the encoder. Your task is to complete the implementation of the `NeuralNetwork` class by addi... | ```python
class NeuralNetwork:
def __init__(
self,
in_channels: int = 3,
encoder_name: str = "simplenet",
):
self.in_channels = in_channels
self.encoder_name = encoder_name
def forward(self, input_tensor):
# Placeholder for the forward pass through the neural... | magicoder | python |
You are tasked with creating a program that processes CSS (Cascading Style Sheets) to perform specific transformations. Your program should implement three operations on the input CSS string:
1. Replace all instances of ";}" with "}".
2. Remove any leading zeros before units (e.g., 0px should become px, 0pt should bec... | ```python
import re
def process_css(css):
# Replace instances of ";}" with "}"
css = css.replace(";}", "}")
# Remove leading zeros before units
css = re.sub(r'([\s:]0)(px|pt|%|em)', r'\1', css)
# Remove comments from CSS
css = re.sub(r'/\*.*?\*/', '', css, flags=re.DOTALL)
return css
# ... | magicoder | python |
You are tasked with implementing a ball detection algorithm using Python and OpenCV. The goal is to create a program that can identify and track a ball in a video stream. The program should be able to detect the ball's position and draw a bounding box around it.
You are provided with a partial code snippet that includ... | ```python
# Import necessary libraries
import sys
import time
import numpy as np
from scipy.ndimage import filters
import imutils
import cv2
import roslib
# Function to preprocess the frame
def preprocess_frame(frame):
# Convert the frame to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Apply ... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.