query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Python function that monitors the status of services and triggers a handler function if the service status is not 'running'. The function `watchdog_handler` takes a `job` object as its input parameter. The `job` object contains information about the service to be monitored. The function u...
```python def watchdog_handler(job): import asyncio loop = job.atyourservice.server.loop service = job.service if str(service.model.data.status) != 'running': # Trigger the handler function or perform necessary actions # Example: Triggering a handler function asyncio.ensure_futur...
magicoder
python
You are tasked with implementing a graph data structure and its associated algorithms. The graph is represented using an adjacency list and supports directed edges. You need to implement the functionality to load the graph from a JSON file and perform edge removal operations. Additionally, you must ensure that the modi...
```python import json class DiGraph: def __init__(self): self.adj_list = {} self.modification_count = 0 def add_edge(self, src, dest, weight): if src not in self.adj_list: self.adj_list[src] = [] self.adj_list[src].append((dest, weight)) self.modification_co...
magicoder
python
You are tasked with creating a program that simulates a simple file system. The file system will consist of directories and files, and you need to implement basic operations such as creating directories, creating files, listing the contents of a directory, and navigating through the file system. Your task is to implem...
```python class FileSystem: def __init__(self): self.root = {'/': []} self.current_path = '/' def create_directory(self, path): if path.endswith('/'): path = path[:-1] dirs = path.split('/') current = self.root for d in dirs[1:]: if d not ...
magicoder
python
You are working on a project that involves integrating various components using PHP and its related libraries. As part of this project, you need to write a function that performs dependency injection using the Nette\DI\Container and Doctrine\ORM\EntityManager classes. The function should override the default behavior o...
```php use Nette\DI\Container; use Doctrine\ORM\EntityManager; function overrideDependency(Container $container, EntityManager $entityManager, string $dependency): void { $container->addService('specificDependency', $entityManager->get($dependency)); $container->addService('', $container->getService('specificD...
magicoder
php
You are working on a network management system for controlling and monitoring devices in a network. The system interacts with various devices and needs to handle events related to port status changes and role requests. You are tasked with implementing a component that processes these events and takes appropriate action...
```java public class DeviceEventManager { public void portStatusChanged(DeviceId deviceId, VirtualPortDescription portDesc) { // Process the port status change event and take necessary actions // Example: Log the event, update port status in the system, trigger related actions System.out.pri...
magicoder
java
You are tasked with creating a Bash script that simulates a simple file management system. Your script should be able to perform basic file operations such as creating, deleting, and listing files and directories. Additionally, it should support navigating through directories and displaying the current working director...
```bash #!/bin/bash create_file() { if [ -e "$1" ]; then echo "File $1 already exists." else touch "$1" echo "File $1 created." fi } create_dir() { if [ -d "$1" ]; then echo "Directory $1 already exists." else mkdir "$1" echo "Directory $1 created." ...
magicoder
shell
You are tasked with creating a CSS class management system for a web development project. The system should allow for the addition, removal, and retrieval of CSS classes associated with HTML elements. Additionally, the system should support the ability to set and retrieve specific style properties for individual classe...
```javascript class CSSManager { constructor() { this.classes = {}; } addClass(className) { if (!this.classes[className]) { this.classes[className] = {}; } } removeClass(className) { if (this.classes[className]) { delete this.classes[className]; } } hasClass(className) {...
magicoder
javascript
You are tasked with implementing a job scheduling system that can handle concurrent updates to the list of jobs. The system uses a locking mechanism to ensure that only one update operation can be performed at a time. Your task is to design a class that manages the job updates and ensures thread safety. Your class sho...
```python import threading import logging class JobScheduler: def __init__(self): self.update_jobs_lock = threading.Lock() def update_jobs(self, req): """ Update jobs. """ self.update_jobs_lock.acquire() resp = None try: logger = logging.getL...
magicoder
python
You are tasked with creating a Python program that simulates a simple login system. The program should prompt the user to enter their username and password. If the entered credentials match the predefined values, the program should grant access and display a welcome message. However, if the credentials do not match, th...
```python import time def login(): username = "admin" password = "password123" attempts = 0 locked_out = False while attempts < 3: if not locked_out: entered_username = input("Enter username: ") entered_password = input("Enter password: ") if entered_us...
magicoder
python
You are tasked with creating a custom logging system for a machine learning project using Python. The logging system should integrate with PyTorch Lightning and utilize the `hydra`, `torch`, `torchmetrics`, and `omegaconf` libraries. Additionally, the system should make use of custom utility functions and logging capab...
```python import torch from omegaconf import DictConfig from pytorch_lightning import LightningModule from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from torchmetrics import Accuracy, MetricCollection from ..optimizer.scheduler import create_scheduler from ..utils import utils from...
magicoder
python
You are tasked with implementing a function that can parse and extract information from an HTML code snippet. The HTML code snippet represents a section of a web page layout, and your function should be able to identify and extract the column layout structure from the given HTML. Write a function `extractColumnLayout(...
```python from bs4 import BeautifulSoup from typing import List def extractColumnLayout(htmlCode: str) -> List[str]: column_layout = [] soup = BeautifulSoup(htmlCode, 'html.parser') div_elements = soup.find_all('div', class_=True) for div in div_elements: classes = div.get('class') if c...
magicoder
python
You are tasked with implementing a custom user model for a web application. The user model should have specific fields and methods to handle user permissions. You are provided with a code snippet that includes a list of required fields and two methods: `__str__`, `has_perm`, and `has_module_perms`. The `__str__` metho...
```python from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None, **extra_fields): if not email: raise ValueError('The Ema...
magicoder
python
You are given two arrays `f` and `g` of floating-point numbers. The code snippet provided is a part of a function that performs some operations on these arrays. Your task is to complete the function by implementing the remaining part. The function should perform the following steps: 1. Assert that the first element of...
```rust fn process_arrays(f: &[f64], g: &[f64]) { assert!(f[0] == 0.0); assert!(g[0] == 0.0); let n = std::cmp::max(f.len(), g.len()); let mut m = 1; while m < n { m <<= 1; } // Additional code can be added here to complete the function } ``` In the provided solution, the function `p...
magicoder
rust
You are tasked with implementing a GUI library that allows setting a default font for all widgets added to the GUI. The library should provide a method to set the default font, and any widget added to the GUI should use this default font unless explicitly overridden. Your task is to design and implement the necessary c...
```java import java.awt.Font; // Class representing the GUI library public class GUI { private Font defaultFont; // Method to set the default font public void setDefaultFont(Font font) { this.defaultFont = font; } // Widget class using the default font unless overridden public class W...
magicoder
java
You are tasked with implementing a Python function that processes a series of version control system status lines and returns a tuple containing the number of changes, the number of lines ahead, the number of lines behind, and the number of conflicts. The function should take a list of strings as input, where each str...
```python import re def process_status_lines(status_lines): changes = 0 ahead = 0 behind = 0 conflicts = 0 for line in status_lines: m = re.match(r'([A-Z])\s?(\d*)\s?(\d*)', line) if m: if m.group(2): ahead += int(m.group(2)) if m.group(3): ...
magicoder
python
You are tasked with implementing a function that processes input arguments and keyword arguments, while also handling and logging any unused arguments. The function should take into account the possibility of receiving a namedtuple as the first argument and should appropriately unpack its elements. Additionally, the fu...
```python import logging def process_and_invoke(hpc_fn, include_args, include_kwargs, runtime_name, namedtuple_data, *args, **kwargs): clean_args = [args[i] for i in include_args if i < len(args)] clean_kwargs = {k: v for k, v in kwargs.items() if k in include_kwargs} nouse_args = [i for i in range(len(arg...
magicoder
python
You are tasked with implementing a Vue.js component that enforces the restriction of allowing only synchronous functions to be used as getters. In Vue.js, getters are functions used to compute derived state based on the store state. Your task is to create a custom Vue.js plugin that validates and enforces this restrict...
To solve this problem, you can create a custom Vue.js plugin that intercepts the definition of getters and checks if any asynchronous functions are used. Here's a possible solution using Vue.js and Vuex: ```javascript // Define the custom plugin const enforceSyncGettersPlugin = store => { const { getters } = store._...
magicoder
javascript
You are tasked with implementing a function to find the length of the Longest Common Subsequence (LCS) of two given strings. The Longest Common Subsequence is the longest sequence of characters that appear in the same order in both strings, but not necessarily consecutively. You are given the following code snippet as...
```cpp #include <iostream> #include <string> int LCS(const char *str1, const char *str2) { int m = strlen(str1); int n = strlen(str2); int dp[m + 1][n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) dp[i][j] = 0; ...
magicoder
cpp
You are tasked with implementing a command-line argument parser for a natural language processing (NLP) model training script. The script accepts various command-line arguments to configure the training process. Your task is to write a function that parses these arguments and returns a dictionary containing the parsed ...
```python def parse_arguments(args): parsed_args = {} current_key = None for arg in args: if arg.startswith("--"): current_key = arg[2:] parsed_args[current_key] = "" elif current_key is not None: if arg.endswith("\\"): parsed_args[current_...
magicoder
python
You are tasked with implementing a program that reads a series of binary numbers from the standard input, converts each binary number to its hexadecimal representation, and then prints the hexadecimal representation to the standard output. Your program should take each binary number, convert it to its hexadecimal equi...
```python import sys for line in sys.stdin: print("{0:02x}".format(int(line.strip(), 2))) ``` The solution reads each line from the standard input using a for loop. It then converts the binary number to its decimal equivalent using `int(line.strip(), 2)`, where `line.strip()` removes any leading or trailing whites...
magicoder
python
You are tasked with implementing a Python function that processes a dataset containing comma-separated values and extracts specific attributes for further analysis. The dataset is stored in a file named `ppd.txt`, and each line of the file represents a record with attributes separated by commas. The function should rea...
```python from typing import List def process_data(file_name: str) -> List[List[float]]: test_data = [] with open(file_name, 'r') as file: for line in file: attr = line.strip().split(',') test_data.append(list(map(float, attr[:31]))) return test_data ``` The `process_data` f...
magicoder
python
You are given a Python code snippet that processes sequencing data from DNA reads. The code iterates through a list of sequencing records called `normal`, and for each record, it checks if the record is supplementary or unmapped. If the record meets these conditions, it skips to the next record. Otherwise, it determine...
```python class SequencingRecord: def __init__(self, is_supplementary, is_unmapped, pos, mpos, cigartuples): self.is_supplementary = is_supplementary self.is_unmapped = is_unmapped self.pos = pos self.mpos = mpos self.cigartuples = cigartuples def extract_left_clips(normal):...
magicoder
python
You are given a class `Point` with the following attributes and methods: ```java public class Point { private int x_6; private int y_6; private int x_14; private int y_14; public Point(int x, int y) { this.x_6 = x; this.y_6 = y; } public void copy_from_6_to_14() { ...
```java public class Point { private int x_6; private int y_6; private int x_14; private int y_14; public Point(int x, int y) { this.x_6 = x; this.y_6 = y; } public void copy_from_6_to_14() { x_14 = x_6; y_14 = y_6; } public double distance_between_...
magicoder
java
You are tasked with implementing a TypeScript class that extends a base API class and provides methods for registering routes and uploading images using the Express framework. You need to create a `CommonApi` class that extends the `BaseApi` class and implements the following methods: 1. `constructor()`: The construct...
```typescript import { BaseApi } from '../BaseAPI'; import { Application, Request, Response } from 'express'; export class CommonApi extends BaseApi { constructor() { super(); // Initialize any common API configurations here } register(express: Application): void { // Register rout...
magicoder
typescript
You are tasked with creating a Python function that filters a list of file paths based on inclusion and exclusion patterns. The function should take in a list of file paths, an inclusion pattern, and an exclusion pattern, and return a filtered list of file paths based on these patterns. The function signature should b...
```python from typing import List import fnmatch def filter_file_paths(file_paths: List[str], include: str, omit: List[str]) -> List[str]: included_files = [] for file_path in file_paths: if any(fnmatch.fnmatch(file_path, pattern) for pattern in include.split(',')): if not any(fnmatch.fnmat...
magicoder
python
You are given a scenario where a group of members needs to be assigned to different tasks, each with a certain cost associated with it. Your task is to find the minimum cost assignment of members to tasks, ensuring that each member is assigned to exactly one task and each task is assigned to exactly one member. You ar...
```cpp #include <iostream> #include <vector> #include <limits> using namespace std; struct edge { int to, flow, cap; double cost; edge(const int _to, const int _flow, const int _cap, const double _cost) : to(_to), flow(_flow), cap(_cap), cost(_cost) {} }; double dist[N]; vector<int> g[N]; vector<e...
magicoder
cpp
You are tasked with implementing a method to generate random byte values within a specified range. The method should throw an exception if the maximum value provided is less than or equal to 0. Your task is to write a Java method that fulfills these requirements. Write a Java method `generateRandomByteInRange(int maxV...
```java import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; public class RandomByteGenerator { public byte generateRandomByteInRange(int maxValue) { if (maxValue <= 0) { throw new IllegalArgumentException("Max value must be greater than 0"); } return (b...
magicoder
java
You are tasked with creating a Python class that manages project contracts for a company. The class should include methods for creating a new project, retrieving a list of contracts associated with a project, and testing the functionality of the class. Your task is to implement the `ProjectManager` class with the foll...
```python import requests class ProjectManager: def __init__(self, moco): self.moco = moco def create_project(self, project_name): create_project_url = "https://example.com/api/create_project" payload = {"project_name": project_name} response = requests.post(create_project_url,...
magicoder
python
You are tasked with creating an Ansible playbook to automate the setup of a secure server environment. The playbook should configure SSH and WireGuard settings based on the provided variables. Your task is to write an Ansible playbook that accomplishes this task. The playbook should perform the following tasks: 1. Set...
```yaml --- - name: Configure Secure Server Environment hosts: localhost gather_facts: false tasks: - name: Set SSH configuration community.crypto.ssh_config: option: Port value: "{{ ssh_port }}" vars: ssh_port: "{{ ssh_port }}" - name: Configure SSH clients ...
magicoder
yaml
You are tasked with implementing a class for managing data fields and relation fields in a semantic data management system. The data fields store specific data values, while the relation fields define relationships between different classes. Your task is to create a Python class that can handle the creation and managem...
```python class DataField: def __init__(self, name, rule, semantic_manager): self.name = name self.rule = rule self.semantic_manager = semantic_manager # Additional methods for managing data fields can be added here class RelationField: def __init__(self, name, rule, inverse_of, s...
magicoder
python
You are tasked with implementing a Python class method that converts a given binary tree node into an ASDF representation. The binary tree node has attributes `offset`, `size`, and `name`. The ASDF representation is a dictionary containing the node's `offset`, `size`, and `name` if it is not `None`. You need to comple...
```python class BinaryTreeNode: requires = [] @classmethod def to_tree(cls, node, ctx): # to ASDF representation d = {} d['offset'] = node.offset d['size'] = node.size if node.name is not None: d['name'] = node.name return d ``` In the solution, the `to_...
magicoder
python
You are tasked with creating a Python program that simulates a simple banner printing system. The program should display a banner when executed and handle user interruptions gracefully. Your program should consist of the following components: 1. `print_banner()`: A function that prints a banner when called. The banne...
```python import sys import time def print_banner(): print("*" * 30) print("Welcome to Our Application") print("*" * 30) def main(): print_banner() try: # Your main program logic goes here time.sleep(5) # Simulating some program execution print("Program execution completed...
magicoder
python
You are tasked with implementing a generic class called `MinMaxStack` that supports the following operations: 1. `push(T element)`: Adds the given element to the top of the stack. 2. `pop()`: Removes the element from the top of the stack and returns it. If the stack is empty, this operation should return null. 3. `getM...
```java import java.util.Stack; public class MinMaxStack<T extends Comparable<T>> { private Stack<T> stack; private Stack<T> minStack; private Stack<T> maxStack; public MinMaxStack() { stack = new Stack<>(); minStack = new Stack<>(); maxStack = new Stack<>(); } public ...
magicoder
java
You are tasked with implementing a stack trace unification algorithm. A stack trace is a list of method calls in the order they were executed, typically used for debugging purposes. In this problem, you are given a snippet of code that is part of a larger algorithm for unifying stack traces from managed and native code...
To complete the unification algorithm, you can use the following code as a starting point: ```csharp List<string> UnifyStackTraces(List<string> managedStackTrace, List<string> nativeStackTrace) { List<string> unifiedStackTrace = new List<string>(); int managedFrame = 0; for (int temp = 0; temp < managedSt...
magicoder
csharp
You are tasked with implementing a method to extend the functionality of a RichTextBox control in a C# application. The RichTextBoxExtensions class provides a starting point for this task. Your goal is to add a method that will highlight all occurrences of a specified word within the RichTextBox control. You need to i...
```csharp using System.Drawing; using System.Windows.Forms; namespace POSH_Toolbelt { public static class RichTextBoxExtensions { public static void HighlightWord(this RichTextBox richTextBox, string word) { int startIndex = 0; while (startIndex < richTextBox.TextLength)...
magicoder
csharp
You are tasked with creating a simple text editor application using Python and PyQt. Your task is to implement a class that inherits from QMainWindow and includes a QVBoxLayout and a QTextEdit widget. The QVBoxLayout will be used to arrange the QTextEdit widget within the main window. Your task is to complete the impl...
```python import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QTextEdit, QAction, QFileDialog from PyQt5.QtGui import QIcon class TextEditor(QMainWindow): def __init__(self): super(TextEditor, self).__init__() self.initUI() def initUI(self): self.layout = QVB...
magicoder
python
You are tasked with implementing a function to update a todo item in a todo list application. The function should take the todo ID and a payload containing the updated title and description of the todo item. After updating the todo item, the function should perform certain assertions to ensure the correctness of the up...
```python class Todo: def __init__(self, title, description): self.title = title self.description = description def update_todo(todo_id: int, payload: dict) -> Todo: # Assume todos is a list of Todo objects todo = todos[todo_id] todo.title = payload['title'] old_description = todo.d...
magicoder
python
You are tasked with implementing a class that manages a collection of results from a series of operations. The class should provide methods to add new results, retrieve the average of all results, and reset the collection. You are given a code snippet for inspiration, which includes a protected property `$results` to ...
```php /** * Class ResultManager * Manages a collection of results and provides methods to manipulate the collection. */ class ResultManager { /** * @var array */ protected $results = []; /** * Constructor. * Initializes the ResultManager. */ public function __construct() ...
magicoder
php
You are tasked with creating a class that manages the relationship between fathers and their children. The class has a method `createChild` that takes two parameters: `father` and `name`. It first checks if the `father` exists, and if not, it throws an error. If the `father` exists, it creates a new child with the give...
```javascript class FatherChildManager { constructor(childRepo) { this.childRepo = childRepo; } createChild(father, name) { if (!father) { throw new Error('Father not found!'); } const child = this.childRepo.create({ father, name }); return this.childRepo.save(child); } } ``` In the ...
magicoder
javascript
You are given a set of 2D points represented by their x and y coordinates. Your task is to write a function to find the closest pair of points in the set. The distance between two points is calculated using the Euclidean distance formula: distance = sqrt((x2 - x1)^2 + (y2 - y1)^2). You are provided with a code snippet...
```cpp #include <iostream> #include <vector> #include <cmath> #include <algorithm> struct Point { int x, y; }; struct PairOfPointsWithDistance { Point p1, p2; double distance; }; double Distance(const Point& a, const Point& b) { return sqrt(pow(b.x - a.x, 2) + pow(b.y - a.y, 2)); } PairOfPointsWithD...
magicoder
cpp
You are tasked with creating a Python function that parses a Django URL configuration file and extracts the URLs mapped to views. The URL configuration file follows the standard Django format, where URLs are mapped to views using the `urlpatterns` list. You need to implement a function `extract_urls` that takes the UR...
```python from typing import List import re def extract_urls(url_config: str) -> List[str]: urls = re.findall(r"path\(['\"](.*?)['\"].*?\)", url_config) return urls ``` The `extract_urls` function uses the `re.findall` method to extract the URLs mapped to views from the given URL configuration file. The regul...
magicoder
python
You are given three integers: n, a, and b. Your task is to find the sum of all integers from 1 to n (inclusive) whose digit sum falls within the range [a, b] (inclusive). The digit sum of a positive integer is the sum of its digits. For example, the digit sum of 123 is 1 + 2 + 3 = 6. Write a function `sum_of_digit_sum...
```python def sum_of_digit_sums(n: int, a: int, b: int) -> int: ans = 0 for i in range(1, n+1): str_i = str(i) digit_sum = 0 for j in range(len(str_i)): digit_sum += int(str_i[j]) if a <= digit_sum <= b: ans += i return ans ```
magicoder
python
You are tasked with creating a language detection system using the langid.py library. The system should take a list of texts as input and identify the language of each text. However, the identified language should be checked against a whitelist of allowed languages before being output. If the identified language is in ...
```python from typing import List from langid.langid import LanguageIdentifier from aleph.core import language_whitelist def detect_languages(texts: List[str]) -> List[str]: identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True) detected_languages = [] for text in texts: lang...
magicoder
python
You are tasked with implementing a Python function that generates variable font names based on the given input. A variable font is a font file that contains multiple variations of a typeface, allowing for a wide range of font styles to be generated from a single file. The function should take in a list of discrete axes...
```python from typing import List, Dict, Union, Optional import os import itertools class RangeAxisSubsetDescriptor: def __init__(self, name): self.name = name class VariableFontDescriptor: def __init__(self, name, axisSubsets): self.name = name self.axisSubsets = axisSubsets def gene...
magicoder
python
You are given a log file containing a series of transactions in the format "operation amount", where the operation can be either "credit" or "debit", and the amount is an integer representing the transaction amount. Each line in the log file represents a single transaction. Your task is to process the log file and calc...
```python def process_transactions(input_file: str, output_file: str) -> None: cur_balance = 0 with open(input_file, 'r') as log_file, open(output_file, 'w') as out: for line in log_file: l = line.strip().split() if l[0] == 'credit': cur_balance += int(l[1]) ...
magicoder
python
You are tasked with developing a command-line tool for importing airport data from a JSON file into a database. The tool should support parallel insertion of data using multiple worker threads. Your task is to implement the logic for parsing command-line arguments and managing the insertion workers. You need to implem...
```python import argparse import json import threading from queue import Queue class AirportImporter: def __init__(self, file_path, num_workers): self.file_path = file_path self.num_workers = num_workers self.work_queue = Queue() def import_airports(self): # Read airport data f...
magicoder
python
You are tasked with implementing a multi-threaded file downloader in Python. The given code snippet is a part of the class that manages the file downloading process. The class has attributes for thread number, queue size, file size, and current position in the file. Your task is to complete the implementation of the `d...
```python from queue import Queue import threading import requests class FileDownloader: def __init__(self, thread_num, queue_size): self.thread_num = thread_num self.queue = Queue(queue_size) self.file_size = self._content_length() self.position = 0 # 当前的字节偏移量 def _content_le...
magicoder
python
You are tasked with implementing a performance metrics calculation function for a machine learning model. The function takes in the actual test data labels, predicted labels, a test dataframe, a task type, and a data type as input. Your goal is to create a function that calculates and prints performance metrics based o...
```python import numpy as np from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, mean_absolute_error, mean_squared_error def get_performance_metrics(actual_labels, predicted_labels, test_dataframe, task_type, data_type): if task_type == "classification": accuracy = accuracy...
magicoder
python
You are tasked with implementing a multi-threaded video processing system. The system is designed to process a series of video objects concurrently using a queue and worker threads. Each video object is represented by a tuple containing the video object itself and a transaction ID. The worker threads will dequeue tasks...
```python import threading def process_videos(queue, logger, worker, video_obj_arr, txnId): # Queue the video objects and transaction IDs for i in range(len(video_obj_arr)): logger.info('Queueing {}'.format(i)) queue.put((video_obj_arr[i], txnId)) # Wait for all tasks to be processed q...
magicoder
python
You are given the definition for a singly-linked list in Python: ```python # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next ``` You are also given the file name and the number of stars (1-10) for a specific LeetCode problem....
```python def is_palindrome(head: ListNode) -> bool: # Find the middle of the linked list slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next # Reverse the second half of the linked list prev = None while slow: temp = slow.next ...
magicoder
python
You are tasked with implementing a custom EnumField class that extends the functionality of the Peewee ORM's basic types. The EnumField should allow the user to define a set of choices for a field, similar to how enums work in other programming languages. Your task is to create the EnumField class and ensure that it in...
```python from peewee import Field, CharField, ValidationError class EnumField(Field): def __init__(self, choices, *args, **kwargs): super().__init__(*args, **kwargs) self.choices = choices def db_value(self, value): if value not in self.choices: raise ValidationError(f"Val...
magicoder
python
You are given a binary tree data structure and a function `sizeTree(node)` that calculates the size of the tree. The size of a tree is defined as the total number of nodes in the tree. The `sizeTree` function takes the root node of the tree as input and returns the size of the tree. Your task is to implement a Python ...
```python class Node: def __init__(self, data): self.data = data self.left = None self.right = None def sizeTree(node): if node is None: return 0 else: return (sizeTree(node.left) + 1 + sizeTree(node.right)) # Driver program to test above function root = Node(1) roo...
magicoder
python
You are tasked with implementing a custom namespace and using it within a C++ program. The namespace should encapsulate a set of functions and classes related to a specific domain. Your goal is to create a namespace called `math_operations` and define a function within it to calculate the factorial of a given integer. ...
```cpp // Custom namespace for math operations namespace math_operations { // Function to calculate the factorial of a given integer int factorial(int n) { if (n == 0 || n == 1) { return 1; } else { int result = 1; for (int i = 2; i <= n; i++) { ...
magicoder
cpp
You are tasked with creating a program that analyzes a given text file to count the occurrences of each unique word. Your program should ignore punctuation and consider words regardless of their case (i.e., "Hello" and "hello" should be considered the same word). Additionally, the program should output the top N most f...
```python import string def count_words(filename, n): word_freq = {} with open(filename, 'r') as file: for line in file: line = line.lower().translate(str.maketrans('', '', string.punctuation)) words = line.split() for word in words: if word in w...
magicoder
python
You are tasked with creating a Python function that generates a Directed Acyclic Graph (DAG) for a workflow management system. The function should take in a dictionary of default arguments and a list of task definitions, and return a DAG object that represents the workflow. The default arguments dictionary contains ke...
```python from datetime import datetime from airflow import DAG from airflow.operators.python_operator import PythonOperator def generate_dag(default_args: dict, task_definitions: list) -> DAG: dag_id = 'example_valohai_dag' dag = DAG(dag_id, default_args=default_args, schedule_interval=None) task_objects...
magicoder
python
You are tasked with creating a Python function that can compress or decompress a file based on the specified compression algorithm. The function should support two compression algorithms: "gzip" and "bz2". If the compression algorithm is "gzip", the function should compress the file using the gzip algorithm. If the com...
```python import gzip import bz2 def compress_decompress_file(compression, filepath_or_buffer, mode): if compression == "gzip": if isinstance(filepath_or_buffer, str): with open(filepath_or_buffer, mode) as file: if mode.startswith('r'): return gzip.GzipFile(...
magicoder
python
You are tasked with implementing a simple test case framework for a custom INI file parser in Swift. An INI file is a configuration file format used to store settings for software applications. Each setting is represented by a key-value pair within a section. For example: ``` [Database] Server = localhost Port = 3306 ...
```swift import XCTest class INIParserTests: XCTestCase { func testParsingValidINIFile() { let iniParser = INIParser() let iniData = """ [Database] Server = localhost Port = 3306 [User] Name = John Doe """ let settings...
magicoder
swift
You are tasked with implementing a generic asynchronous trait for a polling mechanism in Rust. The trait `Pollable` represents an asynchronous operation that can be polled for readiness. Your goal is to implement the `poll_ready` method for a specific type that implements the `Pollable` trait. The `Pollable` trait is ...
```rust impl<InnerType: Pollable> Pollable for CustomPollable<InnerType> { type Error = InnerType::Error; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner.poll_ready(cx) } } ``` In the solution, we implement the `poll_ready` method for the `CustomPoll...
magicoder
rust
You are tasked with implementing a Python function that performs a cubic fit to a set of data points using the method of least squares. The function should take two input arrays, `x` and `y`, representing the independent and dependent variables, and return the coefficients of the cubic polynomial that best fits the dat...
```python import numpy as np def ucurve_fit(reg_cubic, x, y): X = reg_cubic(x) params = np.linalg.lstsq(X, y, rcond=None)[0] return params ``` In the solution, the `ucurve_fit` function uses the provided `reg_cubic` function to generate the regression matrix `X` for the cubic polynomial. It then uses the ...
magicoder
python
You are tasked with implementing a simple text editor that supports the following operations: 1. Create a new file and open it for editing. 2. Insert text at the current cursor position. 3. Delete the character at the current cursor position. 4. Move the cursor left or right within the text. 5. Save the file and exit ...
```python class TextEditor: def __init__(self): self.text_buffer = "" self.cursor_position = 0 def create_file(self, filename: str) -> str: self.text_buffer = "" self.cursor_position = 0 return f"File '{filename}' has been created and opened for editing." def insert...
magicoder
python
You are tasked with creating a script to automate the deployment and testing of Android applications using ADB (Android Debug Bridge). The script should stop the currently running app in a specified namespace, then start a new instance of the app in the same namespace and activity. Given the provided code snippet, cre...
```bash #!/bin/bash # Check if required environment variables are set if [ -z "$APP_NAMESPACE" ] || [ -z "$ADB" ] || [ -z "$ADB_DEVICE" ] || [ -z "$APP_ACTIVITY" ]; then echo "Error: Required environment variables not set" exit 1 fi # Print message indicating stopping the app in the specified namespace echo "Stop...
magicoder
shell
You are working on a machine learning project and need to implement a function to build histograms for gradient boosting decision trees. The function `build_func` takes in several parameters including `sample_indices`, `binned_feature`, `ordered_gradients`, `ordered_hessians`, and `hist`. The `sample_indices` represent...
```python import numpy as np # Define the custom data type for the histogram HISTOGRAM_DTYPE = np.dtype([('count', np.uint32), ('sum_gradients', np.float64), ('sum_hessians', np.float64)]) # Define the custom data type for gradients and Hessians G_H_DTYPE = np.float64 def build_func(bin_id, sample_indices, binned_fe...
magicoder
python
You are tasked with creating a script to organize and process files in a directory. Your script should perform the following operations: 1. Create two new directories named "toto" and "titi". 2. Place all files from the current directory into the "toto" and "titi" directories. 3. Remove the "toto" and "titi" directori...
```bash #!/bin/bash # Create directories mkdir toto mkdir titi # Move files to directories for file in *; do if [ -f "$file" ]; then mv "$file" toto mv "$file" titi fi done # Remove directories rm -r toto titi ``` The script first creates the "toto" and "titi" directories using the `mkdir` command. Then...
magicoder
shell
You are tasked with creating a script to automate the process of packaging and submitting a library to the Haxelib repository. Haxelib is the package manager for the Haxe programming language, and it allows developers to share and distribute libraries. The provided code snippet is a part of the automation process, but ...
```bash #!/bin/bash # Check if edge.zip exists and remove it if [ -f edge.zip ]; then rm edge.zip echo "Previous edge.zip file removed" fi # Create a new zip file containing specific files and directories if zip -r edge.zip src test demo extraParams.hxml haxelib.json LICENSE README.md -x "*/\.*"; then echo "edg...
magicoder
shell
You are given an array `a` of `n` integers. Your task is to find the maximum sum of a subarray with the constraint that you cannot take two consecutive elements from the array. Write a function `maxNonAdjacentSum` that takes in an array of integers `a` and its size `n` as input and returns the maximum sum of a subarra...
```cpp int maxNonAdjacentSum(int a[], int n) { if (n <= 0) return 0; int incl = a[0]; // Maximum sum including the previous element int excl = 0; // Maximum sum excluding the previous element for (int i = 1; i < n; i++) { // Current maximum excluding i int newExcl = (incl...
magicoder
cpp
You are tasked with implementing a Java method to determine the classification of a given floating-point number based on IEEE 754 standard. The IEEE 754 standard defines the format for representing floating-point numbers in computers, including special values such as positive infinity, negative infinity, and NaN (Not a...
```java package org.netlib.lapack; public final class Ieeeck { public static String classifyFloatingPoint(float number) { int classBits = Float.floatToRawIntBits(number) & 0x7F800000; int significandBits = Float.floatToRawIntBits(number) & 0x007FFFFF; if (classBits == 0x7F800000) { ...
magicoder
java
You are working on a script to download and update time zone files for a system. The script needs to download three big-endian files from a given base URL and store them in a temporary directory. The files to be downloaded are `metaZones.res`, `timezoneTypes.res`, and `windowsZones.res`. You need to write a function th...
```python import os import subprocess def downloadBigEndianFiles(baseURL, tmpDir): be_dir = os.path.join(tmpDir, 'be') os.makedirs(be_dir, exist_ok=True) subprocess.run(['curl', '-OLs', f'{baseURL}/be/metaZones.res'], cwd=be_dir) subprocess.run(['curl', '-OLs', f'{baseURL}/be/timezoneTypes.res'], ...
magicoder
python
You are tasked with implementing a custom hook in a React application that handles the conversion of a numerical value to a binary representation. The hook should update the binary representation whenever the input value changes. Your task is to complete the implementation of the custom hook `useBinaryConverter` by fil...
```javascript import { useState, useEffect } from 'react'; const useBinaryConverter = (initialValue, onChange) => { const [value, setValue] = useState(initialValue); const [valueBn, setValueBn] = useState(''); useEffect(() => { const valueBn = (value >>> 0).toString(2); // Convert value to binary representa...
magicoder
javascript
You are tasked with creating a reinforcement learning environment for a simple game. The game environment is represented by a Python class `venv`, which provides the following methods: - `reset()`: Resets the environment and returns the initial observation. - `step(action)`: Takes an action as input and returns the new...
```python def play_game(venv, model, num_episodes): total_rewards = 0 for _ in range(num_episodes): obs = venv.reset() episode_reward = 0 done = False while not done: action, _states = model.predict(obs, deterministic=True) obs, reward, done, _ = venv.step...
magicoder
python
You are tasked with implementing a class to manage the actions and signals of a sequence object context. The context has four possible states represented by the enum `SequenceObjectContext`, and for each state, there is a corresponding action and signal to be managed. The actions are `doNotTranslateAction`, `translateA...
```cpp #include <QObject> enum class SequenceObjectContext { TS_DoNotTranslate, TS_AnnotationsOrSelection, TS_SetUpFramesManually, TS_ShowAllFrames }; class SequenceContextManager : public QObject { Q_OBJECT public: QCheckBox* doNotTranslateAction; QCheckBox* translateAnnotationsOrSelecti...
magicoder
cpp
You are tasked with creating a PHP class that manages a simple inventory system for an e-commerce platform. The class should handle adding, updating, and retrieving product information. Additionally, it should be able to calculate the total value of the inventory. Your task is to implement the `Inventory` class with t...
```php class Inventory { private $products = []; public function addProduct($name, $price, $quantity) { if (isset($this->products[$name])) { $this->products[$name]['price'] = $price; $this->products[$name]['quantity'] += $quantity; } else { $this->products[$n...
magicoder
php
You are tasked with creating a program that processes command-line arguments to perform various mathematical operations. The program should accept the following command-line options: - `--val`: Indicates that the subsequent arguments are to be used for value calculations. - `-x <value>`: Specifies the value of x for t...
```python import argparse def calculate_result(args): if args.val: result = (args.x * args.y) + (args.s - args.t) else: result = (args.x + args.y) * (args.s - args.t) return result def main(): parser = argparse.ArgumentParser(description='Command-line calculator') parser.add_argume...
magicoder
python
You are tasked with implementing a class that performs validation on a given number based on certain criteria. The class should have a method that takes a number as input and returns an enum value indicating the validation result. The enum should include the following values: - `NumberTooLarge` (value: 1) if the input ...
```csharp public enum ValidationResult { NumberTooLarge = 1, NumberTooSmall = 2, ValidButNegativeNumber = 3, Valid = 4, } public class NumberValidator { public ValidationResult ValidateNumber(int number) { if (number > 100) { return ValidationResult.NumberTooLarge; ...
magicoder
csharp
You are tasked with creating a Python class to manage cryptocurrency trading fees for different exchanges. The class should allow for the retrieval and manipulation of fee information for various trading pairs on different exchanges. You are provided with a code snippet that contains some initial configuration setting...
```python class ConfigVar: def __init__(self, key, prompt, required_if, is_secure, is_connect_key): self.key = key self.prompt = prompt self.required_if = required_if self.is_secure = is_secure self.is_connect_key = is_connect_key class TradingFeesManager: def __init__(s...
magicoder
python
You are tasked with implementing a C++ function that performs a specific type of printing based on the type of input argument. The function should have two overloads, one for lvalue references and one for rvalue references. Your task is to complete the implementation of the `print` function for both lvalue and rvalue r...
```cpp #include <iostream> #include <type_traits> // Function overload for lvalue references template <typename T> void print(const T& t) { static_assert(!std::is_rvalue_reference<T>::value, "Invalid overload for rvalue references"); std::cout << "Lvalue reference: " << t << std::endl; } // Function overload ...
magicoder
cpp
You are working on a project that involves creating a simple inventory management system for a small retail store. The store has a variety of products, each with a unique identifier, name, price, and quantity in stock. Your task is to implement a Python class called `Inventory` that will manage the store's inventory. ...
```python class Inventory: def __init__(self): self.products = {} def add_product(self, product_id, name, price, quantity): self.products[product_id] = {'name': name, 'price': price, 'quantity': quantity} def remove_product(self, product_id): if product_id in self.products: ...
magicoder
python
You are tasked with implementing a Python function that converts a given priority level from a Resilient incident to an equivalent priority level for an ICD (Incident, Change, and Defect) ticket. The Resilient incident priority levels range from 1 to 10, with 1 being the highest priority, while the ICD ticket priority ...
```python from resilient_circuits import StatusMessage, FunctionResult, FunctionError from resilient_lib import ResultPayload, readable_datetime from resilient_lib.components.resilient_common import validate_fields # The lowest priority an ICD ticket can have as a default setting for escalation MIN_PRIORITY_ICD = 4 c...
magicoder
python
You are tasked with implementing a class that performs encoding and decoding of messages using a specific algorithm. The class should have methods for setting the version of the algorithm, encoding a message, and decoding a message. The algorithm version determines the encoding and decoding rules. The class should also...
```javascript class Encoder { constructor() { this.version = 1; // Default version this.totalEncoded = 0; this.totalDecoded = 0; } setVersion(version) { this.version = version; return this; } encode(message) { this.totalEncoded++; if (this.version === 1) { // Example encodi...
magicoder
javascript
You are given a list of integers representing the temperatures on different days. Your task is to create a function that, for each day, finds the next day (if any) when a warmer temperature will be encountered. If there is no such day, the value should be set to 0. The function should return a list of integers represen...
```python from typing import List def warmer_temperatures(temperatures: List[int]) -> List[int]: stack = [] res = [0] * len(temperatures) for i, n in enumerate(temperatures): while stack and n > temperatures[stack[-1]]: last = stack.pop() res[last] = i - last st...
magicoder
python
You are tasked with implementing a function to extract and count the unique class names from an HTML snippet. The function should take an HTML string as input and return a list of unique class names found within the HTML. For example, given the input "<a class=\"x a s\"></a>", the function should return ["x", "a", ...
```java import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import jodd.lagarto.dom.Node; import jodd.lagarto.dom.Node.NodeType; import ngoy.core.dom.XDom; public class ClassNameExtractor { public List<String> extractUniqueClassNames(String html) { Set<String>...
magicoder
java
You are tasked with creating a GraphQL mutation for user registration using Python and Graphene library. Your goal is to implement a mutation that takes in user details as input, creates a new user object, and saves it to the database. You will need to handle any potential errors that may occur during the user creation...
```python is_success = graphene.Boolean() message = graphene.String() @staticmethod def mutate(root, info, **kwargs): try: new_user = User(**kwargs) # Create a new user object with the provided input new_user.save() # Save the new user to the database is_success = True # Set the success ...
magicoder
python
You are tasked with creating a Python program that simulates a simple banking system. The program should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry. The program should also be able to handle errors gracefully and provide informative error messages to th...
```python class BankAccount: def __init__(self): self.accounts = {} def create_account(self, account_holder, initial_deposit): account_number = len(self.accounts) + 1 self.accounts[account_number] = {'holder': account_holder, 'balance': initial_deposit} return account_number ...
magicoder
python
You are tasked with implementing a function to determine the number of closing curly braces (`}`) that are not preceded by any opening curly brace (`{`) within a given string. The function should take a string as input and return the count of such closing braces. For example, given the input string: ``` }abc}def}ghi}j...
```cpp #include <iostream> #include <string> int countUnclosedBraces(const std::string& input) { int count = 0; bool opened = false; for (char c : input) { if (c == '{') { opened = true; } else if (c == '}' && !opened) { count++; } else if (c == '}' && opene...
magicoder
cpp
You are working on a Python project that involves managing user roles, user information, and analysis logs. The project has the following file structure: ``` project/ main.py app/ __init__.py role.py user.py logs/ __init__.py analyses_log.py ``` The `rol...
```python from app.role import Role from app.user import User from app.logs.analyses_log import AnalysesLog def get_users_with_role_count(role_name, users): role = Role(role_name) users_with_role = role.get_users_with_role(users) return len(users_with_role) # Example usage if __name__ == "__main__": u...
magicoder
python
You are tasked with implementing a function that processes a given string based on a specific rule. The function should take a string as input and return a modified version of the string according to the following rule: The input string contains a sequence of characters. If the character 'x' is encountered, it should ...
```python def process_string(input_string): final_text = "" skip = False for char in input_string: if not skip: final_text += char skip = not skip if char == 'x' else False return final_text ``` The `process_string` function iterates through the input string, appending chara...
magicoder
python
You are tasked with creating a program to validate CSS code submissions using a linter. The program should be able to handle both valid and invalid CSS code and provide appropriate feedback. Your task is to implement a Python function that takes a solution object as input and performs the following steps: 1. Update th...
```python from typing import List def validate_css_solution(solution: models.Solution) -> List[str]: solution_file = solution.solution_files.get() solution_file.path = 'index.css' solution_file.code = VALID_CODE solution_file.save() tasks.run_linter_on_solution(solution.id) comments = [comment....
magicoder
python
You are tasked with creating a program that utilizes the `PermutationImportance` class from the `eli5` library to calculate and display feature importances for a given machine learning model. The `PermutationImportance` class is used to calculate feature importances for black-box models by permuting the values of each ...
```python # Import necessary libraries import eli5 from eli5.sklearn import PermutationImportance from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier # Example model, can be replaced with any other model from sklearn.datasets import load_iris # Example dataset, can...
magicoder
python
You are tasked with creating a Python class that simulates a remote task manager for controlling swarm robots. The task manager will be responsible for assigning tasks to individual robots and monitoring their progress. Your task is to implement the `RemoteTaskManager` class with specific methods for task assignment an...
```python class RemoteTaskManager: def __init__(self, robots): self.robots = robots self.tasks_assigned = {robot.id: None for robot in robots} def assign_task(self, task): available_robots = [robot for robot in self.robots if self.tasks_assigned[robot.id] is None] if available_r...
magicoder
python
You are tasked with implementing a simple 2D game character movement system. The game character can move left or right based on user input from either a game controller joystick or D-pad buttons. The character's movement is constrained by the game boundaries, and the character can push crates in the game world. You ar...
```cpp #include <iostream> #include "blit.h" enum Direction { DIR_LEFT, DIR_RIGHT }; class GameCharacter { public: blit::Point l_location; Direction l_move; void handleUserInput() { if ((blit::pressed(blit::Button::DPAD_LEFT)) || (blit::joystick.x < -0.3f)) { l_move = DIR_LEFT; ...
magicoder
cpp
You are tasked with creating a program to parse and process a table of employee data from an HTML file. The HTML snippet provided represents the beginning of a table containing employee information. Each row in the table represents an employee, and the columns contain the employee's ID, name, place and date of birth, a...
```python from bs4 import BeautifulSoup def parseEmployeeTable(html_string): soup = BeautifulSoup(html_string, 'html.parser') table = soup.find('table') headers = [header.get_text() for header in table.find_all('th')] rows = table.find_all('tr')[1:] # Skip the header row employees = [] for ro...
magicoder
python
You are tasked with creating a Python class that manages language settings for a user interface. The class should allow for language switching and reading the current language setting from a configuration file. Your task is to implement the `LanguageManager` class with the following requirements: 1. The class should h...
```python import configFileRead class LanguageManager: def __init__(self, config_file_path): self.config_file_path = config_file_path def switch_language(self, language_code): """ Update the language setting in the configuration file. :param language_code: The code representing...
magicoder
python
You are working on a radio astronomy project and need to develop a function to grid a gaintable to a screen image. The gaintable contains visibility data, and the screen represents a virtual screen above the telescope. Your task is to implement the `grid_gaintable_to_screen` function, which takes the gaintable, screen,...
```python import numpy as np def grid_gaintable_to_screen(vis, gaintables, screen, height=3e5, gaintable_slices=None, scale=1.0, **kwargs): """ Grid a gaintable to a screen image The phases are just average per grid cell, no phase unwrapping is performed. :param vis: Visibility data for the radio tel...
magicoder
python
You are tasked with implementing a Python function that processes a CGI form and performs a specific operation based on the form data. The form data is expected to contain parameters for a minimization process, and upon processing the form, an email is sent with the results and certain temporary files are removed. Your...
```python import cgi import cgitb import os def process_cgi_form(form_data: dict) -> None: cgitb.enable() # Enable debugging # Convert the CGI form data into a dictionary format form_dict = cgi2dict(form_data) # Extract the necessary parameters for the minimization process parameters = ew(form_d...
magicoder
python
You are tasked with simulating the configuration of Open vSwitch (OVS) interfaces and ports using the `nmcli` command-line tool. Your goal is to create a Python program that generates the necessary `nmcli` commands based on a given set of network configurations. You are given the following information: - A list of net...
```python def generate_nmcli_commands(network_configurations): nmcli_commands = [] for config in network_configurations: command = "nmcli c add type {} ".format(config["type"]) for key, value in config.items(): if key != "type": command += "{} {} ".format(key, value) ...
magicoder
python
You are tasked with implementing a Python function that generates and prints a representation of a ballot based on the given dimensions and coordinates. The ballot will be represented as a grid of stars (*) and spaces, with specific patterns based on the provided coordinates and dimensions. You are given the following...
```python def make_pretty(dimensions, linear_structure): rows, cols = dimensions ballot_representation = '' for i in range(rows): row_representation = '' for j in range(cols): if linear_structure[i * cols + j] == 1: row_representation += '★' else: ...
magicoder
python
You are tasked with creating a program that processes and manipulates a structured document represented by a series of nodes. Each node can be of different types, such as paragraphs, tags, or line breaks. Your goal is to implement a function that counts the number of paragraphs in the document and returns the total cou...
```typescript function countParagraphs(docSection: DocSection): number { let paragraphCount = 0; // Traverse the document structure to count paragraphs function traverse(node: DocNode) { if (node instanceof DocParagraph) { paragraphCount++; } if (node.childNodes) { for (const childNode o...
magicoder
typescript
You are tasked with creating a program that reads a software source file and extracts the copyright year and the name of the author. The source file is written in C++ and follows a specific format for the copyright notice. The format is as follows: ``` // Copyright (C) <YEAR> <AUTHOR> // All rights reserved. // // This...
```cpp #include <iostream> #include <fstream> #include <string> #include <regex> int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <source_file_path>" << std::endl; return 1; } std::ifstream file(argv[1]); if (!file.is_open()) { std::cer...
magicoder
cpp
You are tasked with implementing a Python function that prints a given value in a specific format. The function should take a single argument, `value`, and print it in a human-readable format. The function should handle various data types such as integers, floats, strings, lists, dictionaries, and nested structures. Ad...
```python def pprint(value): if isinstance(value, int) or isinstance(value, float): print(value) elif isinstance(value, str): print(f'"{value}"') elif isinstance(value, list): print('[' + ', '.join(map(lambda x: pprint(x), value)) + ']') elif isinstance(value, dict): prin...
magicoder
python
You are tasked with creating a type checking utility for a React component library. The utility should ensure that the props passed to the components adhere to the specified types. The code snippet provided is a part of the type checking configuration for a component called `CheckTypes`. The `Props` object contains the...
```typescript type Props = { disabled: boolean; size: 'small' | 'medium' | 'large'; uppercase: boolean; animated: boolean; } type SubComponentProps = { [key: string]: keyof Props; } function typeCheck<Props>(expectedProps: SubComponentProps) { return function (componentName: string, props: Par...
magicoder
typescript
You are tasked with implementing a module resolution algorithm for a JavaScript module system. The module system uses the `export` and `import` keywords to define and use modules. When an `export` statement is encountered, it makes the local binding available for use in other modules. The `export * from 'module'` synta...
```javascript // Import the file system module for reading the module file const fs = require('fs'); function resolveExportAll(modulePath) { try { // Read the content of the module file const moduleContent = fs.readFileSync(modulePath, 'utf8'); // Create an empty object to store the exported binding...
magicoder
javascript