id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
52
7.08k
03a63688b9df18ac52b9
```python import requests from bs4 import BeautifulSoup def extract_news_show_links(url: str) -> str: headers = { 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' } r = requests.g...
03a693353c190aa70e80
```cpp #include <iostream> #include <cstdlib> int main(int argc, char *argv[]) { int sum = 0; for (int i = 1; i < argc; i++) { char *end; int num = std::strtol(argv[i], &end, 10); if (*end == '\0') { if (num % 2 == 0) { sum += num; } } ...
03a78f5c758ec79f3dc3
```python import asyncio import time def decorator_pause(threshold): """ Returns a decorator function that measures the execution time of a function and pauses if it exceeds the threshold. Args: threshold (float): The threshold time in seconds. Returns: function: A decorator function. """...
03a7cc2f63e71fccd676
```python from bs4 import BeautifulSoup def extract_html_info(html_code): # Parse the HTML code using BeautifulSoup soup = BeautifulSoup(html_code, 'html.parser') # Extract tag names of all elements tag_names = [tag.name for tag in soup.find_all()] # Extract the content of the 'Status' he...
03ab0841c3ea98fbb0f8
```java import dagger.Binds; import dagger.Module; import dagger.android.ActivityKey; import dagger.android.AndroidInjector; import dagger.multibindings.IntoMap; @Module(subcomponents = { TestFlombulatorActivityComponent.class }) public abstract class TestBindingModule { @Binds @IntoMap @ActivityKe...
03ab9cc5e84e95bc8aa2
```python from enum import Enum class REPO_STATUS(Enum): SUCCEED = "SUCCEED" FAILED = "FAILED" PENDING = "PENDING" class RepositoryManager: def __init__(self): self.repositories = {} def add_repository(self, name, info, status): self.repositories[name] = {"info": info, "status": s...
03ad43ce52606eb8b6e2
```python class GitRepository: def __init__(self): self.master_branch = [] self.gh_pages_branch = [] def git_pull(self): # Simulate pulling changes from the remote repository # Update the local branches with changes from the remote repository pass def git_push(self)...
03ae9abcea91117a5eb2
```python import threading CMD_THREAD_STOP = False def set_cmd_thread_stop(): global CMD_THREAD_STOP CMD_THREAD_STOP = True class CommandExecutionThread(threading.Thread): def __init__(self, command): super().__init__() self.command = command def run(self): global CMD_THREAD_...
03b05842de60dba3eebc
```python from typing import List def fill_diagonal_pattern(n: int) -> List[List[int]]: grid = [[0 for _ in range(n)] for _ in range(n)] num = 1 for d in range(n): i, j = 0, d while j >= 0: grid[i][j] = num num += 1 i += 1 j -= 1 if d ...
03b25eae91b354aec9b8
```python from channel import Channel from selector import Selector from wg import WaitGroup import time def process1(channel): time.sleep(1) channel.send("Hello from Process 1") def process2(channel): time.sleep(2) channel.send("Hello from Process 2") def main(): channel1 = Channel() channel...
03b2ffb76b4258d3449a
```python import re def count_words(filename, stop_words): word_count = {} with open(filename, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) for word in words: if word not in stop_words: word_count[word] = word_count.get(word, ...
03b3ac26eba3dedb92a7
To address the problem of creating a module system, we can utilize the concept of a module registry and a client interface. The module registry will keep track of available modules, and the client interface will provide a way for clients to access and utilize these modules. Here's a possible solution using Rust: ```r...
03b52ada108c0850b334
```python def check_admin(user_id): # Assuming is_admin is a dictionary mapping user IDs to admin status if user_id in app.jinja_env.globals['is_admin'] and app.jinja_env.globals['is_admin'][user_id]: return True else: return any(theme.startswith('admin_') for theme in app_themes) ``` In the...
03b54040ae1557586b38
```bash #!/bin/bash # packages = audit # Remove all existing rules from the /etc/audit/rules.d/ directory rm -f /etc/audit/rules.d/* # Clear the contents of the /etc/audit/audit.rules file > /etc/audit/audit.rules # Ensure that the script always exits with a success status true ``` The provided Bash script accompli...
03b67d8c4dbf8f1f5963
```python from typing import List, Tuple def final_position(movements: List[str]) -> Tuple[int, int]: x, y = 0, 0 # Initial position at (0, 0) for movement in movements: if "go_up" in movement: steps = int(movement.split("(")[1].split(")")[0]) if "(" in movement else 1 y += ste...
03b681ae0372fbeb86a0
```python import logging def log_utility(counters, tb_lines): log = logging.getLogger(__name__) if counters: log.info(_format_counters(counters)) if tb_lines: for line in tb_lines: log.error(line.rstrip('\r\n')) def _format_counters(counters): formatted_counters = "Counte...
03b7abb5003a08358456
```javascript function sortStringsIgnoreCase(arr) { return arr.sort((a, b) => { if (a.toLowerCase() === b.toLowerCase()) { return arr.indexOf(a) - arr.indexOf(b); } return a.toLowerCase().localeCompare(b.toLowerCase()); }); } // Test the function const inputArray = ["incididunt", "Lorem", "veniam...
03b7e6bbcadb725ae22c
```rust // Define the Routes struct struct Routes; impl Routes { // Define the routes method to return a default configuration fn routes() -> Routes { // Implement the default configuration here Routes } } // Define the Builder struct struct Builder { input_config: Option<Routes>, ...
03b82f53e0c11a829e7e
```bash #!/bin/bash RELEASE_NAME=$1 NAMESPACE=${2:-ibm-system} kubectl delete MutatingWebhookConfiguration image-admission-config --ignore-not-found=true -n $NAMESPACE kubectl delete ValidatingWebhookConfiguration image-admission-config --ignore-not-found=true -n $NAMESPACE kubectl delete clusterrolebinding admission...
03b851f13843d016c0f7
```python import os import requests def send_email(recipient, subject, body): try: response = requests.post( "https://api.mailgun.net/v3/" + os.environ['MAILGUN_DOMAIN'] + "/messages", auth=("api", os.environ['MAILGUN_API_TOKEN']), data={"from": os.environ['EMAIL_FROM'],...
03bb79f291f083911619
```rust // Define subtraction for Vector2 macro_rules! define_sub { ($T:ty, $U:ty, $V:ty) => { impl Sub<$U> for $T { type Output = $V; fn sub(self, rhs: $U) -> $V { $V { x: self.x - rhs.x, y: self.y - rhs.y, } ...
03bca0b1e201e6e33e55
```csharp using Analyzer.Tokens; using Grammar.Common.Infrastructure.Evaluable; using Grammar.Core.Expressions.Operations.Complex.Array.Access; namespace Analyzer.Parser { public class ArrayElementParser: IArrayElementParser { private static IParseTokensProcessInfo tokensInfo; public ArrayElem...
03be750ea07f5d829355
```python class DataFrameMismatchException(Exception): pass class RubiconException(Exception): pass def validate_dataframe(read_dataframe, written_dataframe): if read_dataframe.id != written_dataframe.id: raise DataFrameMismatchException("Dataframes do not match") if getattr(read_dataframe, '...
03bf81ddf9b0bdcc403e
```python from typing import List def getSingleNumber(nums: List[int]) -> int: if len(nums) == 1: return nums[0] nums.sort() # Sort the list to group duplicate numbers together i = 0 while i < len(nums) - 1: if nums[i] != nums[i + 1]: # Check if the current number is not equal to...
03c0250cd7ea6f51115f
```python import click # Assume the existence of a StudentDatabase class for database operations class StudentDatabase: def __init__(self): # Initialize the database connection pass def init_db(self): """Clear existing data and create new tables.""" # Implementation to clear e...
03c0daaf0513ea0ab72a
```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.s...
03c409ff84d3a98a5164
```python import numpy as np def distance_between_points(x1, y1, x2, y2): '''Calculate the Euclidean distance between two points''' distance = np.sqrt((x2 - x1)**2 + (y2 - y1)**2) return distance ``` In the solution, the `distance_between_points` function takes the coordinates of two points as input and ca...
03c519adea1b61d0d9b0
```python class XMLProcessor: def __init__(self, xml_path=None, fp=None, draw=False): if xml_path and fp: self.xml_path = xml_path elif xml_path: self.xml_path = xml_path elif fp: self.xml_path = None # or set to default XML path else: ...
03c6567b8d3d55582e56
```python class Foo: pass class Bar(Foo): def custom_method(self, param1, param2): return param1 + param2 ``` In the solution, the `Bar` class is defined to inherit from the `Foo` class. The `custom_method` is implemented to take two parameters, `param1` and `param2`, and return their sum.
03c94aa41998395050e7
```sql SELECT c.customer_id, c.first_name, c.last_name, c.email, c.phone_number, cu.currency_code, af.address_format, ma.address_details AS mailing_address, ba.address_details AS billing_address, co.country_name FROM customer c JOIN currency cu ON c.currency_id = cu.currency_id ...
03c9b354a993fbf72a81
```bash #!/bin/bash # Add the necessary commands to build the Docker image with the specified configurations docker build --no-cache --squash --tag docker-spark-create . ``` The provided Bash script includes the necessary commands to build the Docker image with the specified configurations. When executed, it will bui...
03cb6d187f56aa4e0335
```python def check_single_output_file(markers: list, is_SingleInputFile: bool) -> bool: # (Special Case 1) If only 1 marker and if only 1 file, it is a single output file if (len(markers) == 1 and is_SingleInputFile == True): return True else: return False ``` In the solution, the function ...
03cbddfbd48c5f9634f9
```python def update_environment_variables(env_vars: dict, multiple: bool) -> dict: # Create a new dictionary to store the updated environment variables updated_env_vars = env_vars.copy() # If multiple is True, override existing variables; otherwise, add new variables if multiple: # Update the ...
03cc14c4024058ec4949
```python from typing import List def find_symbols(input_string: str) -> List[str]: symbols = set() for char in input_string: if not char.isalnum() and not char.isspace(): symbols.add(char) return list(symbols) ``` The `find_symbols` function initializes an empty set to store unique sy...
03ccee83fdc4d5035c98
```python import cv2 if __name__ == '__main__': ESC_KEY = 27 INTERVAL = 33 FRAME_RATE = 30 # Initialize the webcam cap = cv2.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = cap.read() # Check if the frame is captured su...
03cd3af81012cb9dd7f7
```python from jinja2 import Environment, FileSystemLoader class EventTableGenerator: def __init__(self): self.jinja_template = 'table.html' self.headers = ['event', 'event_size', 'datetime', 'event_label'] self.required_parameters = ["uris"] self.optional_parameters = ["output", "d...
03cdb638fe6844e03d5f
```cpp #include <unordered_map> class TextureLayoutManager { private: std::unordered_map<VertexElement, TextureLayout> layoutMap; public: void setTextureLayout(VertexElement element, TextureLayout layout) { layoutMap[element] = layout; } TextureLayout getTextureLayout(VertexElement element) {...
03ce27784cbc160e4101
```python class InvalidAmountError(ValueError): def __init__(self): super().__init__("Invalid amount for currency") class CurrencyMismatchError(ValueError): pass class CurrencyConverter: def __init__(self, exchange_rates): self.exchange_rates = exchange_rates def convert(self, amoun...
03ce714d47159cbd757c
```python def count_nodes(root: TreeNode) -> int: if not root: return 0 return 1 + count_nodes(root.left) + count_nodes(root.right) ``` The `count_nodes` function recursively counts the nodes in the binary tree. If the root is None, it returns 0. Otherwise, it adds 1 for the current node and recursively...
03ce9505e1bd31e1de40
```cpp #include <iostream> #include <string> namespace cros_im { void loadImage(const std::string& filename) { std::cout << "Image loaded from file: " << filename << std::endl; } void applyFilter(int filterType) { std::cout << "Applying filter type: " << filterType << std::endl; } ...
03cf247139af9fce7e81
```python def find_latest_versions(package_versions): latest_versions = {} for version in package_versions: major, minor, patch = map(int, version.split('.')) package_name = f"package{package_versions.index(version) + 1}" if package_name not in latest_versions: latest_version...
03cfc6910acf3dd8204c
```python from time import time, sleep class Stopwatch: def __init__(self): self._start_time = None self._elapsed_time = 0 def start(self): if self._start_time is not None: raise ValueError("Stopwatch is already running") self._start_time = time() def stop(self...
03cfda6f4f48c6bd74fa
```python from distutils.core import setup, Extension module1 = Extension('ipcbridge', define_macros=[('MAJOR_VERSION', '0'), ('MINOR_VERSION', '0.5')], include_dirs=['/usr/include'], sources=['ipcbridge.c']) # Add the sour...
03d05283778bf630e7f7
```typescript // src/chat/enums/callStatuses.enum.ts export enum CallStatus { Pending = "pending", Ongoing = "ongoing", Completed = "completed", Cancelled = "cancelled", } // src/chat/utils/callStatusMessage.ts import { CallStatus } from '../enums/callStatuses.enum'; export function getCallStatusMessage(statu...
03d274097da95f865741
```csharp using System; class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int result = Fibonacci(n); Console.WriteLine(result); } static int Fibonacci(int n) { if (n <= 1) { return n; } int ...
03d33b722f946fca4c2f
```python def removeTrailingSlash(s): if s.endswith('/'): return s[:-1] return s # Test cases test_cases = [ ("abc/", "abc"), ("abc/def/", "abc/def"), ("a/b/c/", "a/b/c"), ] for input_str, expected_output in test_cases: result = removeTrailingSlash(input_str) assert result == expec...
03d431a2af393a2aa5ef
```bash #!/bin/bash # Check if MANAGE_LOCAL_HBASE is set to true if [ "$MANAGE_LOCAL_HBASE" = "true" ]; then # Start HBase service echo "Starting HBase service..." # Add command to start HBase service here else echo "MANAGE_LOCAL_HBASE is not set to true. Skipping HBase service." fi # Check if MANAGE_...
03d64a6d4732adf37f35
```python import os def configure_batch_exporter(): config = {} # Read BATCH_EXPORTER_POST_BATCH_SLEEP_SECONDS environment variable post_batch_sleep_seconds = os.getenv("BATCH_EXPORTER_POST_BATCH_SLEEP_SECONDS", "60") try: config["post_batch_sleep_seconds"] = int(post_batch_sleep_seconds) ...
03d65ce2a04f3e621b00
```csharp using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using System; using System.Linq.Expressions; public class CustomTypeValueConverter : ValueConverter<CustomType, string> { public CustomTypeValueConverter(ConverterMappingHints mappingHints = null) : base( customType => Con...
03d704840c863f3ccb3a
To achieve the desired functionality, you can create a Python package with the following structure: ``` math_operations_package/ │ ├── setup.py ├── math_operations/ │ ├── __init__.py │ ├── operations.py │ └── plugins/ │ ├── __init__.py │ ├── add.py │ └── multiply.py └── tests/ ├── __init__....
03d71a26d148d8543535
```rust pub struct KeyValueStore { keys: Keys, color: bool, } impl KeyValueStore { pub fn new() -> Self { KeyValueStore { keys: Keys { keys: Vec::new() }, color: true, // Default value for "color" key } } pub fn set_value(&mut self, key: &str, value: bool) {...
03d7bb76ac7617d31e0f
```java public int lastRemaining(int n, int m) { if (n <= 0 || m <= 0) return -1; int last = 0; for (int i = 2; i <= n; i++) { last = (last + m) % i; } return last; } ``` The solution uses a mathematical approach to solve the problem. It iterates through the circle of children and calculate...
03d86b3f39a708db4c01
```rust fn calculate_checksum(strings: &[String]) -> usize { let mut two_duplicates = 0; let mut three_duplicates = 0; for s in strings { let mut counts = [0; 26]; for c in s.chars() { let index = (c as u8 - b'a') as usize; counts[index] += 1; } if c...
03d95b2bf53f8146bded
```typescript function filterPackageIds(packageIds: string[]): string[] { return packageIds.filter(id => id.startsWith('P') && id.length > 5); } ``` The `filterPackageIds` function uses the `filter` method to iterate through the `packageIds` array and return a new array containing only the package IDs that meet th...
03da278b98f71b055eb9
```python def to_weird_case(string): # Define a lambda function to convert a word to weird case recase = lambda s: "".join([c.upper() if i % 2 == 0 else c.lower() for i, c in enumerate(s)]) # Split the input string into words, apply the recase function, and join the modified words with spaces retur...
03db4f8bc639f7f9d086
```python import os def manage_files(OriginFile, TargetFile): if os.path.isfile(OriginFile): os.rename(OriginFile, TargetFile) open(OriginFile, 'w').close() else: print("OriginFile does not exist. No operations performed.") # Example usage OriginFile = "/path/to/origin/file.txt" Target...
03dcca2f1d6dc3cf17bb
```python def filter_equipment(equipment_list, target_body_part, target_skills): filtered_equipment = [equipment for equipment in equipment_list if equipment.body_part == target_body_part and any(skill in equipment.skills for skill in target_skills)] return fi...
03ddb87ef12919384a16
```php /** * Verifies the user's email verification link. * * @param Request $request The request object containing 'email' and 'token' parameters * @return array The response indicating the status of the verification link */ public function verify(Request $request) { // Retrieve 'email' and 'token' parameters...
03de2af085343bb2856b
```java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.justwen.trip.bean.TicketInfo; import java.util.List; public class TicketAdapterEx extends BaseAdapter<Tick...
03dee75f2633915e112d
```csharp using System; namespace NQuery.Runtime.ExecutionPlan { internal sealed class ConstantIterator : Iterator { public RuntimeComputedValueOutput[] DefinedValues; private bool _isEof; private int _currentIndex; public override void Open() { _isEof = fal...
03e13cedc8b743804a93
```python from typing import List def sum_of_squares_of_even_numbers(arr: List[int]) -> int: sum_of_squares = 0 for num in arr: if num % 2 == 0: sum_of_squares += num ** 2 return sum_of_squares ``` The `sum_of_squares_of_even_numbers` function iterates through the input list and adds th...
03e2c40737d35fea9cbc
```python class ProblemManager: def __init__(self): self.problems = [] def add_problem(self, is_open, problem): self.problems.append({'is_open': is_open, 'problem': problem}) def get_open_problems(self): return [problem['problem'] for problem in self.problems if problem['is_open']]...
03e3856e2bd8c825ca28
The `generate_final_predictions` function iterates through the list of feature maps and processes the outputs from the bounding box regression, classification, and landmark regression heads. It concatenates the outputs from each head to form the final predictions for bounding box regression, classification, and landmar...
03e3bde344d2fbc68398
```python import numpy as np def distribute_light(image: np.ndarray, indices: np.ndarray, indptr: np.ndarray, fraction: float) -> np.ndarray: new_image = np.zeros_like(image, dtype=float) for i in range(len(indptr) - 1): start_idx = indptr[i] end_idx = indptr[i + 1] total_light = imag...
03e60e5089229784d57b
```cpp #include <iostream> // Base class for combined signals class CombinedSignal { public: virtual double calculateCombinedValue(double signal1, double signal2) const = 0; }; // Class for calculating the difference between two signals class DifferenceCombinedSignal : public CombinedSignal { public: double c...
03e613d5f902192e176a
```cpp #include <iostream> template<typename... Types> struct apply { static typename std::result_of<decltype(&Types::operator())(Types...)>::type result; template<typename F, typename... Args> static void apply(F&& f, Args&&... args) { result = std::forward<F>(f)(std::forward<Args>(args)...); ...
03e7d1c82320005a1820
```python class TileGame: def __init__(self, grid_size): self.grid_size = grid_size self.tiles = [['-' for _ in range(grid_size)] for _ in range(grid_size)] def print_result(self, result): game_printer = GamePrinter() game_printer.print_text(result, len(self.tiles)) class GameP...
03ec6d5a3e2dd8d326bf
```python import requests def is_latest_version(package_name, provided_version): # Assume there is an API endpoint that provides the latest version for a given package api_url = f"https://api.example.com/package/{package_name}/latest_version" try: response = requests.get(api_url) lates...
03ef6f2c88965b41b812
```python import tkinter as tk class OKCancelButtons: def __init__(self, confirm_callback, cancel_callback): self.frame = tk.Frame() self.ok_button = tk.Button(self.frame, text="OK", command=confirm_callback) self.cancel_button = tk.Button(self.frame, text="Cancel", command=cancel_callback)...
03f6e9e710a83968a45c
```python from typing import List, Dict, Union def filter_students(students: List[Dict[str, Union[str, int]]], filter_condition: str) -> List[str]: filtered_students = [] if filter_condition == "high_grade": filtered_students = [student["name"] for student in students if student["grade"] in ["11",...
03f8be23857dfce65549
```python class SHT2X: def __init__(self, i2c_address): self.i2c_address = i2c_address # Initialize the I2C communication with the sensor using the i2cmod module # Example: i2cmod.init(i2c_address) def read_temperature(self): try: # Read the temperature from the sens...
03f8d702f622c6bb79de
```php /** * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ONGR\DemoBundle\Document; use ONGR\ElasticsearchBundle\Annotation as ES; use ONGR\ElasticsearchBundle\Document\DocumentInterface; /** * @ES\Document(type="product")...
03f923f275c4eef9b474
```python class MessageLogger: def __init__(self): self.logged_messages = [] def log_message(self, message, severity="info"): self.logged_messages.append({"message": message, "severity": severity}) def get_messages(self): return self.logged_messages @property def message_c...
03f94eef438abbc4a9dc
```python from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException def wait_for_title(driver, timeout, target_substring): try: WebDriverWait(driver, timeout).until( EC.title_c...
03f9e6c9912499b959f1
```bash #!/bin/bash # Enable debugging mode set -x # Define the path to the NUnit console runner NUNIT_RUNNER="packages/NUnit.Runners.*/tools/nunit-console.exe" # Define the path to the test assembly file TEST_ASSEMBLY="bin/fun.test.dll" # Check if the NUnit console runner exists if [ ! -f "$NUNIT_RUNNER" ]; then ...
03fbe6494b31cab41e90
```python import socket # Create a socket object server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Define the server address and port server_address = ('localhost', 12345) # Bind the socket to the address and port server_sock.bind(server_address) # Listen for incoming connections server_sock.listen(...
03fc2b45ec8c336c4473
The `Rectangle` class is implemented with a constructor to initialize the width and height attributes, and a method to calculate and return the area of the rectangle. The `calculate_area` method simply multiplies the width and height attributes to obtain the area of the rectangle.
040147d7c8f79329cc99
```python def mutations(arr): # Convert both strings to lowercase for case-insensitive comparison str1 = arr[0].lower() str2 = arr[1].lower() # Check if all characters in str2 are present in str1 for char in str2: if char not in str1: return False return True ```
04017add772601925440
```python import zipfile import io import os def build_log_push(build_info): with open(build_info['log'], 'r') as f: build_log = f.read() + "\n" + build_info['build_exception'] log_file_name = os.path.basename(build_info['log']) build_log_key = 'builds/' + log_file_name return build_log, buil...
0402cb0e7c3fbd735606
```python def generate_cubes(): while True: try: n = int(input("Enter a positive integer: ")) if n <= 0: print("Please enter a positive integer.") else: cubes = [i**3 for i in range(1, n+1)] print(cubes) brea...
04031266b229f05115a3
```python class CircularBuffer: def __init__(self, size): self.size = size self.buffer = [None] * size self.message = "" def add_item(self, item): self.buffer.pop(0) self.buffer.append(item) def get_items(self): return [item for item in self.buffer if item i...
0404292ed97408bfae78
```rust use super::super::{Animations, CollideEntity, Direction, DrawableEntity}; use crate::entities::enemies::sight::*; use crate::ui::FloatingText; pub struct Blob { position: (i32, i32), direction: Direction, speed: i32, sight_range: i32, } impl Blob { pub fn new(x: i32, y: i32, speed: i32, si...
0405728e61d66b0b3181
```python import pytesseract from PIL import Image import cv2 def extract_text_from_image(input_image_path): input_image = cv2.imread(input_image_path) grayscale_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY) adaptive_threshold = cv2.adaptiveThreshold(grayscale_image, 255, cv2.ADAPTIVE_THRESH_GAUSSI...
040697f78f210d8ee7d9
```python import json def extract_config_info(filename): try: with open(filename, 'r', encoding='utf-8') as f: config = json.load(f) app_name = config['app_name'] database_host = config['database']['host'] log_level = config['logging']['log_level'] ...
040751837765f2aa4885
```java public String restoreWarnings(int[] warningCodes) { // Restore the warning codes // Assume a method called restoreWarningCode exists to restore a single warning code for (int code : warningCodes) { restoreWarningCode(code); } // Generate the message StringBuilder message = n...
040a6fcb4e3693badd41
```python def generate_sql_commands(database_name, username, password, host): sql_commands = [] sql_commands.append(f"CREATE DATABASE `{database_name}` CHARACTER SET utf8 COLLATE utf8_general_ci;") sql_commands.append(f"CREATE USER '{username}'@'{host}' IDENTIFIED BY '{password}';") sql_commands.append(...
040ac22e7e656473ef2f
```python from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklear...
040cbf02a30403f9e690
```python def process_config_model(cfg): extracted_info = {} # Extract number of layers num_layers = cfg.get_num_layers() # Assuming a method get_num_layers() exists in the Cfg class extracted_info["num_layers"] = num_layers # Extract learning rate learning_rate = cfg.get_learning_rate() # A...
040ced12f75606adf88b
```html <!-- HTML/Blade code --> <div class="form-group"> {!! Form::submit($submitText, ['class' => 'btn btn-primary form-control']) !!} </div> <!-- JavaScript code (in a separate JavaScript file or within a <script> tag) --> <script> $(document).ready(function() { $('#tag_list').select2({ ...
040d5c1e06ade29bbb2b
```javascript function processFrequencyCapData(campaigns) { return campaigns.map(campaign => { if (campaign.frequencyCapUnlimited) { return { ...campaign, frequencyCapTimeUnit: 'unlimited' }; } else { return campaign; } }); } // Test const input = [ { frequencyCapUnlimited: true, frequenc...
040de5c3b2abd82027ce
```python class AttributeEnforcer: def __init__(self, **kwargs): required_attributes = ['id', 'i', 's', 'm', 'groups'] for attr in required_attributes: if attr not in kwargs: raise TypeError(f"Missing required attribute: {attr}") type_mapping = { ...
040e3ee8323bee5e33a9
```python import sys import json # Read input from a source (e.g., file or standard input) input_data = sys.stdin.read() # Output "---" to the standard output print("---") # Check if the input JSON data has a length greater than 0 json_data = json.loads(input_data) if len(json_data) > 0: # Write the final output...
040ea4664559ea167f47
```php function countUniqueItems(array $wishlist): int { // Fix the issue in the given code snippet if (count($wishlist) > 0 && !empty($wishlist)) { // Further processing can be performed here } // Count the unique items in the wishlist $uniqueItems = array_count_values($wishlist); retu...
040f3dc6c2ce22deccd2
```python class EndpointHandler(RoomEndpointsMixin, VREndpointsMixin, OtherEndpointsMixin): """ A class that combines multiple mixins to handle various types of endpoints. """ def __init__(self): super().__init__() # Inherited methods from RoomEndpointsMixin def handle_room_endpoint(sel...
040f6bc6fee4d78cf43d
```csharp using System; using System.Collections.Generic; using Xunit; public class Point { public int X { get; set; } public int Y { get; set; } } public class Rectangle { public int Height { get; } public int Width { get; } public Rectangle(int x, int y, int width, int height) { Hei...
04100adcf7021e1bc133
```rust /// Represents a borrowed string slice with a specific lifetime. struct Kstr<'a> { inner: &'a str, } impl<'a> Kstr<'a> { /// Creates a new `Kstr` instance from a borrowed string slice. fn borrowed(inner: &'a str) -> Self { Kstr { inner } } /// Converts the borrowed string slice int...
0411a5d5bb773ff395d2
```python from typing import List, Dict import re def extract_experiment_info(code_snippets: List[str]) -> List[Dict[str, str]]: extracted_info = [] for snippet in code_snippets: user_match = re.search(r"user_name='(\w+)'", snippet) sample_match = re.search(r"sample_name='([\w\d_]+)'", snippet)...
0411c5fecb1cc1b54326
The solution completes the `MenuOption` enum by adding the missing cases (`support` and `buy`) and their corresponding titles. The `title` computed property is implemented to return the appropriate title for each menu option using a switch statement. This solution ensures that the enum represents the menu options and p...
04138da581ab9ebd9852
```java class ExpenseTracker { private Month[] months; public void setMonths(Month[] months) { this.months = months; } public double getTotalExpensesForYear() { double totalExpenses = 0; for (Month month : months) { totalExpenses += month.calculateTotalExpenses(); ...
04139caea9271019781a
```javascript const fs = require('fs'); function readEnvironmentConfig() { try { const angularCliConfig = JSON.parse(fs.readFileSync('.angular-cli.json', 'utf8')); const environmentMapping = angularCliConfig.apps[0].environments; return environmentMapping; } catch (error) { console.error('Error rea...