import cv2
import numpy as np

def merge_lines(lines, threshold=10):
    if len(lines) == 0:
        return []

    merged_lines = []

    for line in lines:
        x1, y1, x2, y2 = line[0]
        merged = False
        for merged_line in merged_lines:
            x1_m, y1_m, x2_m, y2_m = merged_line[0]
            if abs(y1 - y1_m) < threshold and abs(y2 - y2_m) < threshold:
                merged_line[0] = [min(x1, x1_m), min(y1, y1_m), max(x2, x2_m), max(y2, y2_m)]
                merged = True
                break
        if not merged:
            merged_lines.append(line.copy())

    return merged_lines

def find_horizontal_lines():
    img = cv2.imread("random_lines.png", cv2.IMREAD_GRAYSCALE)

    edges = cv2.Canny(img, 50, 150, apertureSize=3)
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=50, minLineLength=30, maxLineGap=10)

    if lines is None:
        return 0

    merged_lines = merge_lines(lines)

    horizontal_line_count = 0

    for line in merged_lines:
        x1, y1, x2, y2 = line[0]
        if abs(y1 - y2) < 10:
            horizontal_line_count += 1

    return horizontal_line_count

Please use the OpenCV library to solve the following problem: Given a black and white image where the background is black, and the foreground consists of some white lines, count the number of horizontal lines in the image.
Answering the question must meet the following requirements:
1. Define a Python function find_horizontal_line(), which does not need any input parameters, and returns the number of horizontal lines.
2. The image file is "random_lines.png", and it is stored in the same path as the code.
3. There are intersecting lines in the image, please do not mistakenly count one line segment as two because of intersections.

#<INSERT>
if __name__ == '__main__':
    assert find_horizontal_line()==3


import cv2
import numpy as np

def find_smallest_area_pattern_id():
    image = cv2.imread("blackwhite_geometry.png")
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 二值化图像
    _, binary_image = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)

    # 查找连通域
    num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image, 8, cv2.CV_32S)

    # 初始化最小面积和最小面积图案的 ID
    min_area = float('inf')
    min_area_id = -1

    # 遍历连通域统计信息，找到面积最小的图案 ID
    for i in range(1, num_labels):
        area = stats[i, cv2.CC_STAT_AREA]
        if area < min_area:
            min_area = area
            min_area_id = i

    return min_area_id

Please use the OpenCV library to solve the following problem: Given a black and white image, find the connected pattern with the smallest area.
Your solution needs to meet the following requirements:
1. Define the Python function `find_smallest_area_pattern_id()`, which takes no input parameters and returns the id of the connected pattern with the smallest area.
2. The image file is "blackwhite_geometry.png" and is stored in the same path as the code.
3. The image is a 200*200 binary image; the background color is black, and the foreground is white connected patterns. The patterns are independent of each other and regularly arranged in a 3x3 matrix. The id of the top-left pattern is 1, and the ids increase sequentially from left to right, top to bottom.

问题：写一段 python 代码实现以下功能。
找出小于第n个斐波那契数的最大完全平方数
函数命名为 max_square_number，输入为整数 n

答案：
```python
def max_square_number(n):
    if n <= 2:
        return 0  # 对于斐波那契数列的前两个数，没有完全平方数可用

    fibs = [0, 1]  # 存储斐波那契数列的前两个数
    squares = []  # 存储完全平方数的列表

    max_square = 0
    i = 2

    while i <= n:
        fibs.append(fibs[i-1] + fibs[i-2])  # 计算下一个斐波那契数
        i += 1

    fib = fibs[-1]
    perfect_squares = [i**2 for i in range(1, int(math.sqrt(fib)) + 1)]
    max_square = max(filter(lambda x: x < fib, perfect_squares))
    return max_square
```

----------------

#<INSERT>
if __name__ == '__main__':
    assert find_smallest_area_pattern_id()==6


import cv2
import numpy as np

def remove_horizontal_white_lines():
    # 读取图像
    image = cv2.imread("random_lines.png", cv2.IMREAD_GRAYSCALE)

    # 二值化
    _, binary_image = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY)

    # 形态学操作，水平方向的核
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))
    # 开运算去除水平白线
    opened_image = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, horizontal_kernel)

    opened_image = cv2.dilate(opened_image, horizontal_kernel, iterations=1)

    # 从原始图像中删除水平白线
    result_image = image.copy()
    result_image[opened_image == 255] = 0

    return result_image

Please use the OpenCV library to solve the following problem: Given a black-and-white image where the background is black, and the foreground consists of some white lines, please remove the horizontal lines from the image.
Your solution should meet the following requirements:
1. Define a Python function remove_horizontal_white_lines() that does not require any input parameters and returns the image after removing the horizontal lines.
2. The image file is named "random_lines.png" and is located in the same path as the code.
3. Apart from removing the horizontal lines, do not perform any other processing.

#<INSERT>
if __name__ == '__main__':
    result_image= remove_horizontal_white_lines()
    gt= cv2.imread("del_horilines_image.png",cv2.IMREAD_GRAYSCALE)
    assert np.array_equal(gt, result_image)


import cv2
import numpy as np

def remove_horizontal_white_lines():
    image = cv2.imread("hor_lines.png", cv2.IMREAD_GRAYSCALE)

    # Create a copy of the image to draw the detected lines
    result_image = image.copy()

    # Detect horizontal white lines of 1-pixel width
    # Create a kernel to detect horizontal lines
    kernel = np.array([[1, 1, 1]], np.uint8)

    # Use morphological operations to detect lines
    lines = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel, iterations=1)

    # Create a mask for the lines
    mask = cv2.inRange(lines, 255, 255)

    # Find contours of the detected lines
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Remove the detected lines by drawing black on the result image
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        if h == 1:  # Ensure the height is 1 pixel
            cv2.line(result_image, (x, y), (x + w, y), (0,), 1)

    return result_image

Please use the OpenCV library to solve the following problem: Given a black and white image where the background is black and the foreground consists of some white lines, please remove the "1-pixel width" horizontal white lines from the image.
The answer needs to meet the following requirements:
1. Define a Python function remove_horizontal_white_lines(), which does not need any input parameters and returns the image after removal.
2. The image file is "hor_lines.png" and is stored in the same path as the code.
3. The white lines in the image have different widths; there are both 1-pixel width lines and white lines wider than 1 pixel.

#<INSERT>
if __name__ == '__main__':
    result_image= remove_horizontal_white_lines()
    gt= cv2.imread("del_1width_horilines_image.png", cv2.IMREAD_GRAYSCALE)
    assert np.array_equal(gt, result_image)


import cv2
import numpy as np
def detection_intersection():
    img = cv2.imread("random_lines.png")
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    dst = cv2.cornerHarris(gray,2,3,0.04)
    ret,thresh = cv2.threshold(dst,0.01,255,cv2.THRESH_BINARY)

    k1=np.ones((3,3), np.uint8)#指定膨胀核大小
    mask = cv2.morphologyEx(thresh, cv2.MORPH_DILATE, k1)
    mask = mask.astype(np.uint8)
    contours,hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    count=0
    for cnt in contours:
        (x, y, w, h) = cv2.boundingRect(cnt)
        if w > 5 or h > 5:
            count+=1
    return count

Please use the OpenCV library to solve the following problem: Given a black-and-white image with a black background and some white segments in the foreground, count the number of intersections in the image.
The requirements to answer the question are as follows:
1. Define a Python function `detection_intersection()`, which does not need any input parameters and returns the number of intersections.
2. The image file is "random_lines.png" and it is stored in the same path as the code.

#<INSERT>
if __name__ == '__main__':
    assert detection_intersection()==4


import cv2
import numpy as np
def detection_video_length():
    cap = cv2.VideoCapture("city.mp4")
    cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
    frame_id = 0
    images = []
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        if frame_id % 100 == 0:
            images.append(frame)
        frame_id += 1
    return len(images)

Please use the OpenCV library to solve the following problem: Given a video file, extract every 100th frame from the video into a list, and return the length of the list.
The answer needs to meet the following requirements:
1. Define a Python function detection_video_length(), the function does not need any input parameters, and returns the length of the list.
2. The video file is "city.mp4" and is stored in the same path as the code.

#<INSERT>
if __name__ == '__main__':
    assert detection_video_length()==3


import cv2
import numpy as np
def detection_keypoint():
    img = cv2.imread("lena.png")
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    sift = cv2.SIFT_create()
    keypoints = sift.detect(gray_img, None)
    keypoints, descriptors = sift.compute(gray_img, keypoints)
    return len(keypoints)

Please use the OpenCV library to solve the following problem: Given an image, use the SIFT detector to detect the number of keypoints in the image.
The response needs to meet the following requirements:
1. Define a Python function `detection_keypoint()` that does not require any input parameters and returns the number of keypoints.
2. The image file is "lena.png" and is stored in the same path as the code.
3. Convert the read image to a grayscale image.

#<INSERT>
if __name__ == '__main__':
    assert detection_keypoint()==1111


import cv2
import numpy as np
def detection_match():
    img = cv2.imread("lena.png")
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    sift = cv2.SIFT_create()
    keypoints = sift.detect(gray_img, None)
    keypoints, descriptors = sift.compute(gray_img, keypoints)

    bf = cv2.BFMatcher()
    matches = bf.match(descriptors, descriptors)
    return len(matches)

Please use the OpenCV library to solve the following problem: Given an image, convert it to grayscale using cvtColor, then use the SIFT detector to detect the number of key points in the image, and then use the Brute-Force matcher to compare descriptors and find matches.
To answer the question, you need to meet the following requirements:
1. Define a Python function detection_match(), which does not require any input parameters and returns the number of matches found by the Brute-Force matcher.
2. The image file is "lena.png" and is stored in the same path as the code.
3. Please use the sift.detect() and sift.compute() functions; set the crossCheck parameter of BFMatcher to False.

#<INSERT>
if __name__ == '__main__':
    assert detection_match()==1111


import cv2
import numpy as np
def resize_image():
    image = cv2.imread("butterfly.jpg")
    resized_image = cv2.resize(image, (500, 560))
    gray_image = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)

    gaussian_kernel_size = (3, 3)
    gaussian_sigma = 0
    blurred_image = cv2.GaussianBlur(gray_image, gaussian_kernel_size, gaussian_sigma)
    target_size = (500, 600)
    resized_image = cv2.resize(blurred_image, target_size, interpolation=cv2.INTER_LINEAR)
    mean_value = np.mean(resized_image)
    return round(mean_value,2)

Please use the OpenCV library to solve the following problem: Given an image, convert it to grayscale, resize it to a size of (500,560), process it using Gaussian blur, then resize it to a size of (500,600) using linear interpolation, and return the average pixel value of the final image.

The answer needs to meet the following requirements:
1. Define a Python function resize_image() that does not require any input parameters and returns the average pixel value of the processed image.
2. The image file is "butterfly.jpg" and is stored in the same path as the code.
3. The Gaussian kernel function of Gaussian blur is (3,3), and sigma is 0.
4. The returned result retains two decimal places.

#<INSERT>
if __name__ == '__main__':
    assert resize_image()==145.15


import cv2
import numpy as np
def process_image():
    image = cv2.imread("lena.png")
    rows, cols = image.shape[:2]
    translation_matrix = np.float32([[1, 0, 25], [0, 1, 50]])
    translated_img = cv2.warpAffine(image, translation_matrix, (cols, rows))

    rotation_matrix = cv2.getRotationMatrix2D((cols / 2, rows / 2), 45, 1)
    rotated_img = cv2.warpAffine(translated_img, rotation_matrix, (cols, rows))
    return rotated_img

Please use the OpenCV library to solve the following problem: Given an image, move the image 25 pixels to the right, 50 pixels down, and then rotate it 45 degrees around its center, and return the processed image.
The answer must meet the following requirements:
1. Define the Python function process_image(), which does not require any input parameters and returns the processed image.
2. The image file is "lena.png", stored in the same directory as the code.

#<INSERT>
if __name__ == '__main__':
    result_image= process_image()
    gt= cv2.imread("translated_rotated_lena.png")
    assert np.array_equal(gt, result_image)


import cv2
def find_contour():
    image = cv2.imread("hand.png")
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5,5), 0)
    ret, thresh1 = cv2.threshold(blur, 70, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

    contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnt = max(contours, key = lambda x: cv2.contourArea(x))
    return cv2.contourArea(cnt)

Please use the OpenCV library to solve the following problem: Given an image, detect the contours within it, and return the area of the largest contour.
The solution must meet the following requirements:
1. Define a Python function `find_contour()`, which does not require any input parameters and returns the area of the largest contour.
2. The image file is "hand.png" and is stored in the same directory as the code.
3. Sequentially process the input image as follows: convert it to grayscale, apply Gaussian blur with a kernel size of 5x5 and sigma of 0; perform binary thresholding with a threshold value of 70 and threshold type `cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU`.
4. Use `cv2.RETR_TREE` as the contour retrieval mode and `cv2.CHAIN_APPROX_SIMPLE` as the contour approximation method.

#<INSERT>
if __name__ == '__main__':
    assert find_contour()==137652.5


import cv2
import numpy as np

def find_angle(p1, p2, p3):
    a = np.array(p1)
    b = np.array(p2)
    c = np.array(p3)

    ba = a - b
    bc = c - b

    cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
    angle = np.arccos(cosine_angle)

    return np.degrees(angle)

def is_acute_triangle(points):
    angles = [
        find_angle(points[0][0], points[1][0], points[2][0]),
        find_angle(points[1][0], points[2][0], points[0][0]),
        find_angle(points[2][0], points[0][0], points[1][0]),
    ]
    return all(angle < 90 for angle in angles)

def find_acute_triangles():
    img = cv2.imread("blackwhite_geometry_1.png", cv2.IMREAD_GRAYSCALE)
    _, thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    acute_triangle_count = 0

    for cnt in contours:
        epsilon = 0.04 * cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, epsilon, True)

        if len(approx) == 3:
            if is_acute_triangle(approx):
                acute_triangle_count += 1

    return acute_triangle_count

Please use the OpenCV library to solve the following problem: There is a black and white image with a black background and white foreground. The image contains various geometric shapes, such as triangles, polygons, etc. Write a Python function to count the number of acute triangles in the image.
Answer the question according to the following requirements:
1. Define a Python function `find_acute_triangles()`, which does not require any input parameters and returns the number of acute triangles in the image.
2. The image file is "blackwhite_geometry_1.png" and is stored in the same path as the code.
3. The triangles in the image include acute, right, and obtuse triangles. Correctly distinguish and count only the acute triangles.
4. Definition of an acute triangle: a triangle where all three internal angles are less than 90 degrees.

#<INSERT>
if __name__ == '__main__':
    assert find_acute_triangles()==2


import cv2
import numpy as np

def find_angle(p1, p2, p3):
    a = np.array(p1)
    b = np.array(p2)
    c = np.array(p3)

    ba = a - b
    bc = c - b

    cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
    angle = np.arccos(cosine_angle)

    return np.degrees(angle)

def is_right_triangle(points):
    angles = [
        find_angle(points[0][0], points[1][0], points[2][0]),
        find_angle(points[1][0], points[2][0], points[0][0]),
        find_angle(points[2][0], points[0][0], points[1][0]),
    ]
    # 允许一定的误差，例如0.5度，以确保找到90度的角
    return any(88 <= angle <= 92 for angle in angles)

def find_right_triangles():
    # 读取图片
    img = cv2.imread("blackwhite_geometry_1.png", cv2.IMREAD_GRAYSCALE)

    # 二值化图像
    _, thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)

    # 查找轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    right_triangle_count = 0

    for cnt in contours:
        # 多边形拟合
        epsilon = 0.04 * cv2.arcLength(cnt, True)  # 设置精度
        approx = cv2.approxPolyDP(cnt, epsilon, True)

        # 如果是三角形，approx 的长度应为 3
        if len(approx) == 3:
            if is_right_triangle(approx):
                right_triangle_count += 1

    return right_triangle_count

Please use the OpenCV library to solve the following problem: There is a black and white image with a black background and white foreground. The image contains various geometric shapes, such as triangles and polygons. Write a Python function to count the number of right-angled triangles in the image.
To answer the question, meet the following requirements:
1. Define the Python function `find_right_triangles()`, which does not require any input parameters and returns the number of right-angled triangles in the image.
2. The image file is "blackwhite_geometry_1.png", stored in the same path as the code.
3. The triangles in the image include acute, right, and obtuse triangles, and you need to correctly distinguish and only count the right-angled triangles.
4. Definition of a right-angled triangle: A triangle with one interior angle of 90 degrees.

#<INSERT>
if __name__ == '__main__':
    assert find_right_triangles()==1


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;

#<INSERT>

class BookOrganizerTest {
    public static int Main(string[] args) {
        List<Tuple<List<string>, string, List<string>>> testCases = new List<Tuple<List<string>, string, List<string>>> {
            new Tuple<List<string>, string, List<string>>(
                new List<string>{"Fantasy: The Great Adventure", "Sci-Fi: Space Odyssey", "Fantasy: Dragon Realm", "Mystery: The Lost Key"},
                "Fantasy",
                new List<string>{"Fantasy: The Great Adventure", "Fantasy: Dragon Realm"}
            ),
            new Tuple<List<string>, string, List<string>>(
                new List<string>{"Sci-Fi: Space Odyssey", "Mystery: The Lost Key"},
                "Fantasy",
                new List<string>{}
            ),
            new Tuple<List<string>, string, List<string>>(
                new List<string>{"Mystery: The Lost Key", "Mystery: The Hidden Chamber"},
                "Mystery",
                new List<string>{"Mystery: The Lost Key", "Mystery: The Hidden Chamber"}
            ),
            new Tuple<List<string>, string, List<string>>(
                new List<string>{"Horror: The Haunted House", "Romance: Love in the City"},
                "Horror",
                new List<string>{"Horror: The Haunted House"}
            )
        };

        bool allTestsPassed = true;
        foreach (var testCase in testCases) {
            List<string> titles = testCase.Item1;
            string genre = testCase.Item2;
            List<string> expected = testCase.Item3;
            List<string> result = BookOrganizer.SortByGenre(titles, genre);
            if (!result.SequenceEqual(expected)) {
                Console.WriteLine($"Test Failed: Expected [{string.Join(", ", expected)}], but got [{string.Join(", ", result)}]");
                allTestsPassed = false;
            }
        }

        if (allTestsPassed) {
            Console.WriteLine("All tests passed.");
            return 0;
        } else {
            Console.WriteLine("Some tests failed.");
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
class BookOrganizer {
    public static List<string> SortByGenre(List<string> titles, string genre) {
        List<string> sortedTitles = new List<string>();
        foreach (string title in titles) {
            if (title.StartsWith(genre)) {
                sortedTitles.Add(title);
            }
        }
        return sortedTitles;
    }
    public static void CheckFunction() {
        List<string> testTitles = new List<string>{"Fantasy: The Great Adventure", "Sci-Fi: Space Odyssey", "Fantasy: Dragon Realm", "Mystery: The Lost Key"};
        List<string> expected = new List<string>{"Fantasy: The Great Adventure", "Fantasy: Dragon Realm"};
        List<string> result = SortByGenre(testTitles, "Fantasy");
        Console.WriteLine($"Expected: [{string.Join(", ", expected)}]");
        Console.WriteLine($"Result: [{string.Join(", ", result)}]");
        Console.WriteLine($"Test Passed: {expected.SequenceEqual(result)}");
    }
}
class Program {

}

Imagine you're working on a project where you need to organize a bunch of book titles based on their genres. You've decided to write a function that helps you sort out the titles that belong to a specific genre. For example, if you're looking for books in the "Fantasy" genre, your function should be able to filter out all titles that start with the word "Fantasy". How would you write a C# function that takes a list of book titles and a genre as inputs and returns a list of titles that belong to that genre?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class BookOrganizer
{
    public static List<string> SortByGenre(List<string> titles, string genre) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;

#<INSERT>

class FinancialCalculatorTest {
    public static int Main(string[] args) {
        int result = 0;

        // Test Case 1
        if (FinancialCalculator.ConvertToNearestWholeNumber("10.5") != 11) {
            Console.WriteLine("Test Case 1 Failed");
            result = -1;
        }

        // Test Case 2
        if (FinancialCalculator.ConvertToNearestWholeNumber("2.4") != 2) {
            Console.WriteLine("Test Case 2 Failed");
            result = -1;
        }

        // Test Case 3
        if (FinancialCalculator.ConvertToNearestWholeNumber("-2.5") != -3) {
            Console.WriteLine("Test Case 3 Failed");
            result = -1;
        }

        // Test Case 4
        if (FinancialCalculator.ConvertToNearestWholeNumber("-3.6") != -4) {
            Console.WriteLine("Test Case 4 Failed");
            result = -1;
        }

        // Test Case 5
        if (FinancialCalculator.ConvertToNearestWholeNumber("0.5") != 1) {
            Console.WriteLine("Test Case 5 Failed");
            result = -1;
        }

        return result;
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;
class FinancialCalculator {
    public static int ConvertToNearestWholeNumber(string monetaryValue) {
        decimal value = decimal.Parse(monetaryValue);
        decimal fractionalPart = value % 1;
        if (fractionalPart == 0.5m || fractionalPart == -0.5m) {
            return (int)(value + Math.Sign(value) * 0.5m);
        } else {
            return (int)Math.Round(value);
        }
    }
    public static void Check() {
        Console.WriteLine(ConvertToNearestWholeNumber("10.5") == 11 ? "Pass" : "Fail");
        Console.WriteLine(ConvertToNearestWholeNumber("2.4") == 2 ? "Pass" : "Fail");
        Console.WriteLine(ConvertToNearestWholeNumber("-2.5") == -3 ? "Pass" : "Fail");
        Console.WriteLine(ConvertToNearestWholeNumber("-3.6") == -4 ? "Pass" : "Fail");
    }
}
class Program {

}

Imagine you're working on a financial application where precision is key, and you've encountered a scenario where you need to process user input as a string representing a monetary value. Your task is to create a function that accurately converts these string representations into the nearest whole number. However, there's a twist: when the decimal part of the number is exactly .5, you should always round up, regardless of whether the number is positive or negative. For example, "3.5" should round to 4, and "-3.5" should also round to -4, ensuring consistency in your application's financial calculations.

Can you write a function that meets these requirements, ensuring it handles both positive and negative numbers correctly?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class FinancialCalculator
{
    public static int ConvertToNearestWholeNumber(string monetaryValue) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;

#<INSERT>

class FinancialCalculatorTest {
    public static bool TestRoundMonetaryValue(string monetaryValue, int expectedResult) {
        int result = FinancialCalculator.RoundMonetaryValue(monetaryValue);
        return result == expectedResult;
    }

    public static int Main(string[] args) {
        bool allTestsPassed = true;

        allTestsPassed &= TestRoundMonetaryValue("10", 10);
        allTestsPassed &= TestRoundMonetaryValue("15.3", 15);
        allTestsPassed &= TestRoundMonetaryValue("14.5", 15);
        allTestsPassed &= TestRoundMonetaryValue("-14.5", -15);
        allTestsPassed &= TestRoundMonetaryValue("-10.5", -11);

        if (allTestsPassed) {
            return 0;
        } else {
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;
class FinancialCalculator {
    public static int RoundMonetaryValue(string monetaryValue) {
        decimal value = decimal.Parse(monetaryValue);
        decimal fractionalPart = value % 1;
        if (value > 0) {
            return (int)((fractionalPart >= 0.5m) ? Math.Ceiling(value) : Math.Floor(value));
        } else {
            return (int)((fractionalPart <= -0.5m) ? Math.Floor(value) : Math.Ceiling(value));
        }
    }
    public static void Check() {
        Console.WriteLine(RoundMonetaryValue("10"));
        Console.WriteLine(RoundMonetaryValue("15.3"));
        Console.WriteLine(RoundMonetaryValue("14.5"));
        Console.WriteLine(RoundMonetaryValue("-14.5"));
    }
}
class Program {

}

Imagine you're working on a financial application where precision is key, and you need to implement a feature that deals with user inputs in the form of strings representing monetary values. Your task is to write a method that takes these string representations, converts them to numbers, and rounds them to the nearest whole number. However, there's a twist: if the number is exactly halfway between two integers, you should always round it in a direction away from zero. This means positive numbers should round up, and negative numbers should round down in such cases. Can you create a method that accomplishes this?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class FinancialCalculator
{
    public static int RoundMonetaryValue(string monetaryValue) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class EvenNumberListGeneratorTest {
    public static int Main(string[] args) {
        bool allTestsPassed = true;

        // Test Case 1: n = 10
        string result1 = EvenNumberListGenerator.EvenNumbersSequence(10);
        if (result1 != "2,4,6,8,10") {
            Console.WriteLine("Test Case 1 Failed");
            allTestsPassed = false;
        }

        // Test Case 2: n = 1
        string result2 = EvenNumberListGenerator.EvenNumbersSequence(1);
        if (result2 != "") {
            Console.WriteLine("Test Case 2 Failed");
            allTestsPassed = false;
        }

        // Test Case 3: n = 11
        string result3 = EvenNumberListGenerator.EvenNumbersSequence(11);
        if (result3 != "2,4,6,8,10") {
            Console.WriteLine("Test Case 3 Failed");
            allTestsPassed = false;
        }

        // Test Case 4: n = 0
        string result4 = EvenNumberListGenerator.EvenNumbersSequence(0);
        if (result4 != "") {
            Console.WriteLine("Test Case 4 Failed");
            allTestsPassed = false;
        }

        // Test Case 5: n = 2
        string result5 = EvenNumberListGenerator.EvenNumbersSequence(2);
        if (result5 != "2") {
            Console.WriteLine("Test Case 5 Failed");
            allTestsPassed = false;
        }

        if (allTestsPassed) {
            Console.WriteLine("All tests passed successfully.");
            return 0;
        } else {
            Console.WriteLine("Some tests failed.");
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class EvenNumberListGenerator {
    public static string EvenNumbersSequence(int n) {
        if (n < 2) return "";
        return String.Join(",", Enumerable.Range(1, n/2).Select(x => x * 2));
    }
    public static void TestEvenNumbersSequence() {
        Debug.Assert(EvenNumbersSequence(10) == "2,4,6,8,10");
        Debug.Assert(EvenNumbersSequence(1) == "");
        Debug.Assert(EvenNumbersSequence(11) == "2,4,6,8,10");
        Debug.Assert(EvenNumbersSequence(0) == "");
        Console.WriteLine("All tests passed successfully.");
    }

}

Can you write a C# program that generates a comma-separated list of even numbers starting from 2 up to and including a specified number? If the specified number is less than 2, the program should return an empty string. For example, if the input is 10, the output should be "2,4,6,8,10". Make sure to include necessary imports, and also create a function to test the correctness of your solution with a few examples.

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class EvenNumberListGenerator
{
    public static string EvenNumbersSequence(int n) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class BookFilterTest {
    public static int Main(string[] args) {
        List<string> testTitles1 = new List<string> { "The Great Gatsby", "War and Peace", "The Grapes of Wrath" };
        List<string> expected1 = new List<string> { "The Great Gatsby" };
        if (!BookFilter.FilterTitlesWithKeyword(testTitles1, "Great").SequenceEqual(expected1)) {
            Console.WriteLine("Test 1 failed.");
            return -1;
        }

        List<string> testTitles2 = new List<string> { "Brave New World", "New Moon", "Something New" };
        List<string> expected2 = new List<string> { "Brave New World", "New Moon", "Something New" };
        if (!BookFilter.FilterTitlesWithKeyword(testTitles2, "New").SequenceEqual(expected2)) {
            Console.WriteLine("Test 2 failed.");
            return -1;
        }

        List<string> testTitles3 = new List<string> { "Harry Potter", "The Lord of the Rings", "The Hobbit" };
        List<string> expected3 = new List<string> { "The Hobbit" };
        if (!BookFilter.FilterTitlesWithKeyword(testTitles3, "Hobbit").SequenceEqual(expected3)) {
            Console.WriteLine("Test 3 failed.");
            return -1;
        }

        List<string> testTitles4 = new List<string> { "To Kill a Mockingbird", "Pride and Prejudice", "Moby Dick" };
        List<string> expected4 = new List<string> { "Pride and Prejudice" };
        if (!BookFilter.FilterTitlesWithKeyword(testTitles4, "and").SequenceEqual(expected4)) {
            Console.WriteLine("Test 4 failed.");
            return -1;
        }

        List<string> testTitles5 = new List<string> { "1984", "Animal Farm", "Brave New World" };
        List<string> expected5 = new List<string> { };
        if (!BookFilter.FilterTitlesWithKeyword(testTitles5, "None").SequenceEqual(expected5)) {
            Console.WriteLine("Test 5 failed.");
            return -1;
        }

        Console.WriteLine("All tests passed successfully.");
        return 0;
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class BookFilter {
    public static List<string> FilterTitlesWithKeyword(List<string> titles, string keyword) {
        return titles.Where(title => title.Contains(keyword)).ToList();
    }
    public static void Check() {
        var testTitles1 = new List<string> { "The Great Gatsby", "War and Peace", "The Grapes of Wrath" };
        var expected1 = new List<string> { "The Great Gatsby" };
        Debug.Assert(FilterTitlesWithKeyword(testTitles1, "Great").SequenceEqual(expected1));
        var testTitles2 = new List<string> { "Brave New World", "New Moon", "Something New" };
        var expected2 = new List<string> { "Brave New World", "New Moon", "Something New" };
        Debug.Assert(FilterTitlesWithKeyword(testTitles2, "New").SequenceEqual(expected2));
        Console.WriteLine("All tests passed successfully.");
    }

}

Imagine you're working on a project where you need to organize a collection of book titles based on whether they include a specific keyword or not. You're tasked with writing a C# method that sifts through a list of book titles and selects only those that contain a certain keyword. This method should be versatile enough to work with any list of strings and any keyword. How would you design a method in C# that filters a list of strings, returning only those that contain a specified keyword?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class BookFilter
{
    public static List<string> FilterTitlesWithKeyword(List<string> titles, string keyword) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

public class UniqueWordExtractorTest
{
    public static int Main()
    {
        var testCases = new List<Tuple<string, List<string>>>
        {
            new Tuple<string, List<string>>("Hello, world; hello universe", new List<string> { "Hello", "world", "hello", "universe" }),
            new Tuple<string, List<string>>("test, test; test; test", new List<string> { "test" }),
            new Tuple<string, List<string>>("one, two; three four; five", new List<string> { "one", "two", "three", "four", "five" }),
            new Tuple<string, List<string>>("a; a, a a", new List<string> { "a" }),
            new Tuple<string, List<string>>("", new List<string> { })
        };

        int failedTests = 0;

        foreach (var testCase in testCases)
        {
            var result = UniqueWordExtractor.ExtractUniqueWords(testCase.Item1);
            if (new HashSet<string>(result).SetEquals(testCase.Item2))
            {
                Console.WriteLine($"Test Passed: {testCase.Item1}");
            }
            else
            {
                Console.WriteLine($"Test Failed: {testCase.Item1}");
                failedTests++;
            }
        }

        return failedTests == 0 ? 0 : -1;
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
public class UniqueWordExtractor
{
    Takes a string containing words separated by spaces, commas, or semicolons,
    and returns a collection of unique words.
    Example:
    - Given the string "Hello, world; hello universe", it should return a collection
    containing "Hello", "world", "hello", and "universe".
    public static List<string> ExtractUniqueWords(string paragraph)
    {
        char[] delimiters = new char[] { ' ', ',', ';' };
        var words = paragraph.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
        return words.Distinct().ToList();
    }
}
class Program
{

        CheckFunction();
    }
    static void CheckFunction()
    {
        var testString = "Hello, world; hello universe";
        var expected = new List<string> { "Hello", "world", "hello", "universe" };
        var result = UniqueWordExtractor.ExtractUniqueWords(testString);
        if (new HashSet<string>(result).SetEquals(expected))
        {
            Console.WriteLine("Test Passed!");
        }
        else
        {
            Console.WriteLine("Test Failed.");
        }
    }
}

Imagine you're working on a text processing application where you need to extract all the unique words from a given paragraph. The paragraph could contain words separated by spaces, commas, or even semicolons. Your challenge is to write a method that takes this paragraph as input and returns a collection of unique words, ensuring no duplicates are present, regardless of how they are separated in the input string.

For instance, if the input is "Hello, world; hello universe", your method should return a collection containing "Hello", "world", "hello", and "universe".

Can you craft a piece of code in C# that accomplishes this task efficiently?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class UniqueWordExtractor
{
public class UniqueWordExtractor
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Linq;

#<INSERT>

class TextTransformerTest
{
    public static int Main()
    {
        bool allTestsPassed = true;

        // Test case 1
        allTestsPassed &= Test("1234", "4321");
        // Test case 2
        allTestsPassed &= Test("abCD", "ABcd");
        // Test case 3
        allTestsPassed &= Test("#a@C", "#A@c");
        // Test case 4
        allTestsPassed &= Test("HelloWorld", "hELLOwORLD");
        // Test case 5
        allTestsPassed &= Test("1234!@#$", "$#@!4321");

        return allTestsPassed ? 0 : -1;
    }

    private static bool Test(string input, string expected)
    {
        string result = TextTransformer.TransformString(input);
        Console.WriteLine($"Input: {input}, Expected: {expected}, Result: {result}");
        return result == expected;
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Linq;
class TextTransformer
{
    public static string TransformString(string input)
    {
        bool containsLetters = input.Any(char.IsLetter);
        if (!containsLetters)
        {
            return new string(input.Reverse().ToArray());
        }
        return new string(input.Select(c => char.IsLetter(c) ? (char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c)) : c).ToArray());
    }
    public static void Check()
    {
        Debug.Assert(TransformString("1234") == "4321");
        Debug.Assert(TransformString("abCD") == "ABcd");
        Debug.Assert(TransformString("#a@C") == "#A@c");
    }
}
class Program
{

}

Imagine you have a piece of text that you want to transform according to specific rules. Write a C# method that takes a string as input and applies the following transformations:

- If a character is a letter, change its case from uppercase to lowercase or from lowercase to uppercase.
- If the string does not contain any letters, reverse the entire string.
- All non-letter characters should remain unchanged.

Your task is to implement this transformation and return the modified string.

Here are a few examples of how your method should work:

- If the input is "1234", the output should be "4321".
- If the input is "abCD", the output should be "ABcd".
- If the input is "#a@C", the output should be "#A@c".

Make sure to include a function to check your solution with the provided examples.

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class TextTransformer
{
    public static string TransformString(string input)
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;

#<INSERT>

public class DigitSorterTest
{
    public static int Main()
    {
        var testCases = new Dictionary<List<int>, List<string>>
        {
            { new List<int> { 2, 1, 1, 4, 5, 8, 2, 3 }, new List<string> { "Eight", "Five", "Four", "Three", "Two", "Two", "One", "One" } },
            { new List<int>(), new List<string>() },
            { new List<int> { 1, -1, 55 }, new List<string> { "One" } },
            { new List<int> { 9, 7, 3, 6 }, new List<string> { "Nine", "Seven", "Six", "Three" } },
            { new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, new List<string> { "Nine", "Eight", "Seven", "Six", "Five", "Four", "Three", "Two", "One" } }
        };

        foreach (var testCase in testCases)
        {
            var result = DigitSorter.SortAndConvert(testCase.Key);
            if (!result.SequenceEqual(testCase.Value))
            {
                Console.WriteLine($"Test case failed for input: {string.Join(", ", testCase.Key)}");
                return -1;
            }
        }

        Console.WriteLine("All test cases passed!");
        return 0;
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
public class DigitSorter
{
    public static List<string> SortAndConvert(List<int> numbers)
    {
        string[] numberWords = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
        List<int> filteredNumbers = numbers.Where(n => n >= 1 && n <= 9).ToList();
        filteredNumbers.Sort();
        filteredNumbers.Reverse();
        List<string> result = new List<string>();
        foreach (int number in filteredNumbers)
        {
            result.Add(numberWords[number - 1]);
        }
        return result;
    }
    public static void Check()
    {
        var testCases = new Dictionary<List<int>, List<string>>
        {
            { new List<int> { 2, 1, 1, 4, 5, 8, 2, 3 }, new List<string> { "Eight", "Five", "Four", "Three", "Two", "Two", "One", "One" } },
            { new List<int>(), new List<string>() },
            { new List<int> { 1, -1, 55 }, new List<string> { "One" } }
        };
        foreach (var testCase in testCases)
        {
            var result = SortAndConvert(testCase.Key);
            Debug.Assert(result.SequenceEqual(testCase.Value), "Test case failed for input: " + string.Join(", ", testCase.Key));
        }
    }
}
class Program
{

}

Imagine you have a collection of integer values, and you need to organize them in a very specific way. Your task is to write a method that takes a list of integers and performs the following operations:

1. Filters out all integers that are not within the range of 1 to 9, inclusive.
2. Sorts the remaining integers in ascending order.
3. Reverses the sorted list.
4. Converts each integer into its corresponding English word representation ("One" for 1, "Two" for 2, etc.).

For instance, if you're given the list `[2, 1, 1, 4, 5, 8, 2, 3]`, the method should return `["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]`. If the list is empty or contains no integers within the specified range, the method should return an empty list.

Can you write a C# method that accomplishes this task?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class DigitSorter
{
public class DigitSorter
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class DigitWordTransformerTest
{
    public static int Main(string[] args)
    {
        var testCases = new List<List<int>>
        {
            new List<int>{2, 1, 4, 8, 3},
            new List<int>{},
            new List<int>{10, -1, 5},
            new List<int>{9, 7, 1, 6, 3},
            new List<int>{2, 2, 2, 2}
        };

        var expectedOutputs = new List<List<string>>
        {
            new List<string>{"Eight", "Four", "Three", "Two", "One"},
            new List<string>{},
            new List<string>{"Five"},
            new List<string>{"Nine", "Seven", "Six", "Three", "One"},
            new List<string>{"Two", "Two", "Two", "Two"}
        };

        int failedTests = 0;

        for (int i = 0; i < testCases.Count; i++)
        {
            var output = DigitWordTransformer.TransformDigitsToWords(testCases[i]);
            if (!output.SequenceEqual(expectedOutputs[i]))
            {
                Console.WriteLine($"Test Case {i + 1}: Fail");
                failedTests++;
            }
            else
            {
                Console.WriteLine($"Test Case {i + 1}: Pass");
            }
        }

        return failedTests == 0 ? 0 : -1;
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class DigitWordTransformer
{
    public static List<string> TransformDigitsToWords(List<int> numbers)
    {
        var digitWords = new Dictionary<int, string>
        {
            {1, "One"}, {2, "Two"}, {3, "Three"}, {4, "Four"},
            {5, "Five"}, {6, "Six"}, {7, "Seven"}, {8, "Eight"}, {9, "Nine"}
        };
        return numbers
            .Where(number => digitWords.ContainsKey(number))
            .OrderBy(number => number)
            .Reverse()
            .Select(number => digitWords[number])
            .ToList();
    }
    public static void Check()
    {
        var testCases = new List<List<int>>
        {
            new List<int>{2, 1, 4, 8, 3},
            new List<int>{},
            new List<int>{10, -1, 5}
        };
        var expectedOutputs = new List<List<string>>
        {
            new List<string>{"Eight", "Four", "Three", "Two", "One"},
            new List<string>{},
            new List<string>{"Five"}
        };
        for (int i = 0; i < testCases.Count; i++)
        {
            var output = TransformDigitsToWords(testCases[i]);
            Console.WriteLine($"Test Case {i + 1}: {(output.SequenceEqual(expectedOutputs[i]) ? "Pass" : "Fail")}");
        }
    }

}

Imagine you have a collection of numbers, and your task is to filter, sort, and transform these numbers in a very specific way. You need to focus on numbers within a certain range, specifically from 1 to 9, inclusive. Your job is to first filter out any numbers outside this range, then sort the remaining numbers in ascending order. After sorting, you'll reverse the order of these numbers. Finally, you'll convert each number into its corresponding English word representation. For example, 1 becomes "One", 2 becomes "Two", and so on, up to 9 which becomes "Nine". If the input list is empty, your output should also be an empty list. If the list contains numbers outside the specified range, simply ignore those numbers and proceed with the ones that fit the criteria.

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class DigitWordTransformer
{
    public static List<string> TransformDigitsToWords(List<int> numbers)
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class StringListComparerTest {
    public static int Main(string[] args) {
        bool allTestsPassed = true;

        // Test Case 1: Both lists are empty
        var result1 = StringListComparer.CompareByCharCount(new List<string>(), new List<string>());
        if (!result1.SequenceEqual(new List<string>())) {
            Console.WriteLine("Test Case 1 Failed");
            allTestsPassed = false;
        }

        // Test Case 2: First list has more characters
        var result2 = StringListComparer.CompareByCharCount(new List<string>{"apple", "banana"}, new List<string>{"cherry", "date"});
        if (!result2.SequenceEqual(new List<string>{"cherry", "date"})) {
            Console.WriteLine("Test Case 2 Failed");
            allTestsPassed = false;
        }

        // Test Case 3: Second list has more characters
        var result3 = StringListComparer.CompareByCharCount(new List<string>{"hello", "world"}, new List<string>{"hello", "universe", "!"});
        if (!result3.SequenceEqual(new List<string>{"hello", "world"})) {
            Console.WriteLine("Test Case 3 Failed");
            allTestsPassed = false;
        }

        // Test Case 4: First list has fewer characters
        var result4 = StringListComparer.CompareByCharCount(new List<string>{"short"}, new List<string>{"longer", "list", "of", "strings"});
        if (!result4.SequenceEqual(new List<string>{"short"})) {
            Console.WriteLine("Test Case 4 Failed");
            allTestsPassed = false;
        }

        // Test Case 5: Both lists have the same total character count
        var result5 = StringListComparer.CompareByCharCount(new List<string>{"one", "two"}, new List<string>{"three", "four"});
        if (!result5.SequenceEqual(new List<string>{"one", "two"})) {
            Console.WriteLine("Test Case 5 Failed");
            allTestsPassed = false;
        }

        if (allTestsPassed) {
            Console.WriteLine("All tests passed!");
            return 0;
        } else {
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class StringListComparer {
    public static List<string> CompareByCharCount(List<string> firstList, List<string> secondList) {
        int firstListTotalChars = firstList.Sum(item => item.Length);
        int secondListTotalChars = secondList.Sum(item => item.Length);
        return firstListTotalChars <= secondListTotalChars ? firstList : secondList;
    }
    public static void Check() {
        Debug.Assert(CompareByCharCount(new List<string>(), new List<string>()).SequenceEqual(new List<string>()));
        Debug.Assert(CompareByCharCount(new List<string>{"apple", "banana"}, new List<string>{"cherry", "date"}).SequenceEqual(new List<string>{"cherry", "date"}));
        Debug.Assert(CompareByCharCount(new List<string>{"hello", "world"}, new List<string>{"hello", "universe", "!"}).SequenceEqual(new List<string>{"hello", "world"}));
        Debug.Assert(CompareByCharCount(new List<string>{"short"}, new List<string>{"longer", "list", "of", "strings"}).SequenceEqual(new List<string>{"short"}));
        Console.WriteLine("All checks passed!");
    }

}

Imagine you're working on a project where you need to compare two collections of text data, specifically, two lists of strings. Your task is to write a method that takes these two lists as input and determines which list has a smaller total character count. If both lists have an equal number of characters, your method should return the first list. This functionality could be useful in scenarios where you need to optimize data storage or transmission by choosing the more compact dataset. Can you craft a C# method to accomplish this?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class StringListComparer
{
    public static List<string> CompareByCharCount(List<string> firstList, List<string> secondList) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class TextAnalyzerTest
{
    public static int Main(string[] args)
    {
        bool allTestsPassed = true;

        // Test Case 1
        var testSentence1 = "Hello, world! Welcome to coding.";
        var expectedOutput1 = new List<string> { "Hello", "world!", "Welcome", "to", "coding." };
        var result1 = TextAnalyzer.ExtractWordsFromSentence(testSentence1);
        if (!result1.SequenceEqual(expectedOutput1))
        {
            Console.WriteLine("Test Case 1 Failed");
            allTestsPassed = false;
        }

        // Test Case 2
        var testSentence2 = "C#, Java, Python, and JavaScript.";
        var expectedOutput2 = new List<string> { "C#", "Java", "Python", "and", "JavaScript." };
        var result2 = TextAnalyzer.ExtractWordsFromSentence(testSentence2);
        if (!result2.SequenceEqual(expectedOutput2))
        {
            Console.WriteLine("Test Case 2 Failed");
            allTestsPassed = false;
        }

        // Test Case 3
        var testSentence3 = "One, two, three, four, five.";
        var expectedOutput3 = new List<string> { "One", "two", "three", "four", "five." };
        var result3 = TextAnalyzer.ExtractWordsFromSentence(testSentence3);
        if (!result3.SequenceEqual(expectedOutput3))
        {
            Console.WriteLine("Test Case 3 Failed");
            allTestsPassed = false;
        }

        // Test Case 4
        var testSentence4 = "No,spaces,or,commas";
        var expectedOutput4 = new List<string> { "No", "spaces", "or", "commas" };
        var result4 = TextAnalyzer.ExtractWordsFromSentence(testSentence4);
        if (!result4.SequenceEqual(expectedOutput4))
        {
            Console.WriteLine("Test Case 4 Failed");
            allTestsPassed = false;
        }

        // Test Case 5
        var testSentence5 = "  Leading and trailing spaces  ";
        var expectedOutput5 = new List<string> { "Leading", "and", "trailing", "spaces" };
        var result5 = TextAnalyzer.ExtractWordsFromSentence(testSentence5);
        if (!result5.SequenceEqual(expectedOutput5))
        {
            Console.WriteLine("Test Case 5 Failed");
            allTestsPassed = false;
        }

        if (allTestsPassed)
        {
            Console.WriteLine("All tests passed successfully.");
            return 0;
        }
        else
        {
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class TextAnalyzer
{
    public static List<string> ExtractWordsFromSentence(string sentence)
    {
        char[] delimiters = new char[] { ',', ' ' };
        List<string> words = sentence.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).ToList();
        return words;
    }
    public static void CheckFunction()
    {
        var testSentence1 = "Hello, world! Welcome to coding.";
        var expectedOutput1 = new List<string> { "Hello", "world!", "Welcome", "to", "coding." };
        Debug.Assert(ExtractWordsFromSentence(testSentence1).SequenceEqual(expectedOutput1));
        var testSentence2 = "C#, Java, Python, and JavaScript.";
        var expectedOutput2 = new List<string> { "C#", "Java", "Python", "and", "JavaScript." };
        Debug.Assert(ExtractWordsFromSentence(testSentence2).SequenceEqual(expectedOutput2));
        Console.WriteLine("All tests passed successfully.");
    }

}

Imagine you're working on a text processing application where you need to analyze sentences. Your current task is to write a method that takes a sentence as input and returns each word in that sentence as elements of a list. The sentence could be separated by either spaces or commas. For instance, if the input is "Hello, world! Welcome to coding.", your method should return a list containing ["Hello", "world!", "Welcome", "to", "coding."]. How would you design such a method in C# to accomplish this task efficiently?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class TextAnalyzer
{
    public static List<string> ExtractWordsFromSentence(string sentence)
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;

#<INSERT>

class HexadecimalConverterTest {
    public static bool RunTests() {
        var testData = new Dictionary<int, string> {
            { 255, "hxffhx" },
            { 10, "hxahx" },
            { 16, "hx10hx" },
            { 0, "hx0hx" },
            { 1024, "hx400hx" }
        };

        foreach (var test in testData) {
            var result = HexadecimalConverter.ConvertToHex(test.Key);
            if (result != test.Value) {
                Console.WriteLine($"Test failed for input {test.Key}: Expected {test.Value}, got {result}");
                return false;
            }
        }
        return true;
    }

    public static void Main(string[] args) {
        if (RunTests()) {
            Console.WriteLine("All tests passed.");
            System.Environment.Exit(0);
        } else {
            Console.WriteLine("Some tests failed.");
            System.Environment.Exit(-1);
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;
class HexadecimalConverter {
    public static string ConvertToHex(int number) {
        return "hx" + number.ToString("X").ToLower() + "hx";
    }

    public static bool CheckConversion() {
        var testData = new Dictionary<int, string> {
            { 255, "hxffhx" },
            { 10, "hxahx" },
            { 16, "hx10hx" },
            { 0, "hx0hx" }
        };
        foreach (var test in testData) {
            var result = ConvertToHex(test.Key);
            if (result != test.Value) {
                Console.WriteLine($"Test failed for input {test.Key}: Expected {test.Value}, got {result}");
                return false;
            }
        }
        return true;
    }
}

Write a program in C# that takes an integer input and converts it to a hexadecimal string. The output string should start and end with the characters 'hx' to indicate the format. For example, converting the integer 255 should result in the output "hxffhx". Ensure your solution includes all necessary imports and is fully self-contained.

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class HexadecimalConverter
{
    public static string ConvertToHex(int number) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;

#<INSERT>

class ScoreComparerTest {
    public static int Main(string[] args) {
        bool allTestsPassed = true;

        // Test Case 1
        var result1 = ScoreComparer.CompareScores(new List<int>{1, 2, 3, 4, 5, 1}, new List<int>{1, 2, 3, 4, 2, -2});
        var expected1 = new List<int>{0, 0, 0, 0, 3, 3};
        allTestsPassed &= result1.SequenceEqual(expected1);
        Console.WriteLine($"Test 1 Passed: {result1.SequenceEqual(expected1)}");

        // Test Case 2
        var result2 = ScoreComparer.CompareScores(new List<int>{0, 5, 0, 0, 0, 4}, new List<int>{4, 1, 1, 0, 0, -2});
        var expected2 = new List<int>{4, 4, 1, 0, 0, 6};
        allTestsPassed &= result2.SequenceEqual(expected2);
        Console.WriteLine($"Test 2 Passed: {result2.SequenceEqual(expected2)}");

        // Test Case 3
        var result3 = ScoreComparer.CompareScores(new List<int>{10, 20, 30, 40, 50}, new List<int>{10, 25, 30, 45, 55});
        var expected3 = new List<int>{0, 5, 0, 5, 5};
        allTestsPassed &= result3.SequenceEqual(expected3);
        Console.WriteLine($"Test 3 Passed: {result3.SequenceEqual(expected3)}");

        if (allTestsPassed) {
            return 0;
        } else {
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
class ScoreComparer {
    public static List<int> CompareScores(List<int> actualScores, List<int> predictedScores) {
        List<int> accuracyResults = new List<int>();
        for (int i = 0; i < actualScores.Count; i++) {
            accuracyResults.Add(Math.Abs(actualScores[i] - predictedScores[i]));
        }
        return accuracyResults;
    }
    public static void Check() {
        var result1 = CompareScores(new List<int>{1, 2, 3, 4, 5, 1}, new List<int>{1, 2, 3, 4, 2, -2});
        var expected1 = new List<int>{0, 0, 0, 0, 3, 3};
        Console.WriteLine($"Test 1 Passed: {result1.SequenceEqual(expected1)}");
        var result2 = CompareScores(new List<int>{0, 5, 0, 0, 0, 4}, new List<int>{4, 1, 1, 0, 0, -2});
        var expected2 = new List<int>{4, 4, 1, 0, 0, 6};
        Console.WriteLine($"Test 2 Passed: {result2.SequenceEqual(expected2)}");
    }
}
class Program {

}

Imagine you're keeping track of a series of predictions for game scores. After all the games have concluded, you want to see how well your predictions matched up with the actual outcomes. Write a program that compares the predicted scores against the actual scores of the games. Your program should take two lists as input: one with the actual scores and another with the predicted scores, both lists having the same length. It should then return a list indicating the accuracy of the predictions. For each game, if the prediction was spot-on, the result should be 0. Otherwise, the result should be the absolute difference between the predicted score and the actual score. Can you craft a solution that accomplishes this task?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class ScoreComparer
{
    public static List<int> CompareScores(List<int> actualScores, List<int> predictedScores) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class DataAnalyzerTest
{
    public static int Main(string[] args)
    {
        bool allTestsPassed = true;

        // Test Case 1
        var result1 = DataAnalyzer.FindCommonDescending(new List<int> { 1, 4, 3, 34, 653, 2, 5 }, new List<int> { 5, 7, 1, 9, 653, 121 });
        var expected1 = new List<int> { 653, 5, 1 };
        allTestsPassed &= result1.SequenceEqual(expected1);

        // Test Case 2
        var result2 = DataAnalyzer.FindCommonDescending(new List<int> { 5, 3, 2, 8 }, new List<int> { 3, 2 });
        var expected2 = new List<int> { 3, 2 };
        allTestsPassed &= result2.SequenceEqual(expected2);

        // Test Case 3
        var result3 = DataAnalyzer.FindCommonDescending(new List<int> { 10, 20, 30, 40 }, new List<int> { 10, 20, 30, 40 });
        var expected3 = new List<int> { 40, 30, 20, 10 };
        allTestsPassed &= result3.SequenceEqual(expected3);

        // Test Case 4
        var result4 = DataAnalyzer.FindCommonDescending(new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 });
        var expected4 = new List<int> { };
        allTestsPassed &= result4.SequenceEqual(expected4);

        // Test Case 5
        var result5 = DataAnalyzer.FindCommonDescending(new List<int> { -1, -2, -3 }, new List<int> { -3, -2, -1 });
        var expected5 = new List<int> { -1, -2, -3 };
        allTestsPassed &= result5.SequenceEqual(expected5);

        if (allTestsPassed)
        {
            Console.WriteLine("All tests passed.");
            return 0;
        }
        else
        {
            Console.WriteLine("Some tests failed.");
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class DataAnalyzer
{
    public static List<int> FindCommonDescending(List<int> firstList, List<int> secondList)
    {
        var commonElements = new SortedSet<int>(firstList.Intersect(secondList)).Reverse().ToList();
        return commonElements;
    }
    public static void Check()
    {
        var result1 = FindCommonDescending(new List<int> { 1, 4, 3, 34, 653, 2, 5 }, new List<int> { 5, 7, 1, 9, 653, 121 });
        Console.WriteLine($"Result 1: {string.Join(", ", result1)}");
        var result2 = FindCommonDescending(new List<int> { 5, 3, 2, 8 }, new List<int> { 3, 2 });
        Console.WriteLine($"Result 2: {string.Join(", ", result2)}");
    }
}
class Program
{

}

Imagine you're working on a project where you need to analyze data from two different sources. Your task is to find the elements that are common in both datasets, but with a twist. You need to ensure that the common elements are not only unique but also presented in descending order. For example, if you're comparing sales data from two different quarters, you want to identify which products were popular in both periods, but list them starting from the most sold to the least. Can you write a function that accomplishes this?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class DataAnalyzer
{
    public static List<int> FindCommonDescending(List<int> firstList, List<int> secondList)
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;

#<INSERT>

class MusicParserTest
{
    public static int Main(string[] args)
    {
        bool allTestsPassed = true;

        // Test case 1
        List<int> result1 = MusicParser.InterpretMusic("W H+ Q");
        List<int> expected1 = new List<int> { 4, 2, 1 };
        allTestsPassed &= result1.SequenceEqual(expected1);

        // Test case 2
        List<int> result2 = MusicParser.InterpretMusic("H+ Q Q W");
        List<int> expected2 = new List<int> { 2, 1, 1, 4 };
        allTestsPassed &= result2.SequenceEqual(expected2);

        // Test case 3
        List<int> result3 = MusicParser.InterpretMusic("W W W");
        List<int> expected3 = new List<int> { 4, 4, 4 };
        allTestsPassed &= result3.SequenceEqual(expected3);

        // Test case 4
        List<int> result4 = MusicParser.InterpretMusic("Q Q Q Q");
        List<int> expected4 = new List<int> { 1, 1, 1, 1 };
        allTestsPassed &= result4.SequenceEqual(expected4);

        // Test case 5
        List<int> result5 = MusicParser.InterpretMusic("H+ H+ H+ H+");
        List<int> expected5 = new List<int> { 2, 2, 2, 2 };
        allTestsPassed &= result5.SequenceEqual(expected5);

        if (allTestsPassed)
        {
            return 0;
        }
        else
        {
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
class MusicParser
{
    public static List<int> InterpretMusic(string musicNotes)
    {
        List<int> durations = new List<int>();
        string[] notes = musicNotes.Split(' ');
        foreach (string note in notes)
        {
            switch (note)
            {
                case "W":
                    durations.Add(4);
                    break;
                case "H+":
                    durations.Add(2);
                    break;
                case "Q":
                    durations.Add(1);
                    break;
            }
        }
        return durations;
    }
    public static void Check()
    {
        var result = InterpretMusic("W H+ Q H+ H+ Q Q Q Q W W");
        var expected = new List<int> { 4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4 };
        Console.WriteLine($"Result: {string.Join(", ", result)}");
        Console.WriteLine($"Expected: {string.Join(", ", expected)}");
        Console.WriteLine($"Correct: {result.SequenceEqual(expected)}");
    }
}
class Program
{

}

Suppose you are developing a software module for a digital music sheet application. You need to write a function that interprets a string of ASCII characters representing different types of musical notes and their durations. The input string will contain symbols that map to the duration of the notes in a simple encoding scheme, and your task is to convert this string into a list of integers, where each integer represents the duration of the corresponding note in the input string. The encoding is as follows:

- 'W' represents a whole note, which lasts for 4 beats.
- 'H' followed by a '+' (i.e., 'H+') represents a half note, which lasts for 2 beats.
- 'Q' stands for a quarter note, lasting 1 beat.

For example, given the input string "W H+ Q H+ H+ Q Q Q Q W W", your function should return a list of integers corresponding to the duration of each note in beats.

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class MusicParser
{
    public static List<int> InterpretMusic(string musicNotes)
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;

#<INSERT>

class SequenceAnalyzerTest
{
    public static int Main(string[] args)
    {
        bool allTestsPassed = true;

        // Test case 1
        List<int> test1 = new List<int> { 1, 2, 4, 3, 5 };
        int result1 = SequenceAnalyzer.FindDescendingIndex(test1);
        if (result1 != 3)
        {
            Console.WriteLine($"Test 1 failed: Expected 3, got {result1}");
            allTestsPassed = false;
        }

        // Test case 2
        List<int> test2 = new List<int> { 1, 2, 3 };
        int result2 = SequenceAnalyzer.FindDescendingIndex(test2);
        if (result2 != -1)
        {
            Console.WriteLine($"Test 2 failed: Expected -1, got {result2}");
            allTestsPassed = false;
        }

        // Test case 3
        List<int> test3 = new List<int> { 5, 4, 3, 2, 1 };
        int result3 = SequenceAnalyzer.FindDescendingIndex(test3);
        if (result3 != 1)
        {
            Console.WriteLine($"Test 3 failed: Expected 1, got {result3}");
            allTestsPassed = false;
        }

        // Test case 4
        List<int> test4 = new List<int> { 10, 20, 30, 25, 40 };
        int result4 = SequenceAnalyzer.FindDescendingIndex(test4);
        if (result4 != 3)
        {
            Console.WriteLine($"Test 4 failed: Expected 3, got {result4}");
            allTestsPassed = false;
        }

        if (allTestsPassed)
        {
            Console.WriteLine("All test cases passed successfully.");
            return 0;
        }
        else
        {
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
class SequenceAnalyzer
{
    public static int FindDescendingIndex(List<int> numbers)
    {
        for (int i = 1; i < numbers.Count; i++)
        {
            if (numbers[i] < numbers[i - 1])
            {
                return i;
            }
        }
        return -1;
    }
    ) == 3);
        Debug.Assert(FindDescendingIndex(new List<int>{1, 2, 3}) == -1);
        Debug.Assert(FindDescendingIndex(new List<int>{5, 4, 3, 2, 1}) == 1);
        Debug.Assert(FindDescendingIndex(new List<int>{10, 20, 30, 25, 40}) == 3);
        Console.WriteLine("All test cases passed successfully.");
    }
}

Imagine you're working on a data analysis tool and you need to find a specific pattern in your dataset. Specifically, you're looking for the first occurrence where a number in a sequence is less than the number that comes right before it. You're dealing with a list of unique integers, and you want to identify the position of the number that breaks the ascending order. If all numbers are in ascending order, your function should return -1, indicating that the sequence is already sorted. Can you write a C# function to accomplish this?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class SequenceAnalyzer
{
    public static int FindDescendingIndex(List<int> numbers)
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class TextAnalyzerTest {
    public static int RunTests() {
        bool allTestsPassed = true;

        // Test case 1
        int result1 = TextAnalyzer.UniqueLetterCount("Hello, World! 123");
        if (result1 != 7) {
            Console.WriteLine($"Test 1 failed: Expected 7, got {result1}");
            allTestsPassed = false;
        }

        // Test case 2
        int result2 = TextAnalyzer.UniqueLetterCount("Apple123");
        if (result2 != 4) {
            Console.WriteLine($"Test 2 failed: Expected 4, got {result2}");
            allTestsPassed = false;
        }

        // Test case 3
        int result3 = TextAnalyzer.UniqueLetterCount("Function!@#");
        if (result3 != 7) {
            Console.WriteLine($"Test 3 failed: Expected 7, got {result3}");
            allTestsPassed = false;
        }

        // Test case 4
        int result4 = TextAnalyzer.UniqueLetterCount("1234567890");
        if (result4 != 0) {
            Console.WriteLine($"Test 4 failed: Expected 0, got {result4}");
            allTestsPassed = false;
        }

        // Test case 5
        int result5 = TextAnalyzer.UniqueLetterCount("AaBbCc");
        if (result5 != 3) {
            Console.WriteLine($"Test 5 failed: Expected 3, got {result5}");
            allTestsPassed = false;
        }

        if (allTestsPassed) {
            Console.WriteLine("All tests passed!");
            return 0;
        } else {
            return -1;
        }
    }

    static void Main(string[] args) {
        int result = RunTests();
        Environment.Exit(result);
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class TextAnalyzer {
    public static int UniqueLetterCount(string input) {
        var lettersOnly = input.ToLower().Where(char.IsLetter);
        HashSet<char> uniqueLetters = new HashSet<char>(lettersOnly);
        return uniqueLetters.Count;
    }
    public static void Check() {
        Debug.Assert(UniqueLetterCount("Hello, World! 123") == 7);
        Debug.Assert(UniqueLetterCount("Apple123") == 4);
        Debug.Assert(UniqueLetterCount("Function!@#") == 7);
        Debug.Assert(UniqueLetterCount("1234567890") == 0);
        Debug.Assert(UniqueLetterCount("AaBbCc") == 3);
        Console.WriteLine("All checks passed!");
    }

}

Imagine you're working on a text analysis tool and you need to figure out how many unique letters are in a given piece of text, ignoring any numbers or special characters and not differentiating between uppercase and lowercase. For example, if someone inputs "Hello, World! 123", your tool should tell them there are 7 unique letters. Can you write a C# program that accomplishes this?

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class TextAnalyzer
{
    public static int UniqueLetterCount(string input) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Text.RegularExpressions;

#<INSERT>

class TextFormatterTest
{
    public static int Main(string[] args)
    {
        var testData = new Dictionary<string, string>
        {
            { "This is a test", "This_is_a_test" },
            { "This   is  a    test", "This-is_a-test" },
            { "  Leading and trailing  ", "_Leading_and_trailing_" },
            { "NoSpaces", "NoSpaces" },
            { "     Multiple     spaces    ", "-Multiple-spaces-" }
        };

        foreach (var test in testData)
        {
            string result = TextFormatter.FormatText(test.Key);
            if (result != test.Value)
            {
                Console.WriteLine($"Fail: \"{test.Key}\" -> \"{result}\" (Expected: \"{test.Value}\")");
                return -1;
            }
        }

        Console.WriteLine("All tests passed!");
        return 0;
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Text.RegularExpressions;
class TextFormatter
{
    public static string FormatText(string input)
    {
        string result = Regex.Replace(input, @"\s{3,}", "-");
        result = Regex.Replace(result, @"\s{1,2}", "_");
        return result;
    }
}
class Program
{
    public static void CheckFormatting()
    {
        var testData = new Dictionary<string, string>
        {
            { "This is a test", "This_is_a_test" },
            { "This   is  a    test", "This-is_a-test" },
            { "  Leading and trailing  ", "_Leading_and_trailing_" },
            { "NoSpaces", "NoSpaces" },
            { "     Multiple     spaces    ", "-Multiple-spaces-" }
        };
        foreach (var test in testData)
        {
            string result = TextFormatter.FormatText(test.Key);
            if (result == test.Value)
            {
                Console.WriteLine($"Pass: \"{test.Key}\" -> \"{result}\"");
            }
            else
            {
                Console.WriteLine($"Fail: \"{test.Key}\" -> \"{result}\" (Expected: \"{test.Value}\")");
            }
        }
    }

}

You're working on a text processing module for a new application, and you've encountered a specific formatting issue that needs to be addressed. The task is to write a method that takes a string as input and performs the following transformations:

1. Every instance of one or two spaces should be replaced with a single underscore (`_`).
2. Any occurrence of three or more consecutive spaces should be replaced with a single dash (`-`).

The goal is to ensure that the text adheres to a specific format for further processing. Here's what you need to do:

- Implement a method named `FormatText` in a class named `TextFormatter`.
- The method should accept a single string argument and return a modified string according to the rules mentioned above.
- Make sure to handle edge cases, such as strings that start or end with spaces, or strings that contain long sequences of spaces.

To verify the correctness of your implementation, include a method named `CheckFormatting` that tests the `FormatText` method with various scenarios and prints out whether it succeeds.

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class TextFormatter
{
    public static string FormatText(string input)
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class ArrayProcessorTest {
    public static int Main(string[] args) {
        bool allTestsPassed = true;

        // Test case 1
        int[] testArray1 = {1, -2, 3, 0};
        int[] expectedOutput1 = {0, 1, 9};
        if (!ArrayProcessor.FilterAndSquare(testArray1).SequenceEqual(expectedOutput1)) {
            Console.WriteLine("Test case 1 failed.");
            allTestsPassed = false;
        }

        // Test case 2
        int[] testArray2 = {-1, -3, -5, 2, 4, 6};
        int[] expectedOutput2 = {4, 16, 36};
        if (!ArrayProcessor.FilterAndSquare(testArray2).SequenceEqual(expectedOutput2)) {
            Console.WriteLine("Test case 2 failed.");
            allTestsPassed = false;
        }

        // Test case 3
        int[] testArray3 = {-10, -20};
        int[] expectedOutput3 = {};
        if (!ArrayProcessor.FilterAndSquare(testArray3).SequenceEqual(expectedOutput3)) {
            Console.WriteLine("Test case 3 failed.");
            allTestsPassed = false;
        }

        // Test case 4
        int[] testArray4 = {-1, 0, 1, 2, 3};
        int[] expectedOutput4 = {0, 1, 4, 9};
        if (!ArrayProcessor.FilterAndSquare(testArray4).SequenceEqual(expectedOutput4)) {
            Console.WriteLine("Test case 4 failed.");
            allTestsPassed = false;
        }

        // Test case 5
        int[] testArray5 = {5, 7, 11};
        int[] expectedOutput5 = {25, 49, 121};
        if (!ArrayProcessor.FilterAndSquare(testArray5).SequenceEqual(expectedOutput5)) {
            Console.WriteLine("Test case 5 failed.");
            allTestsPassed = false;
        }

        if (allTestsPassed) {
            Console.WriteLine("All test cases passed successfully.");
            return 0;
        } else {
            return -1;
        }
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class ArrayProcessor {
    public static int[] FilterAndSquare(int[] arr) {
        return arr.Where(x => x >= 0).Select(x => x * x).OrderBy(x => x).ToArray();
    }
    public static void CheckCorrectness() {
        int[] testArray1 = {1, -2, 3, 0};
        int[] expectedOutput1 = {0, 1, 9};
        Debug.Assert(FilterAndSquare(testArray1).SequenceEqual(expectedOutput1));
        int[] testArray2 = {-1, -3, -5, 2, 4, 6};
        int[] expectedOutput2 = {4, 16, 36};
        Debug.Assert(FilterAndSquare(testArray2).SequenceEqual(expectedOutput2));
        int[] testArray3 = {-10, -20};
        int[] expectedOutput3 = {};
        Debug.Assert(FilterAndSquare(testArray3).SequenceEqual(expectedOutput3));
        Console.WriteLine("All test cases passed successfully.");
    }

}

Can you write a method that takes an array of integers as input, filters out all the negative numbers, squares the remaining numbers, and then returns a sorted array of these squared numbers? The input will always be an array of integers, which could include both positive and negative numbers, as well as zero. The output should be an array of integers sorted in ascending order. No external libraries are needed for this task. Additionally, write a function to test the correctness of your method with some predefined data points.

For instance, if the input array is `[1, -2, 3, 0]`, the output should be `[0, 1, 9]` because `-2` is negative and is thus removed, while `1`, `3`, and `0` are squared and sorted.

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class ArrayProcessor
{
    public static int[] FilterAndSquare(int[] arr) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;

#<INSERT>

class ListMultiplierSumTest {
    public static int RunTests() {
        bool allTestsPassed = true;

        // Test Case 1
        int result1 = ListMultiplierSum.MultiplyAndSum(new List<int>{1, 2, 3}, 2);
        if (result1 != 12) {
            Console.WriteLine($"Test Case 1 Failed: Expected 12, got {result1}");
            allTestsPassed = false;
        }

        // Test Case 2
        int result2 = ListMultiplierSum.MultiplyAndSum(new List<int>{4, 5, 6}, 3);
        if (result2 != 45) {
            Console.WriteLine($"Test Case 2 Failed: Expected 45, got {result2}");
            allTestsPassed = false;
        }

        // Test Case 3
        int result3 = ListMultiplierSum.MultiplyAndSum(new List<int>{-1, 0, 1}, 1);
        if (result3 != 0) {
            Console.WriteLine($"Test Case 3 Failed: Expected 0, got {result3}");
            allTestsPassed = false;
        }

        // Test Case 4
        int result4 = ListMultiplierSum.MultiplyAndSum(new List<int>{0, 0, 0}, 10);
        if (result4 != 0) {
            Console.WriteLine($"Test Case 4 Failed: Expected 0, got {result4}");
            allTestsPassed = false;
        }

        // Test Case 5
        int result5 = ListMultiplierSum.MultiplyAndSum(new List<int>{10, 20, 30}, -1);
        if (result5 != -60) {
            Console.WriteLine($"Test Case 5 Failed: Expected -60, got {result5}");
            allTestsPassed = false;
        }

        if (allTestsPassed) {
            Console.WriteLine("All test cases passed!");
            return 0;
        } else {
            return -1;
        }
    }

    static void Main(string[] args) {
        int result = RunTests();
        Environment.Exit(result);
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
class ListMultiplierSum {
    public static int MultiplyAndSum(List<int> numbers, int multiplier) {
        int sum = 0;
        foreach (int number in numbers) {
            sum += number * multiplier;
        }
        return sum;
    }
    public static void CheckFunction() {
        Debug.Assert(MultiplyAndSum(new List<int>{1, 2, 3}, 2) == 12, "Test Case 1 Failed");
        Debug.Assert(MultiplyAndSum(new List<int>{4, 5, 6}, 3) == 45, "Test Case 2 Failed");
        Debug.Assert(MultiplyAndSum(new List<int>{-1, 0, 1}, 1) == 0, "Test Case 3 Failed");
        Console.WriteLine("All test cases passed!");
    }

}

Hey, could you help me with a little coding task? I need a method that takes a list of integers, multiplies each element by a specific number, and then sums up all the elements in the list. The twist is, I want this functionality wrapped in a simple C# program. Can you also include a way to check if the method works correctly with a couple of test cases? For example, if we multiply each element by 2 and our list is [1, 2, 3], the result should be 12 because (1*2) + (2*2) + (3*2) = 12.

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class ListMultiplierSum
{
    public static int MultiplyAndSum(List<int> numbers, int multiplier) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class DistinctAndSortedTest {
    public static int Main(string[] args) {
        var testCases = new List<Tuple<List<int>, List<int>>> {
            Tuple.Create(new List<int>{ 4, 2, 7, 3, 2, 4 }, new List<int>{ 2, 3, 4, 7 }),
            Tuple.Create(new List<int>{ 1, 5, 3, 9, 5, 3 }, new List<int>{ 1, 3, 5, 9 }),
            Tuple.Create(new List<int>{ 10, 8, 10, 8 }, new List<int>{ 8, 10 }),
            Tuple.Create(new List<int>{ 5, 5, 5, 5, 5 }, new List<int>{ 5 }),
            Tuple.Create(new List<int>{ 1, 2, 3, 4, 5 }, new List<int>{ 1, 2, 3, 4, 5 })
        };

        bool allTestsPassed = true;

        foreach (var testCase in testCases) {
            var result = DistinctAndSorted.FilterAndSort(testCase.Item1);
            bool isEqual = result.SequenceEqual(testCase.Item2);
            Console.WriteLine($"Input: [{String.Join(", ", testCase.Item1)}] | Expected: [{String.Join(", ", testCase.Item2)}] | Result: [{String.Join(", ", result)}] | Correct: {isEqual}");
            if (!isEqual) {
                allTestsPassed = false;
            }
        }

        return allTestsPassed ? 0 : -1;
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class DistinctAndSorted {
    public static List<int> FilterAndSort(List<int> numbers) {
        List<int> distinctSorted = numbers.Distinct().OrderBy(n => n).ToList();
        return distinctSorted;
    }
    public static void Check() {
        var testCases = new Dictionary<List<int>, List<int>> {
            { new List<int>{ 4, 2, 7, 3, 2, 4 }, new List<int>{ 2, 3, 4, 7 } },
            { new List<int>{ 1, 5, 3, 9, 5, 3 }, new List<int>{ 1, 3, 5, 9 } },
            { new List<int>{ 10, 8, 10, 8 }, new List<int>{ 8, 10 } }
        };
        foreach (var testCase in testCases) {
            var result = FilterAndSort(testCase.Key);
            bool isEqual = result.SequenceEqual(testCase.Value);
            Console.WriteLine($"Input: [{String.Join(", ", testCase.Key)}] | Expected: [{String.Join(", ", testCase.Value)}] | Result: [{String.Join(", ", result)}] | Correct: {isEqual}");
        }
    }

}

Can you write a C# program to filter and order a collection of numbers? Specifically, I need a function that takes a list of integers as input and returns a new list containing only the distinct elements from the original list, sorted in ascending order. For example, if the input list is `[4, 2, 7, 3, 2, 4]`, the output should be `[2, 3, 4, 7]`. Make sure to include necessary imports and a way to verify the correctness of your function with given test cases.

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class DistinctAndSorted
{
    public static List<int> FilterAndSort(List<int> numbers) {
    {
        // Implement your code here.
    }
}
```


using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;

#<INSERT>

class DataProcessorTest {
    public static int Main(string[] args) {
        bool allTestsPassed = true;

        // Test 1
        List<int> test1 = new List<int>{5, 3, 5, 2, 3, 3, 9, 0, 123};
        List<int> expected1 = new List<int>{0, 2, 3, 5, 9, 123};
        allTestsPassed &= DataProcessor.RemoveDuplicatesAndSort(test1).SequenceEqual(expected1);

        // Test 2
        List<int> test2 = new List<int>{-1, -3, -1, 0, -3, 1, 2};
        List<int> expected2 = new List<int>{-3, -1, 0, 1, 2};
        allTestsPassed &= DataProcessor.RemoveDuplicatesAndSort(test2).SequenceEqual(expected2);

        // Test 3
        List<int> test3 = new List<int>{1, 2, 3, 4, 5};
        List<int> expected3 = new List<int>{1, 2, 3, 4, 5};
        allTestsPassed &= DataProcessor.RemoveDuplicatesAndSort(test3).SequenceEqual(expected3);

        // Test 4
        List<int> test4 = new List<int>{5, 4, 3, 2, 1};
        List<int> expected4 = new List<int>{1, 2, 3, 4, 5};
        allTestsPassed &= DataProcessor.RemoveDuplicatesAndSort(test4).SequenceEqual(expected4);

        // Test 5
        List<int> test5 = new List<int>{};
        List<int> expected5 = new List<int>{};
        allTestsPassed &= DataProcessor.RemoveDuplicatesAndSort(test5).SequenceEqual(expected5);

        return allTestsPassed ? 0 : -1;
    }
}

using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
class DataProcessor {
    public static List<int> RemoveDuplicatesAndSort(List<int> numbers) {
        HashSet<int> uniqueNumbers = new HashSet<int>(numbers);
        List<int> sortedNumbers = uniqueNumbers.ToList();
        sortedNumbers.Sort();
        return sortedNumbers;
    }
    public static void Test() {
        List<int> test1 = new List<int>{5, 3, 5, 2, 3, 3, 9, 0, 123};
        List<int> expected1 = new List<int>{0, 2, 3, 5, 9, 123};
        Console.WriteLine($"Test 1 Passed: {RemoveDuplicatesAndSort(test1).SequenceEqual(expected1)}");
        List<int> test2 = new List<int>{-1, -3, -1, 0, -3, 1, 2};
        List<int> expected2 = new List<int>{-3, -1, 0, 1, 2};
        Console.WriteLine($"Test 2 Passed: {RemoveDuplicatesAndSort(test2).SequenceEqual(expected2)}");
    }

}

Hey there! I was working on a piece of code earlier today that's supposed to filter out all the duplicate numbers from a list and then sort them in ascending order. However, I got pulled into another task and couldn't finish it. The list contains integers, and I need the final list to have only unique numbers, sorted from the smallest to the largest. Can you help me write a C# function to do that? It would be great if you could also include a simple way to verify the function works as expected with a couple of examples. Thanks!

Please use C# to implement the complete code without the Main function. Please follow the following type definitions:

```csharp
using xxx
...
class DataProcessor
{
    public static void Test() {
    {
        // Implement your code here.
    }
}
```