Prompt:
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import skew

def task_func(data_matrix):
    """
    Calculate the skew of each row in a 2D data matrix and plot the distribution.

    Parameters:
    - data_matrix (numpy.array): The 2D data matrix.

    Returns:
    pandas.DataFrame: A DataFrame containing the skewness of each row. The skweness is stored in a new column which name is 'Skewness'.
    matplotlib.axes.Axes: The Axes object of the plotted distribution.

    Requirements:
    - pandas
    - matplotlib.pyplot
    - scipy.stats.skew

    Example:
    >>> import numpy as np
    >>> data = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]])
    >>> df, ax = task_func(data)
    >>> print(df)
       Skewness
    0  0.122440
    1  0.403407
    """

    skewness = skew(data_matrix, axis=1)
    df = pd.DataFrame(skewness, columns=["Skewness"])
    plt.figure(figsize=(10, 5))
    df["Skewness"].plot(kind="hist", title="Distribution of Skewness")
    return df, plt.gca()

import unittest
import os
import numpy as np
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def setUp(self):
        self.test_dir = "data/task_func"
        os.makedirs(self.test_dir, exist_ok=True)
    def test_case_1(self):
        data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        df, ax = task_func(data)
        self.verify_output(df, ax, data.shape[0], data)
    def test_case_2(self):
        data = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]])
        df, ax = task_func(data)
        self.verify_output(df, ax, data.shape[0], data)
    def test_case_3(self):
        data = np.array([[3, 5, 7, 1000], [200, 5, 7, 1], [1, -9, 14, 700]])
        df, ax = task_func(data)
        self.verify_output(df, ax, data.shape[0], data)
    def test_case_4(self):
        data = np.array(
            [
                [1, 2, 3, 4, 5, 4, 3, 2, 1],
            ]
        )
        df, ax = task_func(data)
        self.verify_output(df, ax, data.shape[0], data)
    def test_case_5(self):
        data = np.array([[1, 1], [1, 1], [1, 1]])
        df, ax = task_func(data)
        # Check if DataFrame is returned with correct values
        self.assertIsInstance(df, pd.DataFrame)
        self.assertEqual(df.shape, (3, 1))
        self.assertIn("Skewness", df.columns)
        # Check if Axes object is returned for the plot
        self.assertIsInstance(ax, plt.Axes)
        self.assertEqual(ax.get_title(), "Distribution of Skewness")
    def verify_output(self, df, ax, expected_rows, data):
        # Check if DataFrame is returned with correct values
        self.assertIsInstance(df, pd.DataFrame)
        self.assertEqual(df.shape, (expected_rows, 1))
        self.assertIn("Skewness", df.columns)
        # Check if Axes object is returned for the plot
        self.assertIsInstance(ax, plt.Axes)
        self.assertEqual(ax.get_title(), "Distribution of Skewness")
        # Check skewness values
        skewness = skew(data, axis=1)
        self.assertListEqual(df["Skewness"].tolist(), list(skewness))

Instruction:
Write a function called `def task_func(data_matrix):` to: Calculate the skew of each row in a 2D data matrix and plot the distribution.
The function should output with:
    pandas.DataFrame: A DataFrame containing the skewness of each row. The skweness is stored in a new column which name is 'Skewness'.
    matplotlib.axes.Axes: The Axes object of the plotted distribution.
You should start with:
```
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import skew
def task_func(data_matrix):
```


Prompt:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

def task_func(data_matrix, n_components=2):
    """
    Apply PCA with n_components components to a 2D data matrix, calculate the mean value of each component, and then return the cumulative explained variance of the components in a plot.
    - The function returns a dataframe with columns 'Component 1', 'Component 2', ... etc.
    - Each row of the dataframe correspond to a row of the original matrix mapped in the PCA space.
    - The dataframe should also include a column 'Mean' which is the average value of each component value per row
    - Create a plot of the cumulative explained variance.
        - the xlabel should be 'Number of Components' and the ylabel 'Cumulative Explained Variance'

    Parameters:
    data_matrix (numpy.array): The 2D data matrix.

    Returns:
    tuple:
        - pandas.DataFrame: A DataFrame containing the PCA transformed data and the mean of each component.
        - matplotlib.axes._axes.Axes: A plot showing the cumulative explained variance of the components.

    Requirements:
    - pandas
    - matplotlib.pyplot
    - sklearn.decomposition

    Example:
    >>> import numpy as np
    >>> data = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]])
    >>> df, ax = task_func(data)
    >>> print(df["Mean"])
    0    2.850439
    1   -2.850439
    Name: Mean, dtype: float64
    """

    pca = PCA(n_components=n_components)
    transformed_data = pca.fit_transform(data_matrix)

    df = pd.DataFrame(
        transformed_data,
        columns=[f"Component {i+1}" for i in range(transformed_data.shape[1])],
    )
    df["Mean"] = df.mean(axis=1)

    fig, ax = plt.subplots()
    ax.plot(np.cumsum(pca.explained_variance_ratio_))
    ax.set_xlabel("Number of Components")
    ax.set_ylabel("Cumulative Explained Variance")
    return df, ax

import unittest
import numpy as np
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        data = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]])
        df, ax = task_func(data)
        self.assertEqual(df.shape, (2, 3))
        self.assertTrue("Mean" in df.columns)
        self.assertEqual(ax.get_xlabel(), "Number of Components")
        self.assertEqual(ax.get_ylabel(), "Cumulative Explained Variance")
    def test_case_2(self):
        data = np.array([[1, 2], [3, 4], [5, 6]])
        df, ax = task_func(data)
        self.assertEqual(df.shape, (3, 3))
        self.assertTrue("Mean" in df.columns)
        self.assertEqual(ax.get_xlabel(), "Number of Components")
        self.assertEqual(ax.get_ylabel(), "Cumulative Explained Variance")
    # Additional test cases
    def test_case_3(self):
        data = np.array([[1, 2], [3, 4], [5, 6]])
        df, ax = task_func(data)
        expected_columns = min(data.shape) + 1
        self.assertEqual(df.shape[1], expected_columns)
        self.assertTrue("Mean" in df.columns)
        self.assertEqual(ax.get_xlabel(), "Number of Components")
        self.assertEqual(ax.get_ylabel(), "Cumulative Explained Variance")
    def test_case_4(self):
        data = np.array([[1, 2], [3, 4], [5, 6]])
        df, ax = task_func(data)
        expected_columns = min(data.shape) + 1
        self.assertEqual(df.shape[1], expected_columns)
        self.assertTrue("Mean" in df.columns)
        self.assertEqual(ax.get_xlabel(), "Number of Components")
        self.assertEqual(ax.get_ylabel(), "Cumulative Explained Variance")
    def test_case_5(self):
        data = np.array([[1, 2], [3, 4], [5, 6]])
        df, ax = task_func(data)
        expected_columns = min(data.shape) + 1
        self.assertEqual(df.shape[1], expected_columns)
        self.assertTrue("Mean" in df.columns)
        self.assertTrue("Component 1" in df.columns)
        self.assertTrue("Component 2" in df.columns)
        self.assertEqual(ax.get_xlabel(), "Number of Components")
        self.assertEqual(ax.get_ylabel(), "Cumulative Explained Variance")

Instruction:
Write a function called `def task_func(data_matrix, n_components=2):` to: Apply PCA with n_components components to a 2D data matrix, calculate the mean value of each component, and then return the cumulative explained variance of the components in a plot. - The function returns a dataframe with columns 'Component 1', 'Component 2', ... etc. - Each row of the dataframe correspond to a row of the original matrix mapped in the PCA space. - The dataframe should also include a column 'Mean' which is the average value of each component value per row - Create a plot of the cumulative explained variance. - the xlabel should be 'Number of Components' and the ylabel 'Cumulative Explained Variance'
The function should output with:
    tuple:
    pandas.DataFrame: A DataFrame containing the PCA transformed data and the mean of each component.
    matplotlib.axes._axes.Axes: A plot showing the cumulative explained variance of the components.
You should start with:
```
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
def task_func(data_matrix, n_components=2):
```


Prompt:
import numpy as np
import seaborn as sns

def task_func(df):
    """
    Describe a dataframe and draw a distribution chart for each numeric column after replacing the NaN values with the average of the column.

    Parameters:
    df (DataFrame): The pandas DataFrame.

    Returns:
    tuple: A tuple containing:
        - DataFrame: A pandas DataFrame with statistics. This includes count, mean, standard deviation (std), min, 25%, 50%, 75%, and max values for each numeric column.
        - List[Axes]: A list of matplotlib Axes objects representing the distribution plots for each numeric column.
                    Each plot visualizes the distribution of data in the respective column with 10 bins.

    Requirements:
    - numpy
    - seaborn

    Example:
    >>> import pandas as pd
    >>> import numpy as np
    >>> df = pd.DataFrame([[1,2,3],[4,5,6],[7.0,np.nan,9.0]], columns=["c1","c2","c3"])
    >>> description, plots = task_func(df)
    >>> print(description)
            c1    c2   c3
    count  3.0  3.00  3.0
    mean   4.0  3.50  6.0
    std    3.0  1.50  3.0
    min    1.0  2.00  3.0
    25%    2.5  2.75  4.5
    50%    4.0  3.50  6.0
    75%    5.5  4.25  7.5
    max    7.0  5.00  9.0
    """

    df = df.fillna(df.mean(axis=0))
    description = df.describe()
    plots = []
    for col in df.select_dtypes(include=[np.number]).columns:
        plot = sns.displot(df[col], bins=10)
        plots.append(plot.ax)
    return description, plots

import unittest
import pandas as pd
class TestCases(unittest.TestCase):
    """Test cases for the f_112 function."""
    def setUp(self):
        # Generating more complex data for testing
        self.df1 = pd.DataFrame(
            {"A": [1, 2, 3, 4, 5], "B": [6, 7, 8, 9, 10], "C": [11, 12, 13, 14, 15]}
        )
        self.df2 = pd.DataFrame({"X": [1, None, 9, 13], "Y": [None, 3, 4, 8]})
        self.df3 = pd.DataFrame(
            {"M": [7, 13, 21, 11, 22, 8, None, 17], "N": [None, 2, 3, 4, 10, 0, 27, 12]}
        )
        self.df4 = pd.DataFrame(
            {"P": [None, None, 4], "Q": [7, None, 3], "R": [2, None, 6]}
        )
        self.df5 = pd.DataFrame({"W": [1, 2], "Z": [2, 1]})
        self.df6 = pd.DataFrame(
            {
                "A": [1, 2, 3, 4, 5, 6],
                "B": [None, 8, 9, 10, 11, None],
                "C": [13, None, None, None, None, 18],
                "D": [19, None, 21, None, 23, None],
            }
        )
    def test_case_1(self):
        description, plots = task_func(self.df1)
        self.assertFalse(description.isna().any().any())
        self.assertIsInstance(description, pd.DataFrame)
        self.assertListEqual(list(description.columns), ["A", "B", "C"])
        self.assertEqual(len(plots), 3)
    def test_case_2(self):
        description, plots = task_func(self.df2)
        self.assertFalse(description.isna().any().any())
        self.assertIsInstance(description, pd.DataFrame)
        self.assertListEqual(list(description.columns), ["X", "Y"])
        self.assertEqual(len(plots), 2)
    def test_case_3(self):
        description, plots = task_func(self.df3)
        self.assertFalse(description.isna().any().any())
        self.assertIsInstance(description, pd.DataFrame)
        self.assertListEqual(list(description.columns), ["M", "N"])
        self.assertEqual(len(plots), 2)
    def test_case_4(self):
        description, plots = task_func(self.df4)
        self.assertFalse(description.isna().any().any())
        self.assertIsInstance(description, pd.DataFrame)
        self.assertListEqual(list(description.columns), ["P", "Q", "R"])
        self.assertEqual(len(plots), 3)
    def test_case_5(self):
        description, plots = task_func(self.df5)
        self.assertFalse(description.isna().any().any())
        self.assertIsInstance(description, pd.DataFrame)
        self.assertListEqual(list(description.columns), ["W", "Z"])
        self.assertEqual(len(plots), 2)
    def test_case_6(self):
        description, plots = task_func(self.df6)
        self.assertFalse(description.isna().any().any())
        self.assertIsInstance(description, pd.DataFrame)
        self.assertListEqual(list(description.columns), ["A", "B", "C", "D"])
        self.assertEqual(len(plots), 4)
        self.assertEqual(description.loc["mean", "A"], 3.5)
        self.assertEqual(description.loc["std", "B"], 1.0)
        self.assertEqual(description.loc["25%", "A"], 2.25)
        self.assertEqual(description.loc["50%", "C"], 15.5)
        self.assertEqual(description.loc["75%", "A"], 4.75)
        self.assertEqual(description.loc["max", "D"], 23.0)

Instruction:
Write a function called `def task_func(df):` to: Describe a dataframe and draw a distribution chart for each numeric column after replacing the NaN values with the average of the column.
The function should output with:
    tuple: A tuple containing:
    DataFrame: A pandas DataFrame with statistics. This includes count, mean, standard deviation (std), min, 25%, 50%, 75%, and max values for each numeric column.
    List[Axes]: A list of matplotlib Axes objects representing the distribution plots for each numeric column.
    Each plot visualizes the distribution of data in the respective column with 10 bins.
You should start with:
```
import numpy as np
import seaborn as sns
def task_func(df):
```


Prompt:
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt

def task_func(df):
    """
    Normalize numeric columns in a DataFrame and draw a box plot for each column. Missing values are replaced by column's average.

    Parameters:
    df (DataFrame): The pandas DataFrame.

    Returns:
    DataFrame: A pandas DataFrame after normalization.
    Axes: A matplotlib Axes displaying a box plot for each column.

    Requirements:
    - pandas
    - numpy
    - sklearn.preprocessing.MinMaxScaler
    - matplotlib.pyplot

    Example:
    >>> import pandas as pd
    >>> import numpy as np
    >>> df = pd.DataFrame([[1,2,3],[4,5,6],[7.0,np.nan,9.0]], columns=["c1","c2","c3"])
    >>> df, ax = task_func(df)
    >>> print(df)
        c1   c2   c3
    0  0.0  0.0  0.0
    1  0.5  1.0  0.5
    2  1.0  0.5  1.0
    """

    df = df.fillna(df.mean(axis=0))
    scaler = MinMaxScaler()
    df[df.columns] = scaler.fit_transform(df[df.columns])
    plt.figure(figsize=(10, 5))
    df.boxplot(grid=False, vert=False, fontsize=15)
    return df, plt.gca()

import unittest
import pandas as pd
import numpy as np
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        df = pd.DataFrame(
            [[1, 2, 3], [4, 5, 6], [7.0, np.nan, 9.0]], columns=["c1", "c2", "c3"]
        )
        normalized_df, ax = task_func(df)
        self.assertTrue(np.allclose(normalized_df["c1"].tolist(), [0.0, 0.5, 1.0]))
        self.assertTrue(np.allclose(normalized_df["c2"].tolist(), [0.0, 1.0, 0.5]))
        self.assertTrue(np.allclose(normalized_df["c3"].tolist(), [0.0, 0.5, 1.0]))
        self.assertIsInstance(ax, plt.Axes)
    def test_case_2(self):
        df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["c1", "c2", "c3"])
        normalized_df, ax = task_func(df)
        self.assertTrue(np.allclose(normalized_df["c1"].tolist(), [0.0, 0.5, 1.0]))
        self.assertTrue(np.allclose(normalized_df["c2"].tolist(), [0.0, 0.5, 1.0]))
        self.assertTrue(np.allclose(normalized_df["c3"].tolist(), [0.0, 0.5, 1.0]))
        self.assertIsInstance(ax, plt.Axes)
    def test_case_3(self):
        df = pd.DataFrame(
            [[1, 2, 3, 4, 5], [None, None, None, None, None]],
            columns=["c1", "c2", "c3", "c4", "c5"],
        )
        normalized_df, ax = task_func(df)
        for col in df.columns:
            self.assertTrue(normalized_df[col].max() <= 1.0)
            self.assertTrue(normalized_df[col].min() >= 0.0)
        self.assertIsInstance(ax, plt.Axes)
    def test_case_4(self):
        df = pd.DataFrame(
            [[11, 2, 13, 7], [1, 5, 6, 16], [15, 3, 14, 9], [8, 10, 4, 12]],
            columns=["c1", "c2", "c3", "c4"],
        )
        normalized_df, ax = task_func(df)
        for col in df.columns:
            self.assertTrue(normalized_df[col].max() <= 1.0)
            self.assertTrue(normalized_df[col].min() >= 0.0)
        self.assertIsInstance(ax, plt.Axes)
    def test_case_5(self):
        df = pd.DataFrame(
            [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], columns=["c1", "c2"]
        )
        normalized_df, ax = task_func(df)
        for col in df.columns:
            self.assertTrue(np.isclose(normalized_df[col].max(), 1.0, atol=1e-5))
            self.assertTrue(normalized_df[col].min() >= 0.0)
        self.assertListEqual(
            normalized_df.loc[:, "c1"].tolist(), [0.0, 0.25, 0.5, 0.75, 1.0]
        )
        self.assertListEqual(
            normalized_df.loc[:, "c2"].tolist(), [0.0, 0.25, 0.5, 0.75, 1.0]
        )
        self.assertIsInstance(ax, plt.Axes)

Instruction:
Write a function called `def task_func(df):` to: Normalize numeric columns in a DataFrame and draw a box plot for each column. Missing values are replaced by column's average.
The function should output with:
    DataFrame: A pandas DataFrame after normalization.
    Axes: A matplotlib Axes displaying a box plot for each column.
You should start with:
```
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
def task_func(df):
```


Prompt:
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
import seaborn as sns
import matplotlib.pyplot as plt

def task_func(df: pd.DataFrame):
    """
    Perform PCA on a DataFrame (excluding non-numeric columns) and draw a scatter plot of the first two main components. The principal columns should be name 'Component 1' and 'Component 2'.
    Missing values are replaced by column's average.

    Parameters:
    df (DataFrame): The pandas DataFrame.

    Returns:
    DataFrame: A pandas DataFrame with the first two principal components. The columns should be 'principal component 1' and 'principal component 2'.
    Axes: A matplotlib Axes object representing the scatter plot. The xlabel should be 'principal component' and the ylabel 'principal component 2'.

    Requirements:
    - pandas
    - numpy
    - sklearn.decomposition.PCA
    - seaborn
    - matplotlib

    Example:
    >>> df = pd.DataFrame([[1,2,3],[4,5,6],[7.0,np.nan,9.0]], columns=["c1","c2","c3"])
    >>> principalDf, ax = task_func(df)
    >>> print(principalDf)
       Component 1  Component 2
    0     4.450915    -0.662840
    1    -0.286236     1.472436
    2    -4.164679    -0.809596
    """

    # Select only numeric columns
    df_numeric = df.select_dtypes(include=[np.number])
    # Replace missing values
    df_numeric = df_numeric.fillna(df_numeric.mean(axis=0))
    # Perform PCA
    pca = PCA(n_components=2)
    principalComponents = pca.fit_transform(df_numeric)
    principalDf = pd.DataFrame(
        data=principalComponents,
        columns=["Component 1", "Component 2"],
    )

    # Plot scatter plot
    ax = sns.scatterplot(data=principalDf, x="Component 1", y="Component 2")
    plt.show()
    return principalDf, ax

    df_numeric = df.select_dtypes(include=[np.number])
    df_numeric = df_numeric.fillna(df_numeric.mean(axis=0))
    pca = PCA(n_components=2)
    principalComponents = pca.fit_transform(df_numeric)
    principalDf = pd.DataFrame(
        data=principalComponents,
        columns=["Component 1", "Component 2"],
    )
    ax = sns.scatterplot(data=principalDf, x="Component 1", y="Component 2")
    plt.show()
    return principalDf, ax

import unittest
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        df = pd.DataFrame(
            [[1, 2, 3], [4, 5, 6], [7.0, np.nan, 9.0]], columns=["c1", "c2", "c3"]
        )
        principalDf, ax = task_func(df)
        self.assertTrue("Component 1" in principalDf.columns)
        self.assertTrue("Component 2" in principalDf.columns)
        self.assertEqual(principalDf.shape, (3, 2))
        self.assertEqual(ax.get_xlabel(), "Component 1")
        self.assertEqual(ax.get_ylabel(), "Component 2")
    def test_case_2(self):
        df = pd.DataFrame(
            {
                "A": [1, 2.5, 3, 4.5, 5],
                "B": [5, 4.5, np.nan, 2, 1.5],
                "C": [2.5, 3, 4, 5.5, 6],
                "categoral_1": ["A", "B", "B", "B", "A"],
                "categoral_2": ["0", "1", "1", "0", "1"],
            }
        )
        principalDf, ax = task_func(df)
        self.assertTrue("Component 1" in principalDf.columns)
        self.assertTrue("Component 2" in principalDf.columns)
        self.assertEqual(principalDf.shape, (5, 2))
        self.assertEqual(ax.get_xlabel(), "Component 1")
        self.assertEqual(ax.get_ylabel(), "Component 2")
    def test_case_3(self):
        df = pd.DataFrame(
            {
                "col1": [None, 17, 11, None],
                "col2": [0, 4, 15, 27],
                "col3": [7, 9, 3, 8],
            }
        )
        principalDf, ax = task_func(df)
        self.assertTrue("Component 1" in principalDf.columns)
        self.assertTrue("Component 2" in principalDf.columns)
        self.assertEqual(principalDf.shape, (4, 2))
        self.assertEqual(ax.get_xlabel(), "Component 1")
        self.assertEqual(ax.get_ylabel(), "Component 2")
    def test_case_4(self):
        df = pd.DataFrame(
            {
                "c1": [np.nan] * 9 + [10],
                "c2": [np.nan] * 8 + [20, 30],
                "c3": [np.nan] * 7 + [40, 50, 60],
            }
        )
        principalDf, ax = task_func(df)
        self.assertTrue("Component 1" in principalDf.columns)
        self.assertTrue("Component 2" in principalDf.columns)
        self.assertEqual(principalDf.shape, (10, 2))
        self.assertEqual(ax.get_xlabel(), "Component 1")
        self.assertEqual(ax.get_ylabel(), "Component 2")
    def test_case_5(self):
        df = pd.DataFrame({"c1": [1] * 10, "c2": [2] * 10, "c3": [3] * 10})
        principalDf, ax = task_func(df)
        self.assertTrue("Component 1" in principalDf.columns)
        self.assertTrue("Component 2" in principalDf.columns)
        self.assertEqual(principalDf.shape, (10, 2))
        self.assertEqual(ax.get_xlabel(), "Component 1")
        self.assertEqual(ax.get_ylabel(), "Component 2")

pandas numpy sklearn.decomposition.PCA seaborn matplotlib

Instruction:
Write a function called `def task_func(df: pd.DataFrame):` to: Perform PCA on a DataFrame (excluding non-numeric columns) and draw a scatter plot of the first two main components. The principal columns should be name 'Component 1' and 'Component 2'. Missing values are replaced by column's average.
The function should output with:
    DataFrame: A pandas DataFrame with the first two principal components. The columns should be 'principal component 1' and 'principal component 2'.
    Axes: A matplotlib Axes object representing the scatter plot. The xlabel should be 'principal component' and the ylabel 'principal component 2'.
You should start with:
```
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
import seaborn as sns
import matplotlib.pyplot as plt
def task_func(df: pd.DataFrame):
```


Prompt:
from scipy.stats import zscore
import matplotlib.pyplot as plt

def task_func(df):
    """
    Calculate Z-scores for numeric columns in a DataFrame and draw a histogram for each column.
    - Missing values are replaced by the column's average.
    - The histograms are plotted with 10 bins.

    Parameters:
    - df (pandas.DataFrame): The input pandas DataFrame with numeric columns.

    Returns:
    - tuple:
        1. pandas.DataFrame: A DataFrame with computed z-scores.
        2. list: A list of Axes objects representing the histograms of the numeric columns.

    Requirements:
    - pandas.
    - numpy.
    - scipy.stats.zscore.
    - matplotlib.pyplot.

    Example:
    >>> import pandas as pd
    >>> import numpy as np
    >>> df_input = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7.0, np.nan, 9.0]], columns=["col1", "col2", "col3"])
    >>> zscore_output, plots = task_func(df_input)
    """

    # Fill missing values with column's average
    df = df.fillna(df.mean(axis=0))
    # Compute Z-scores
    df = df.apply(zscore)
    # Plot histograms for each numeric column
    axes = df.hist(grid=False, bins=10, layout=(1, df.shape[1]))
    plt.tight_layout()
    return df, axes

    df = df.fillna(df.mean(axis=0))
    df = df.apply(zscore)
    axes = df.hist(grid=False, bins=10, layout=(1, df.shape[1]))
    plt.tight_layout()
    return df, axes

import unittest
import pandas as pd
import numpy as np
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        df = pd.DataFrame(
            {
                "col1": [1, 7, 3],
                "col2": [4, 5, 7],
                "col3": [None, None, None],
            }
        )
        zscores, plots = task_func(df)
        self.assertAlmostEqual(zscores.mean().mean(), 0.0, places=6)
        self.assertEqual(len(plots[0]), 3)
    def test_case_2(self):
        df = pd.DataFrame(
            {
                "col1": [None, None, 3],
                "col2": [None, 5, 7],
                "col3": [8, 6, 4],
            }
        )
        zscores, plots = task_func(df)
        self.assertAlmostEqual(zscores.mean().mean(), 0.0, places=6)
        self.assertEqual(len(plots[0]), 3)
    def test_case_3(self):
        df = pd.DataFrame(
            {
                "col1": [None, 17, 11, None],
                "col2": [0, 4, 15, 27],
                "col3": [7, 9, 3, 8],
            }
        )
        # Expected solutions
        expected_df = df.copy()
        expected_df = expected_df.fillna(expected_df.mean(axis=0))
        expected_df = expected_df.apply(zscore)
        # Function execution
        zscores, plots = task_func(df)
        self.assertAlmostEqual(zscores.mean().mean(), 0.0, places=6)
        self.assertEqual(len(plots[0]), 3)
        pd.testing.assert_frame_equal(zscores, expected_df)
    def test_case_4(self):
        df = pd.DataFrame(
            {
                "col1": [1, 7, 3, None],
                "col2": [4, 5, 7, 2],
            }
        )
        zscores, plots = task_func(df)
        self.assertAlmostEqual(zscores.mean().mean(), 0.0, places=6)
        self.assertEqual(len(plots[0]), 2)
    def test_case_5(self):
        df = pd.DataFrame(
            {
                "col1": [1, 2, 3, 4, 5],
                "col2": [None, None, None, None, None],
            }
        )
        zscores, plots = task_func(df)
        self.assertAlmostEqual(zscores.mean().mean(), 0.0, places=6)
        self.assertEqual(len(plots[0]), 2)
    def test_case_6(self):
        df = pd.DataFrame(
            {
                "A": [np.nan, np.nan, np.nan],
                "B": [np.nan, np.nan, np.nan],
                "C": [np.nan, np.nan, np.nan],
            }
        )
        zscores, plots = task_func(df)
        self.assertTrue(zscores.isnull().all().all())
        self.assertEqual(len(plots[0]), 3)
    def test_case_7(self):
        df = pd.DataFrame(
            {
                "A": [1, 2.5, 3, 4.5, 5],
                "B": [5, 4.5, np.nan, 2, 1.5],
                "C": [2.5, 3, 4, 5.5, 6],
            }
        )
        zscores, plots = task_func(df)
        self.assertAlmostEqual(zscores.mean().mean(), 0.0, places=6)
        self.assertEqual(len(plots[0]), 3)

Instruction:
Write a function called `def task_func(df):` to: Calculate Z-scores for numeric columns in a DataFrame and draw a histogram for each column. - Missing values are replaced by the column's average. - The histograms are plotted with 10 bins.
The function should output with:
    tuple:
    1. pandas.DataFrame: A DataFrame with computed z-scores.
    2. list: A list of Axes objects representing the histograms of the numeric columns.
You should start with:
```
from scipy.stats import zscore
import matplotlib.pyplot as plt
def task_func(df):
```


Prompt:
from sklearn.preprocessing import StandardScaler
import seaborn as sns
import matplotlib.pyplot as plt

def task_func(df):
    """
    Standardize numeric columns in a DataFrame and return the heatmap of the correlation matrix. Missing values are replaced by the column's average.

    Parameters:
    - df (pandas.DataFrame): The pandas DataFrame to be standardized.

    Returns:
    - DataFrame: The pandas DataFrame after standardization.
    - Axes: A heatmap of the correlation matrix.

    Requirements:
    - sklearn.preprocessing.StandardScaler
    - seaborn
    - matplotlib.pyplot

    Example:
    >>> import pandas as pd
    >>> import numpy as np
    >>> df = pd.DataFrame([[1,2,3],[4,5,6],[7.0,np.nan,9.0]], columns=["c1","c2","c3"])
    >>> standardized_df, heatmap = task_func(df)
    >>> print(standardized_df)
             c1        c2        c3
    0 -1.224745 -1.224745 -1.224745
    1  0.000000  1.224745  0.000000
    2  1.224745  0.000000  1.224745
    """

    df = df.fillna(df.mean(axis=0))
    scaler = StandardScaler()
    df[df.columns] = scaler.fit_transform(df[df.columns])
    plt.figure(figsize=(10, 5))
    heatmap = sns.heatmap(df.corr(), annot=True, cmap="coolwarm")
    return df, heatmap

import unittest
import pandas as pd
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        df = pd.DataFrame(
            [[1, 2, 3], [4, 5, 6], [7, None, 9]], columns=["c1", "c2", "c3"]
        )
        # Expected output
        expected_df = df.copy()
        expected_df = expected_df.fillna(df.mean(axis=0))
        scaler = StandardScaler()
        expected_df[expected_df.columns] = scaler.fit_transform(
            expected_df[expected_df.columns]
        )
        # Function execution
        standardized_df, heatmap = task_func(df)
        pd.testing.assert_frame_equal(standardized_df, expected_df)
        # Asserting the output DataFrame
        self.assertEqual(standardized_df.shape, df.shape)
        # Asserting the heatmap
        self.assertIsInstance(heatmap, plt.Axes)
    def test_case_2(self):
        df = pd.DataFrame([[3, 7, 9], [4, 1, 8], [2, 6, 5]], columns=["c1", "c2", "c3"])
        standardized_df, heatmap = task_func(df)
        # Asserting the output DataFrame
        self.assertEqual(standardized_df.shape, df.shape)
        # Asserting the heatmap
        self.assertIsInstance(heatmap, plt.Axes)
    def test_case_3(self):
        df = pd.DataFrame([[4, 6, 8], [9, 5, 2], [3, 1, 7]], columns=["c1", "c2", "c3"])
        standardized_df, heatmap = task_func(df)
        # Asserting the output DataFrame
        self.assertEqual(standardized_df.shape, df.shape)
        # Asserting the heatmap
        self.assertIsInstance(heatmap, plt.Axes)
    def test_case_4(self):
        df = pd.DataFrame([[9, 1, 2], [3, 4, 5], [7, 8, 6]], columns=["c1", "c2", "c3"])
        standardized_df, heatmap = task_func(df)
        # Asserting the output DataFrame
        self.assertEqual(standardized_df.shape, df.shape)
        # Asserting the heatmap
        self.assertIsInstance(heatmap, plt.Axes)
    def test_case_5(self):
        df = pd.DataFrame(
            [[None, 17, 13], [None, None, 29], [42, 3, 100]], columns=["c1", "c2", "c3"]
        )
        standardized_df, heatmap = task_func(df)
        # Asserting the output DataFrame
        self.assertEqual(standardized_df.shape, df.shape)
        # Asserting the heatmap
        self.assertIsInstance(heatmap, plt.Axes)

Instruction:
Write a function called `def task_func(df):` to: Standardize numeric columns in a DataFrame and return the heatmap of the correlation matrix. Missing values are replaced by the column's average.
The function should output with:
    DataFrame: The pandas DataFrame after standardization.
    Axes: A heatmap of the correlation matrix.
You should start with:
```
from sklearn.preprocessing import StandardScaler
import seaborn as sns
import matplotlib.pyplot as plt
def task_func(df):
```


Prompt:
import time
from datetime import datetime
import random
import matplotlib.pyplot as plt

# Constants
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

def task_func(n, output_path=None):
    """
    Generate n random Unix timestamps and convert them to strings formatted as UTC DATE_FORMAT.
    Plot a histogram of the distribution of the generated timestamps. If an output path is provided,
    save the histogram to the specified path. Otherwise, display the plot.

    Parameters:
    n (int): The number of timestamps to generate.
    output_path (str, optional): Path to save the histogram plot. Defaults to None.

    Returns:
    list: The list of n formatted timestamps.

    Requirements:
    - time
    - datetime
    - random
    - matplotlib.pyplot

    Example:
    >>> random.seed(42)
    >>> timestamps = task_func(n=3, output_path=None)
    >>> print(timestamps)
    ['2013-07-06 20:56:46', '1977-07-29 23:34:23', '1971-09-14 11:29:44']
    """

    timestamps = []
    for _ in range(n):
        timestamp = random.randint(0, int(time.time()))
        formatted_time = datetime.utcfromtimestamp(timestamp).strftime(DATE_FORMAT)
        timestamps.append(formatted_time)

    plt.hist([datetime.strptime(t, DATE_FORMAT) for t in timestamps])

    if output_path:
        plt.savefig(output_path)
    else:
        plt.show()
    return timestamps

import unittest
import os
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def setUp(self):
        self.test_dir = "data/task_func"
        os.makedirs(self.test_dir, exist_ok=True)
        self.o_1 = os.path.join(self.test_dir, "histogram_1.png")
    def tearDown(self) -> None:
        import shutil
        try:
            shutil.rmtree(self.test_dir)
        except:
            pass
    def test_case_1(self):
        random.seed(42)
        result = task_func(10)
        self.assertEqual(len(result), 10)
    def test_case_2(self):
        random.seed(42)
        result = task_func(15)
        for timestamp in result:
            try:
                datetime.strptime(timestamp, DATE_FORMAT)
            except ValueError:
                self.fail(f"Timestamp {timestamp} doesn't match the specified format.")
    def test_case_3(self):
        random.seed(42)
        task_func(20, output_path=self.o_1)
        self.assertTrue(os.path.exists(self.o_1))
    def test_case_4(self):
        result = task_func(50)
        self.assertEqual(len(result), len(set(result)))
    def test_case_5(self):
        result = task_func(0)
        self.assertEqual(len(result), 0)

Instruction:
Write a function called `def task_func(n, output_path=None):` to: Generate n random Unix timestamps and convert them to strings formatted as UTC DATE_FORMAT. Plot a histogram of the distribution of the generated timestamps. If an output path is provided, save the histogram to the specified path. Otherwise, display the plot.
The function should output with:
    list: The list of n formatted timestamps.
You should start with:
```
import time
from datetime import datetime
import random
import matplotlib.pyplot as plt
# Constants
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
def task_func(n, output_path=None):
```


Prompt:
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

# Constants
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

def task_func(timestamps):
    """
    Convert a list of Unix timestamps to date objects, create a Pandas DataFrame, and draw a histogram.
    - The date format should be as DATE_FORMAT.
    - The DataFrame should have 'Timestamp' and 'Datetime' as column names.
    - If the list of timestamps is empty, raise a ValueError with the message "Input list of timestamps is empty".

    Parameters:
    - timestamps (list): The list of Unix timestamps.

    Returns:
    - pandas.DataFrame: A pandas DataFrame containing the original Unix timestamps and the converted datetime objects.
    - Axes: The Axes object of the histogram plot. The histogram will have 10 bins by default, representing the distribution of the datetime objects.

    Raises:
    - ValueError("Input list of timestamps is empty."): If the list of timestamps is empty.

    Requirements:
    - datetime
    - pandas
    - matplotlib.pyplot

    Examples:
    >>> df, ax = task_func([1347517370, 1475153730, 1602737300])
    >>> print(df)
        Timestamp             Datetime
    0  1347517370  2012-09-13 02:22:50
    1  1475153730  2016-09-29 08:55:30
    2  1602737300  2020-10-15 00:48:20
    """

    if not timestamps:
        raise ValueError("Input list of timestamps is empty.")
    datetimes = [datetime.fromtimestamp(t).strftime(DATE_FORMAT) for t in timestamps]
    df = pd.DataFrame({"Timestamp": timestamps, "Datetime": datetimes})
    ax = plt.hist(pd.to_datetime(df["Datetime"]))
    plt.close()
    return df, ax

import unittest
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def setUp(self):
        self.test_data = [
            [1318935276, 1342905276, 23074268],
            [4235087541, 1234653346, 19862358],
            [],
            [1156829289],
            [1000000000, 2000000000, 3000000000],
        ]
    def test_case_1(self):
        input_timestamps = self.test_data[0]
        self.assert_function_output(input_timestamps)
    def test_case_2(self):
        input_timestamps = self.test_data[1]
        self.assert_function_output(input_timestamps)
    def test_case_3(self):
        input_timestamps = self.test_data[2]
        with self.assertRaises(ValueError) as context:
            task_func(input_timestamps)
        self.assertEqual(
            str(context.exception),
            "Input list of timestamps is empty.",
        )
    def test_case_4(self):
        input_timestamps = self.test_data[3]
        self.assert_function_output(input_timestamps)
    def test_case_5(self):
        input_timestamps = self.test_data[4]
        self.assert_function_output(input_timestamps)
        df, ax = task_func(input_timestamps)
        expected_df = pd.DataFrame(
            {
                "Timestamp": [1000000000, 2000000000, 3000000000],
                "Datetime": [
                    "2001-09-09 01:46:40",
                    "2033-05-18 03:33:20",
                    "2065-01-24 05:20:00",
                ],
            }
        )

        pd.testing.assert_frame_equal(df, expected_df)
    def assert_function_output(self, input_timestamps):
        df, ax = task_func(input_timestamps)
        # Assert that the DataFrame contains the correct timestamps
        self.assertEqual(df["Timestamp"].tolist(), input_timestamps)
        # Assert the histogram attributes (e.g., number of bins)
        self.assertEqual(len(ax[0]), 10)  # There should be 10 bars in the histogram

Instruction:
Write a function called `def task_func(timestamps):` to: Convert a list of Unix timestamps to date objects, create a Pandas DataFrame, and draw a histogram. - The date format should be as DATE_FORMAT. - The DataFrame should have 'Timestamp' and 'Datetime' as column names. - If the list of timestamps is empty, raise a ValueError with the message "Input list of timestamps is empty".
The function should raise the exception for: ValueError("Input list of timestamps is empty."): If the list of timestamps is empty.
The function should output with:
    pandas.DataFrame: A pandas DataFrame containing the original Unix timestamps and the converted datetime objects.
    Axes: The Axes object of the histogram plot. The histogram will have 10 bins by default, representing the distribution of the datetime objects.
You should start with:
```
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
# Constants
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
def task_func(timestamps):
```


Prompt:
from datetime import datetime
import pandas as pd
import pytz
import matplotlib.pyplot as plt

# Constants
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
TIMEZONES = [
    "America/New_York",
    "Europe/London",
    "Asia/Shanghai",
    "Asia/Tokyo",
    "Australia/Sydney",
]

def task_func(timestamp):
    """
    Convert a Unix timestamp to date objects in different time zones, create a Pandas DataFrame, and draw a bar chart.
    - You should use the time zones mentionned in the constant TIMEZONES.
    - The date format should be as DATE_FORMAT.
    - The DataFrame should have 'Timezone' and 'Datetime' as column names.
    - The x-label of the bar plot should be set to 'Timezone' while the y-label should be set to 'Datetime'.
    - The plot title should be "Datetime = f(Timezone)"

    Parameters:
    timestamp (int): The Unix timestamp.

    Returns:
    tuple: A tuple containing:
        - DataFrame: A pandas DataFrame containing the datetime in different timezones.
        - Axes: A matplotlib Axes object for the generated bar chart.

    Requirements:
    - datetime
    - pandas
    - pytz
    - matplotlib.pyplot

    Example:
    >>> df, ax = task_func(1347517370)
    >>> print(df)
               Timezone            Datetime
    0  America/New_York 2012-09-13 02:22:50
    1     Europe/London 2012-09-13 07:22:50
    2     Asia/Shanghai 2012-09-13 14:22:50
    3        Asia/Tokyo 2012-09-13 15:22:50
    4  Australia/Sydney 2012-09-13 16:22:50
    """

    datetimes = [
        datetime.fromtimestamp(timestamp, pytz.timezone(tz)).strftime(DATE_FORMAT)
        for tz in TIMEZONES
    ]
    df = pd.DataFrame({"Timezone": TIMEZONES, "Datetime": datetimes})
    df["Datetime"] = pd.to_datetime(df["Datetime"])
    ax = df.plot.bar(x="Timezone", y="Datetime", legend=False)
    plt.ylabel("Timezone")
    plt.ylabel("Datetime")
    plt.title("Datetime = f(Timezone)")
    plt.close()
    return df, ax

import unittest
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        df, ax = task_func(398024852)
        self.validate_output(df, ax)
    def test_case_2(self):
        df, ax = task_func(229981844)
        self.validate_output(df, ax)
    def test_case_3(self):
        df, ax = task_func(163757150)
        self.validate_output(df, ax)
    def test_case_4(self):
        df, ax = task_func(136821030)
        self.validate_output(df, ax)
    def test_case_5(self):
        df, ax = task_func(1318935276)
        self.validate_output(df, ax)
    def test_case_6(self):
        df, ax = task_func(2078245012)
        edf = pd.DataFrame(
            {
                "Timezone": [
                    "America/New_York",
                    "Europe/London",
                    "Asia/Shanghai",
                    "Asia/Tokyo",
                    "Australia/Sydney",
                ],
                "Datetime": [
                    "2035-11-09 13:16:52",
                    "2035-11-09 18:16:52",
                    "2035-11-10 02:16:52",
                    "2035-11-10 03:16:52",
                    "2035-11-10 05:16:52",
                ],
            }
        )
        edf = edf.astype({"Timezone": "object", "Datetime": "datetime64[ns]"})
        pd.testing.assert_frame_equal(df, edf)
        self.validate_output(df, ax)
    def validate_output(self, df, ax):
        # Test the shape of the returned DataFrame
        self.assertEqual(df.shape, (5, 2))
        # Test if the Timezones in DataFrame are correct
        expected_timezones = [
            "America/New_York",
            "Europe/London",
            "Asia/Shanghai",
            "Asia/Tokyo",
            "Australia/Sydney",
        ]
        self.assertListEqual(df["Timezone"].tolist(), expected_timezones)
        # Test if the Datetime column in DataFrame is of datetime64 type
        self.assertEqual(df["Datetime"].dtype, "datetime64[ns]")
        # Test the title of the plot
        self.assertEqual(ax.get_title(), "Datetime = f(Timezone)")
        # Test the x and y axis labels of the plot
        self.assertEqual(ax.get_xlabel(), "Timezone")
        self.assertEqual(ax.get_ylabel(), "Datetime")

Instruction:
Write a function called `def task_func(timestamp):` to: Convert a Unix timestamp to date objects in different time zones, create a Pandas DataFrame, and draw a bar chart. - You should use the time zones mentionned in the constant TIMEZONES. - The date format should be as DATE_FORMAT. - The DataFrame should have 'Timezone' and 'Datetime' as column names. - The x-label of the bar plot should be set to 'Timezone' while the y-label should be set to 'Datetime'. - The plot title should be "Datetime = f(Timezone)"
The function should output with:
    tuple: A tuple containing:
    DataFrame: A pandas DataFrame containing the datetime in different timezones.
    Axes: A matplotlib Axes object for the generated bar chart.
You should start with:
```
from datetime import datetime
import pandas as pd
import pytz
import matplotlib.pyplot as plt
# Constants
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
TIMEZONES = [
    "America/New_York",
    "Europe/London",
    "Asia/Shanghai",
    "Asia/Tokyo",
    "Australia/Sydney",
]
def task_func(timestamp):
```


Prompt:
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

def task_func(df, age: int, height: int):
    """
    Filters the input DataFrame based on specified 'Age' and 'Height' conditions and applies KMeans clustering.
    - If the filtered dataframe has less than 3  columns, add to it a column 'Cluster' with 0 for each row.
    - Otherwise, do a KMeans clustering (by Age and Height) with 3 clusters and add a column 'Cluster' to the dataframe which corresponds to the cluster
    index of the cluster to which each row belongs to.
    - Plot a scatter plot of the 'Age' and 'height' and colored by the cluster indices.
    - the xlabel should be 'Age', the ylabel 'Height' and the title 'KMeans Clustering based on Age and Height'.

    Parameters:
    df (DataFrame): The text to analyze.
    age (int): Filter out the rows of the dataframe which 'Age' value is less than or equal to this value.
    height (int): Filter out the rows of the dataframe which 'Height' value is greater than or equal to this value.

    Returns:
    DataFrame: The filtered dataframe with the new column.
    matplotlib.axes.Axes: The Axes object of the plotted data. If no KMeans was done, returns None.

    Requirements:
    - sklearn
    - matplotlib

    Example:
    >>> import pandas as pd
    >>> df = pd.DataFrame({
    ...     'Age': [30, 45, 60, 75],
    ...     'Height': [160, 170, 165, 190],
    ...     'Weight': [55, 65, 75, 85]
    ... })
    >>> selected_df, ax = task_func(df, 50, 180)
    >>> print(selected_df)
       Age  Height  Weight  Cluster
    2   60     165      75        0
    """

    # Filter the DataFrame based on given conditions
    selected_df = df[(df["Age"] > age) & (df["Height"] < height)].copy()

    # Apply KMeans clustering only if there are at least 3 rows in the filtered data
    if len(selected_df) >= 3:
        kmeans = KMeans(n_clusters=3)
        selected_df["Cluster"] = kmeans.fit_predict(selected_df[["Age", "Height"]])

        # Visualize the clusters
        plt.figure(figsize=(10, 5))
        plt.scatter(selected_df["Age"], selected_df["Height"], c=selected_df["Cluster"])
        plt.xlabel("Age")
        plt.ylabel("Height")
        plt.title("KMeans Clustering based on Age and Height")
        ax = plt.gca()
        return selected_df, ax
    else:
        selected_df["Cluster"] = 0
        return selected_df, None

    selected_df = df[(df["Age"] > age) & (df["Height"] < height)].copy()
    if len(selected_df) >= 3:
        kmeans = KMeans(n_clusters=3)
        selected_df["Cluster"] = kmeans.fit_predict(selected_df[["Age", "Height"]])
        plt.figure(figsize=(10, 5))
        plt.scatter(selected_df["Age"], selected_df["Height"], c=selected_df["Cluster"])
        plt.xlabel("Age")
        plt.ylabel("Height")
        plt.title("KMeans Clustering based on Age and Height")
        ax = plt.gca()
        return selected_df, ax
    else:
        selected_df["Cluster"] = 0
        return selected_df, None

import unittest
import pandas as pd
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        data = {
            "Age": [25, 30, 35, 40, 45],
            "Height": [160, 155, 170, 165, 150],
            "Weight": [60, 65, 70, 75, 80],
        }
        df = pd.DataFrame(data)
        result, ax = task_func(df, 28, 165)
        self.assertTrue(isinstance(result, pd.DataFrame))
        self.assertTrue("Cluster" in result.columns)
        self.assertListEqual(result["Cluster"].tolist(), [0, 0])
        self.assertTrue(max(result.loc[:, "Cluster"]) < 3)
        self.assertEqual(len(result), 2)
        self.assertIsNone(ax)
    def test_case_2(self):
        data = {
            "Age": [20, 25, 30, 35, 40],
            "Height": [150, 155, 160, 165, 170],
            "Weight": [55, 60, 65, 70, 75],
        }
        df = pd.DataFrame(data)
        result, ax = task_func(df, 30, 160)
        self.assertTrue(isinstance(result, pd.DataFrame))
        self.assertTrue("Cluster" in result.columns or len(result) < 3)
        self.assertEqual(len(result), 0)
        self.assertIsNone(ax)
    def test_case_3(self):
        data = {
            "Age": [29, 30, 35, 40, 75],
            "Height": [140, 155, 170, 165, 210],
            "Weight": [60, 65, 70, 75, 70],
        }
        df = pd.DataFrame(data)
        result, ax = task_func(df, 28, 220)
        self.assertTrue(isinstance(result, pd.DataFrame))
        self.assertTrue("Cluster" in result.columns or len(result) < 3)
        self.assertEqual(len(result), 5)
        self.assertEqual(ax.get_xlabel(), "Age")
        self.assertEqual(ax.get_ylabel(), "Height")
        self.assertEqual(ax.get_title(), "KMeans Clustering based on Age and Height")
    def test_case_4(self):
        data = {
            "Age": [25, 30, 35, 40, 45],
            "Height": [160, 155, 170, 165, 150],
            "Weight": [60, 65, 70, 75, 80],
        }
        df = pd.DataFrame(data)
        result, ax = task_func(df, 28, 180)
        self.assertTrue(isinstance(result, pd.DataFrame))
        self.assertTrue("Cluster" in result.columns)
        self.assertTrue(max(result.loc[:, "Cluster"]) < 3)
        self.assertEqual(len(result), 4)
    def test_case_5(self):
        data = {
            "Age": [25, 30, 35, 40, 45],
            "Height": [160, 155, 170, 165, 150],
            "Weight": [60, 65, 70, 75, 80],
        }
        df = pd.DataFrame(data)
        result, ax = task_func(df, 24, 165)
        self.assertTrue(isinstance(result, pd.DataFrame))
        self.assertTrue("Cluster" in result.columns)
        self.assertTrue(max(result.loc[:, "Cluster"]) < 3)
        self.assertEqual(len(result), 3)

Instruction:
Write a function called `def task_func(df, age: int, height: int):` to: Filters the input DataFrame based on specified 'Age' and 'Height' conditions and applies KMeans clustering. - If the filtered dataframe has less than 3  columns, add to it a column 'Cluster' with 0 for each row. - Otherwise, do a KMeans clustering (by Age and Height) with 3 clusters and add a column 'Cluster' to the dataframe which corresponds to the cluster index of the cluster to which each row belongs to. - Plot a scatter plot of the 'Age' and 'height' and colored by the cluster indices. - the xlabel should be 'Age', the ylabel 'Height' and the title 'KMeans Clustering based on Age and Height'.
The function should output with:
    DataFrame: The filtered dataframe with the new column.
    matplotlib.axes.Axes: The Axes object of the plotted data. If no KMeans was done, returns None.
You should start with:
```
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
def task_func(df, age: int, height: int):
```


Prompt:
import pandas as pd
import regex as re

# Constants
STOPWORDS = ["a", "an", "the", "in", "is", "are"]

def task_func(text):
    """
    Count the frequency of each word in a text after removing specific stopwords.

    Parameters:
    text (str): The text to analyze.

    Returns:
    Series: A pandas Series with word frequencies excluding the words in STOPWORDS list.

    Requirements:
    - pandas
    - regex

    Example:
    >>> text = "This is a sample text. This text contains sample words."
    >>> word_counts = task_func(text)
    >>> print(word_counts)
    this        2
    sample      2
    text        2
    contains    1
    words       1
    dtype: int64
    """

    words = re.findall(r"\b\w+\b", text.lower())
    words = [word for word in words if word not in STOPWORDS]
    word_counts = pd.Series(words).value_counts().rename(None)
    return word_counts

import unittest
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        text = "This is a sample text This text contains sample words"
        word_counts = task_func(text).to_dict()
        expected_counts = {"this": 2, "sample": 2, "text": 2, "contains": 1, "words": 1}
        self.assertDictEqual(word_counts, expected_counts)
    def test_case_2(self):
        text = "Hello world Hello everyone"
        word_counts = task_func(text).to_dict()
        expected_counts = {"hello": 2, "world": 1, "everyone": 1}
        self.assertDictEqual(word_counts, expected_counts)
    def test_case_3(self):
        text = "a an the in is are"
        word_counts = task_func(text).to_dict()
        expected_counts = {}
        self.assertDictEqual(word_counts, expected_counts)
    def test_case_4(self):
        text = "This is a test sentence which has a bunch of words and no period"
        word_counts = task_func(text).to_dict()
        expected_counts = {
                "this": 1,
                "test": 1,
                "sentence": 1,
                "which": 1,
                "has": 1,
                "bunch": 1,
                "of": 1,
                "words": 1,
                "and": 1,
                "no": 1,
                "period": 1,
            }
        self.assertDictEqual(word_counts, expected_counts)
    def test_case_5(self):
        text = (
            "I I I want want to to to to to go to to to the olympics olympics this year"
        )
        word_counts = task_func(text).to_dict()
        expected_counts = {"i": 3, "want": 2, "to": 8, "go": 1, "olympics": 2, "this": 1, "year": 1}
        self.assertDictEqual(word_counts, expected_counts)

Instruction:
Write a function called `def task_func(text):` to: Count the frequency of each word in a text after removing specific stopwords.
The function should output with:
    Series: A pandas Series with word frequencies excluding the words in STOPWORDS list.
You should start with:
```
import pandas as pd
import regex as re
# Constants
STOPWORDS = ["a", "an", "the", "in", "is", "are"]
def task_func(text):
```


Prompt:
import pandas as pd
import regex as re
import seaborn as sns
import matplotlib.pyplot as plt

COLUMN_NAMES = ["Name", "Email", "Age", "Country"]

def task_func(text):
    """
    Extract data from a text and create a Pandas DataFrame.
    The text contains several lines, each formatted as 'Name: John Doe, Email: john.doe@example.com, Age: 30, Country: USA'.
    Plot the age distribution using seaborn.

    The data is extracted using the regular expression pattern:
    "Name: (.*?), Email: (.*?), Age: (.*?), Country: (.*?)($|\n)"
    and the resulting DataFrame has columns: ['Name', 'Email', 'Age', 'Country']

    Parameters:
    text (str): The text to analyze.

    Returns:
    DataFrame: A pandas DataFrame with extracted data.

    Requirements:
    - pandas
    - regex
    - seaborn
    - matplotlib.pyplot

    Example:
    >>> text = 'Name: John Doe, Email: john.doe@example.com, Age: 30, Country: USA\\nName: Jane Doe, Email: jane.doe@example.com, Age: 25, Country: UK'
    >>> df = task_func(text)
    >>> print(df)
           Name                 Email  Age Country
    0  John Doe  john.doe@example.com   30     USA
    1  Jane Doe  jane.doe@example.com   25      UK
    """

    pattern = r"Name: (.*?), Email: (.*?), Age: (.*?), Country: (.*?)($|\n)"
    matches = re.findall(pattern, text)
    data = []
    for match in matches:
        data.append(match[:-1])
    df = pd.DataFrame(data, columns=COLUMN_NAMES)
    df["Age"] = df["Age"].astype(int)
    sns.histplot(data=df, x="Age")
    plt.show()
    return df

import unittest
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        input_text = "Name: John Doe, Email: john.doe@example.com, Age: 30, Country: USA\nName: Jane Doe, Email: jane.doe@example.com, Age: 25, Country: UK"
        df = task_func(input_text)
        self.assertEqual(df.shape, (2, 4))
        self.assertListEqual(list(df.columns), ["Name", "Email", "Age", "Country"])
        self.assertListEqual(
            df.iloc[0].tolist(), ["John Doe", "john.doe@example.com", 30, "USA"]
        )
        self.assertListEqual(
            df.iloc[1].tolist(), ["Jane Doe", "jane.doe@example.com", 25, "UK"]
        )
    def test_case_2(self):
        input_text = (
            "Name: Alex Smith, Email: alex.smith@example.com, Age: 35, Country: Canada"
        )
        df = task_func(input_text)
        self.assertEqual(df.shape, (1, 4))
        self.assertListEqual(
            df.iloc[0].tolist(), ["Alex Smith", "alex.smith@example.com", 35, "Canada"]
        )
    def test_case_3(self):
        input_text = ""
        df = task_func(input_text)
        self.assertTrue(df.empty)
    def test_case_4(self):
        input_text = (
            "Name: Alex Smith, Email: alex.smith@example.com, Age: 35, Country: Canada"
        )
        df = task_func(input_text)
        self.assertEqual(df.shape, (1, 4))
        self.assertListEqual(
            df.iloc[0].tolist(), ["Alex Smith", "alex.smith@example.com", 35, "Canada"]
        )
    def test_case_5(self):
        input_text = """Name: Alex Smith, Email: alex.smith@example.com, Age: 35, Country: Canada
        Name: Bob Miller, Email: bob.miller@example.com, Age: 25, Country: USA
        Name: Anna Karin, Email: anna.karin@example.com, Age: 47, Country: Finland
        """
        df = task_func(input_text)
        self.assertEqual(df.shape, (3, 4))
        self.assertListEqual(list(df.columns), ["Name", "Email", "Age", "Country"])
        self.assertListEqual(
            df.iloc[0].tolist(), ["Alex Smith", "alex.smith@example.com", 35, "Canada"]
        )
        self.assertListEqual(
            df.iloc[1].tolist(), ["Bob Miller", "bob.miller@example.com", 25, "USA"]
        )
        self.assertListEqual(
            df.iloc[2].tolist(), ["Anna Karin", "anna.karin@example.com", 47, "Finland"]
        )

0  John Doe  john.doe@example.com   30     USA

1  Jane Doe  jane.doe@example.com   25      UK

Instruction:
Write a function called `def task_func(text):` to: Extract data from a text and create a Pandas DataFrame. The text contains several lines, each formatted as 'Name: John Doe, Email: john.doe@example.com, Age: 30, Country: USA'. Plot the age distribution using seaborn. The data is extracted using the regular expression pattern: "Name: (.*?), Email: (.*?), Age: (.*?), Country: (.*?)($|\n)" and the resulting DataFrame has columns: ['Name', 'Email', 'Age', 'Country']
The function should output with:
    DataFrame: A pandas DataFrame with extracted data.
You should start with:
```
import pandas as pd
import regex as re
import seaborn as sns
import matplotlib.pyplot as plt
COLUMN_NAMES = ["Name", "Email", "Age", "Country"]
def task_func(text):
```


Prompt:
import pandas as pd
import regex as re
from sklearn.feature_extraction.text import CountVectorizer

def task_func(text):
    """
    Analyze a text by creating a document term matrix with CountVectorizer. The text contains several sentences, each separated by a period.
    Ignore empty sentences.

    Parameters:
    text (str): The text to analyze.

    Returns:
    DataFrame: A pandas DataFrame with the document-term matrix. Its column names should be adapted from the vectorizer feature names.

    Requirements:
    - pandas
    - regex
    - sklearn.feature_extraction.text.CountVectorizer

    Example:
    >>> text = "This is a sample sentence. This sentence contains sample words."
    >>> dtm = task_func(text)
    >>> print(dtm)
       contains  is  sample  sentence  this  words
    0         0   1       1         1     1      0
    1         1   0       1         1     1      1
    """

    sentences = re.split(r"\.\s*", text)
    sentences = [sentence for sentence in sentences if len(sentence.strip()) != 0]
    vectorizer = CountVectorizer()
    dtm = vectorizer.fit_transform(sentences)
    df = pd.DataFrame(dtm.toarray(), columns=vectorizer.get_feature_names_out())
    return df

import unittest
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        # Test with a basic input
        text = "This is a sample sentence. This sentence contains sample words."
        dtm = task_func(text)
        # Assertions
        self.assertEqual(
            dtm.shape, (2, 6)
        )  # Expected 2 rows (sentences) and 6 unique words
        self.assertEqual(dtm["sample"].tolist(), [1, 1])
        self.assertEqual(dtm["this"].tolist(), [1, 1])
    def test_case_2(self):
        # Test with a single sentence (with a trailing period)
        text = "A single sentence."
        dtm = task_func(text)
        # Assertions
        self.assertEqual(
            dtm.shape, (1, 2)
        )  # Expected 1 rows (sentences) and 2 unique words
        self.assertEqual(dtm["single"].tolist(), [1])
    def test_case_3(self):
        # Test with no periods (still should consider it as one sentence)
        text = "No periods in this text"
        dtm = task_func(text)
        # Assertions
        self.assertEqual(
            dtm.shape, (1, 5)
        )  # Expected 1 row (sentence) and 5 unique words
        self.assertEqual(dtm["text"].tolist(), [1])
    def test_case_4(self):
        # Test with a single sentence (with same word multiple times)
        text = ("test test test test test test test test test test test " * 3).strip()
        dtm = task_func(text)
        # Assertions
        self.assertEqual(
            dtm.shape, (1, 1)
        )  # Expected 1 row (sentence) and 1 unique words
        self.assertEqual(dtm["test"].tolist(), [33])
    def test_case_5(self):
        # Test with no periods (still should consider it as one sentence)
        text = "This is the first sentence. This is the second sentence. This is the third sentence. This is the fourth sentence. This is the fith and last sentence."
        dtm = task_func(text)
        # Assertions
        self.assertEqual(
            dtm.shape, (5, 11)
        )  # Expected 5 rows (sentence) and 11 unique words
        self.assertEqual(dtm["this"].tolist(), [1, 1, 1, 1, 1])
        self.assertEqual(dtm["is"].tolist(), [1, 1, 1, 1, 1])
        self.assertEqual(dtm["the"].tolist(), [1, 1, 1, 1, 1])
        self.assertEqual(dtm["sentence"].tolist(), [1, 1, 1, 1, 1])

Ignore empty sentences.

contains  is  sample  sentence  this  words

Instruction:
Write a function called `def task_func(text):` to: Analyze a text by creating a document term matrix with CountVectorizer. The text contains several sentences, each separated by a period. Ignore empty sentences.
The function should output with:
    DataFrame: A pandas DataFrame with the document-term matrix. Its column names should be adapted from the vectorizer feature names.
You should start with:
```
import pandas as pd
import regex as re
from sklearn.feature_extraction.text import CountVectorizer
def task_func(text):
```


Prompt:
import re
import pandas as pd

STOPWORDS = ["Those", "are", "the", "words", "to", "ignore"]

def task_func(text):
    """
    Given a text as input, the function should split it into multiple sentences and build a dictionary where each key is associated with a sentence and the corresponding value is the number of words in the sentence. The function returns a pandas Series built from the dictionary.
    - The keys of the dictionary (which correspond to the Index of the pandas Series) should be named "Sentence 1", "Sentence 2" etc.
    - When counting the words in a sentence, do not consider those included in the constant STOPWORDS.
    - Do not consider empty sentences.

    Parameters:
    text (str): The text to analyze.

    Returns:
    pandas.core.series.Series: A pandas Series each sentence and its number of words that are not in STOPWORDS.

    Requirements:
    - pandas
    - regex

    Example:
    >>> text = "This is a sample sentence. This sentence contains sample words."
    >>> df = task_func("I am good at programming. I learned it in college.")
    >>> print(df)
    Sentence 1    5
    Sentence 2    5
    dtype: int64
    """

    sentences = re.split(r"\.\s*", text)
    sentence_counts = {}

    for i, sentence in enumerate(sentences):
        if sentence.strip() == "":
            continue
        words = re.split(r"\s+", sentence.lower())
        words = [word for word in words if word not in STOPWORDS]
        sentence_counts[f"Sentence {i+1}"] = len(words)

    sentence_counts = pd.Series(sentence_counts)
    return sentence_counts

import unittest
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        text = "This is a sample sentence. This sentence contains sample words."
        expected_output = pd.Series({"Sentence 1": 5, "Sentence 2": 4})
        result = task_func(text)
        pd.testing.assert_series_equal(result, expected_output)
    def test_case_2(self):
        text = "Hello. My name is Marc. I'm here to help. How can I assist you today?"
        expected_output = pd.Series(
            {"Sentence 1": 1, "Sentence 2": 4, "Sentence 3": 3, "Sentence 4": 6}
        )
        result = task_func(text)
        pd.testing.assert_series_equal(result, expected_output)
    def test_case_3(self):
        text = "This is a test. Stopwords are words which do not contain important meaning."
        expected_output = pd.Series({"Sentence 1": 4, "Sentence 2": 7})
        result = task_func(text)
        pd.testing.assert_series_equal(result, expected_output)
    def test_case_4(self):
        text = "Hello! How are you? I'm fine, thanks."
        expected_output = pd.Series(
            {"Sentence 1": 6}
        )  # Only the last sentence is split by a period
        result = task_func(text)
        pd.testing.assert_series_equal(result, expected_output)
    def test_case_5(self):
        text = ""
        expected_output = pd.Series()
        result = task_func(text)
        pd.testing.assert_series_equal(result, expected_output)

- Do not consider empty sentences.

Instruction:
Write a function called `def task_func(text):` to: Given a text as input, the function should split it into multiple sentences and build a dictionary where each key is associated with a sentence and the corresponding value is the number of words in the sentence. The function returns a pandas Series built from the dictionary. - The keys of the dictionary (which correspond to the Index of the pandas Series) should be named "Sentence 1", "Sentence 2" etc. - When counting the words in a sentence, do not consider those included in the constant STOPWORDS. - Do not consider empty sentences.
The function should output with:
    pandas.core.series.Series: A pandas Series each sentence and its number of words that are not in STOPWORDS.
You should start with:
```
import re
import pandas as pd
STOPWORDS = ["Those", "are", "the", "words", "to", "ignore"]
def task_func(text):
```


Prompt:
import pandas as pd
import regex as re

def task_func(text):
    """
    Extract data from a text and create a Pandas DataFrame. The text contains several lines, each formatted as 'Score: 85, Category: Math'. Make sure to convert the scores in integer.

    Parameters:
    text (str): The text to analyze.

    Returns:
    DataFrame: A pandas DataFrame with extracted data.

    Requirements:
    - pandas
    - regex

    Example:
    >>> text = "Score: 85, Category: Math\\nScore: 90, Category: Science\\nScore: 80, Category: Math"
    >>> df = task_func(text)
    >>> print(df)
       Score Category
    0     85     Math
    1     90  Science
    2     80     Math
    """

    pattern = r"Score: (.*?), Category: (.*?)(\n|$)"
    matches = re.findall(pattern, text)
    data = [
        match[:2] for match in matches
    ]  # Extracting only the score and category from each match
    df = pd.DataFrame(data, columns=["Score", "Category"])
    df["Score"] = df["Score"].astype(int)
    return df

import unittest
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        text = "Score: 85, Category: Math\nScore: 90, Category: Science\nScore: 80, Category: Math"
        df = task_func(text)
        self.assertEqual(len(df), 3)
        self.assertEqual(df["Score"].iloc[0], 85)
        self.assertEqual(df["Category"].iloc[0], "Math")
        self.assertEqual(df["Score"].iloc[1], 90)
        self.assertEqual(df["Category"].iloc[1], "Science")
        self.assertEqual(df["Score"].iloc[2], 80)
        self.assertEqual(df["Category"].iloc[2], "Math")
    def test_case_2(self):
        text = "Score: 70, Category: History"
        df = task_func(text)
        self.assertEqual(len(df), 1)
        self.assertEqual(df["Score"].iloc[0], 70)
        self.assertEqual(df["Category"].iloc[0], "History")
    def test_case_3(self):
        text = ""  # Empty string
        df = task_func(text)
        self.assertEqual(len(df), 0)  # Expecting an empty DataFrame
    def test_case_4(self):
        text = "Score: 70, Category: Chemistry"
        df = task_func(text)
        self.assertEqual(len(df), 1)
        self.assertEqual(df["Score"].iloc[0], 70)
        self.assertEqual(df["Category"].iloc[0], "Chemistry")
    def test_case_5(self):
        text = "Score: 70, Category: Literature\nScore: 37, Category: Mathematics\nScore: 90, Category: Japanese\nScore: 58, Category: Machine Learning"
        df = task_func(text)
        self.assertEqual(len(df), 4)
        self.assertEqual(df["Score"].iloc[0], 70)
        self.assertEqual(df["Category"].iloc[0], "Literature")
        self.assertEqual(df["Score"].iloc[1], 37)
        self.assertEqual(df["Category"].iloc[1], "Mathematics")
        self.assertEqual(df["Score"].iloc[2], 90)
        self.assertEqual(df["Category"].iloc[2], "Japanese")
        self.assertEqual(df["Score"].iloc[3], 58)
        self.assertEqual(df["Category"].iloc[3], "Machine Learning")

Instruction:
Write a function called `def task_func(text):` to: Extract data from a text and create a Pandas DataFrame. The text contains several lines, each formatted as 'Score: 85, Category: Math'. Make sure to convert the scores in integer.
The function should output with:
    DataFrame: A pandas DataFrame with extracted data.
You should start with:
```
import pandas as pd
import regex as re
def task_func(text):
```


Prompt:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

def task_func(csv_file_path: str, title: str):
    """
    Create a heatmap of the correlation matrix of a DataFrame built from a CSV file. Round each correlation to 2 decimals.

    Parameters:
    csv_file_path (str): The path to the CSV file containing the input data.
    title (str): The title of the heatmap.

    Returns:
    DataFrame: correlation dataframe where each row and each column correspond to a specific column.
    matplotlib.axes.Axes: The Axes object of the plotted data.

    Requirements:
    - pandas
    - matplotlib.pyplot
    - seaborn

    Example:
    >>> data = "data/task_func/csv_1.csv"
    >>> c, ax = task_func(data, 'Correlation Heatmap')
    """

    data = pd.read_csv(csv_file_path)
    corr = data.corr().round(2)
    plt.figure(figsize=(10, 8))
    sns.heatmap(corr, annot=True, cmap='coolwarm', cbar=True)
    plt.title(title)
    return corr, plt.gca()

import unittest
import os
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def setUp(self) -> None:
        self.test_dir = "data/task_func"
        os.makedirs(self.test_dir, exist_ok=True)
        data = pd.DataFrame({'A': range(10), 'B': range(10), 'C': range(10)})
        data.to_csv(os.path.join(self.test_dir, "csv_1.csv"), index=False)
        data = pd.DataFrame({'X': [1, 2, 3, 4, 5], 'Y': [5, 4, 3, 2, 1], 'Z': [2, 3, 4, 5, 6]})
        data.to_csv(os.path.join(self.test_dir, "csv_2.csv"), index=False)
        data = pd.DataFrame({'M': [10, 20, 30], 'N': [30, 20, 10], 'O': [15, 25, 35]})
        data.to_csv(os.path.join(self.test_dir, "csv_3.csv"), index=False)
        data = pd.DataFrame({'P': [10, 43], 'Q': [32, 19], 'R': [22, 16]})
        data.to_csv(os.path.join(self.test_dir, "csv_4.csv"), index=False)
        data = pd.DataFrame({'S': [1, 7, 3], 'T': [9, 9, 5], 'U': [5, 8, 2]})
        data.to_csv(os.path.join(self.test_dir, "csv_5.csv"), index=False)

    def tearDown(self) -> None:
        import shutil
        try:
            shutil.rmtree(self.test_dir)
        except:
            pass
    def test_case_1(self):
        title = 'Test Case 1'
        expected_c = pd.DataFrame(
            {
                "A" : [1.0, 1.0, 1.0],
                "B" : [1.0, 1.0, 1.0],
                "C" : [1.0, 1.0, 1.0]
            },
            index = ["A", "B", "C"]
        )
        c, ax = task_func(os.path.join(self.test_dir, "csv_1.csv"), title)
        self.assertEqual(ax.get_title(), title)
        pd.testing.assert_frame_equal(c, expected_c)
    def test_case_2(self):
        title = 'Test Case 2'
        expected_c = pd.DataFrame(
            {
                "X" : [1.0, -1.0, 1.0],
                "Y" : [-1.0, 1.0, -1.0],
                "Z" : [1.0, -1.0, 1.0]
            },
            index = ["X", "Y", "Z"]
        )
        c, ax = task_func(os.path.join(self.test_dir, "csv_2.csv"), title)
        self.assertEqual(ax.get_title(), title)
        pd.testing.assert_frame_equal(c, expected_c)
    def test_case_3(self):
        title = 'Test Case 3'
        _, ax = task_func(os.path.join(self.test_dir, "csv_3.csv"), title)
        self.assertEqual(ax.get_title(), title)

    def test_case_4(self):
        title = 'Test Case 4'
        _, ax = task_func(os.path.join(self.test_dir, "csv_4.csv"), title)
        self.assertEqual(ax.get_title(), title)
    def test_case_5(self):
        title = 'Test Case 5'
        expected_c = pd.DataFrame(
            {
                "S" : [1.0, 0.19, 0.65],
                "T" : [0.19, 1.0, 0.87],
                "U" : [0.65, 0.87, 1.0]
            },
            index = ["S", "T", "U"]
        )
        c, ax = task_func(os.path.join(self.test_dir, "csv_5.csv"), title)
        self.assertEqual(ax.get_title(), title)
        pd.testing.assert_frame_equal(c, expected_c)

Instruction:
Write a function called `def task_func(csv_file_path: str, title: str):` to: Create a heatmap of the correlation matrix of a DataFrame built from a CSV file. Round each correlation to 2 decimals.
The function should output with:
    DataFrame: correlation dataframe where each row and each column correspond to a specific column.
    matplotlib.axes.Axes: The Axes object of the plotted data.
You should start with:
```
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def task_func(csv_file_path: str, title: str):
```


Prompt:
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

def task_func(mu, sigma, num_samples):
    """
    Display a plot showing a normal distribution with a given mean and standard deviation and overlay a histogram of randomly generated samples from this distribution.
    The plot title should be 'Normal Distribution'.

    Parameters:
    mu (float): The mean of the distribution.
    sigma (float): The standard deviation of the distribution.
    num_samples (int): The number of samples to generate.

    Returns:
    fig (matplotlib.figure.Figure): The generated figure. Useful for testing purposes.

    Requirements:
    - numpy
    - scipy.stats
    - matplotlib.pyplot

    Example:
    >>> plt = task_func(0, 1, 1000)
    """

    samples = np.random.normal(mu, sigma, num_samples)
    fig, ax = plt.subplots()
    ax.hist(samples, bins=30, density=True, alpha=0.6, color='g')

    xmin, xmax = plt.xlim()
    x = np.linspace(xmin, xmax, 100)
    p = stats.norm.pdf(x, mu, sigma)
    ax.plot(x, p, 'k', linewidth=2)

    ax.set_title('Normal Distribution')
    plt.show()
    return fig

import unittest
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        np.random.seed(42)
        mu = 0
        sigma = 1
        num_samples = 1000
        fig = task_func(mu, sigma, num_samples)
        ax = fig.gca()
        self.assertEqual(ax.get_title(), "Normal Distribution")
        self.assertTrue(len(ax.patches) > 0)
        self.assertTrue(len(ax.lines) > 0)
    def test_case_2(self):
        np.random.seed(42)
        mu = 5
        sigma = 2
        num_samples = 1000
        fig = task_func(mu, sigma, num_samples)
        ax = fig.gca()
        self.assertEqual(ax.get_title(), "Normal Distribution")
        self.assertTrue(len(ax.patches) > 0)
        self.assertTrue(len(ax.lines) > 0)
    def test_case_3(self):
        np.random.seed(42)
        mu = 0
        sigma = 1
        num_samples = 10
        fig = task_func(mu, sigma, num_samples)
        ax = fig.gca()
        self.assertEqual(ax.get_title(), "Normal Distribution")
        self.assertTrue(len(ax.patches) > 0)
        self.assertTrue(len(ax.lines) > 0)
    def test_case_4(self):
        np.random.seed(42)
        mu = 0
        sigma = 1
        num_samples = 10
        fig = task_func(mu, sigma, num_samples)
        ax = fig.gca()
        self.assertEqual(ax.get_title(), "Normal Distribution")
        self.assertTrue(len(ax.patches) > 0)
        self.assertTrue(len(ax.lines) > 0)
    def test_case_5(self):
        np.random.seed(42)
        mu = 0
        sigma = 1
        num_samples = 10
        fig = task_func(mu, sigma, num_samples)
        ax = fig.gca()
        self.assertEqual(ax.get_title(), "Normal Distribution")
        self.assertTrue(len(ax.patches) > 0)
        self.assertTrue(len(ax.lines) > 0)

Instruction:
Write a function called `def task_func(mu, sigma, num_samples):` to: Display a plot showing a normal distribution with a given mean and standard deviation and overlay a histogram of randomly generated samples from this distribution. The plot title should be 'Normal Distribution'.
The function should output with:
    fig (matplotlib.figure.Figure): The generated figure. Useful for testing purposes.
You should start with:
```
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
def task_func(mu, sigma, num_samples):
```


Prompt:
import wikipedia
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def task_func(page_title):
    """
    Create a word cloud from the text of a Wikipedia page.

    Parameters:
    page_title (str): The title of the Wikipedia page.

    Returns:
    matplotlib.axes.Axes: The Axes object of the plotted data. Is None if there is no wikipedia page with the title given as input.

    Requirements:
    - wikipedia
    - wordcloud.WordCloud
    - matplotlib.pyplot

    Example:
    >>> ax = task_func('Python (programming language)')
    """

    try:
        text = wikipedia.page(page_title).content
    except Exception as e:
        print(f"An error occured: {e}")
        return None
    wordcloud = WordCloud().generate(text)
    plt.figure(figsize=(10, 5))
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    ax = plt.gca()
    return ax

import unittest
from unittest.mock import patch
class A :
    def __init__(self, content) -> None:
        self.content = content
        self.text = content
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    @patch('wikipedia.page')
    def test_case_1(self, mock_function):
        # Mocking the function to prevent actual execution
        mock_function.return_value = A("I want to sleep")
        # Running the function
        _ = task_func('Python (programming language)')
    @patch('wikipedia.page')
    def test_case_2(self, mock_function):
        # Mocking the function to prevent actual execution
        mock_function.return_value = A("I want to sleep because it is important to sleep.")
        # Running the function
        _ = task_func('Python (programming language)')
    @patch('wikipedia.page')
    def test_case_3(self, mock_function):
        # Mocking the function to prevent actual execution
        mock_function.return_value = A("I want to sleep")
        # Running the function
        _ = task_func('Python (programming language)')
    @patch('wikipedia.page')
    def test_case_4(self, mock_function):
        # Mocking the function to prevent actual execution
        mock_function.return_value =A("I want to eat")
        # Running the function
        _ = task_func('Python (programming language)')
    @patch('wikipedia.page')
    def test_case_5(self, mock_function):
        # Mocking the function to prevent actual execution
        mock_function.return_value = A("I want to help you to get your business to work.")
        # Running the function
        _ = task_func('Python (programming language)')
    def test_case_6(self):
        ax = task_func("Invalid Page Title")
        self.assertIsNone(ax)

Instruction:
Write a function called `def task_func(page_title):` to: Create a word cloud from the text of a Wikipedia page.
The function should output with:
    matplotlib.axes.Axes: The Axes object of the plotted data. Is None if there is no wikipedia page with the title given as input.
You should start with:
```
import wikipedia
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def task_func(page_title):
```


Prompt:
import json
import pandas as pd

def task_func(result, csv_file_path="test.csv", json_file_path="test.json"):
    """
    Save the list of dictionaries provided in the 'result' parameter to a CSV file (without index) and a JSON file.

    Parameters:
    - result (list): A list of dictionaries.
    - csv_file_path (str): A path to a CSV file.
    - json_file_path (str): A path to a JSON file.

    Returns:
    None

    Requirements:
    - pandas
    - json

    Example:
    >>> result = [{"hi": 7, "bye": 4, "from_user": 0}, {1: 2, 3: 4, 5: 6}]
    >>> task_func(result, 'test.csv', 'test.json')
    """

    # Save to CSV
    df = pd.DataFrame(result)
    df.to_csv(csv_file_path, index=False)

    # Save to JSON
    with open(json_file_path, 'w') as f:
        json.dump(result, f, indent=4)

    return None

    df = pd.DataFrame(result)
    df.to_csv(csv_file_path, index=False)
    with open(json_file_path, 'w') as f:
        json.dump(result, f, indent=4)
    return None

import unittest
import os
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def setUp(self):
        self.test_dir = "data/task_func"
        os.makedirs(self.test_dir, exist_ok=True)
        self.f_1 = os.path.join(self.test_dir, "csv_1.csv")
        self.f_2 = os.path.join(self.test_dir, "csv_2.csv")
        self.f_3 = os.path.join(self.test_dir, "csv_3.csv")
        self.f_4 = os.path.join(self.test_dir, "csv_4.csv")
        self.f_5 = os.path.join(self.test_dir, "csv_5.csv")
        self.j_1 = os.path.join(self.test_dir, "json_1.json")
        self.j_2 = os.path.join(self.test_dir, "json_2.json")
        self.j_3 = os.path.join(self.test_dir, "json_3.json")
        self.j_4 = os.path.join(self.test_dir, "json_4.json")
        self.j_5 = os.path.join(self.test_dir, "json_5.json")
    def tearDown(self):
        import shutil
        if os.path.exists(self.test_dir):
            shutil.rmtree(self.test_dir)
    def test_case_1(self):
        # Test with a list of dictionaries with string keys and integer values
        result = [
            {"hi": 7, "bye": 4, "from_user": 0}
        ]
        task_func(result, self.f_1, self.j_1)
        self.assertTrue(os.path.exists(self.f_1))
        self.assertTrue(os.path.exists(self.j_1))
        with open(self.j_1, 'r') as f:
            loaded_json = json.load(f)
        # Adjusting the expected result for JSON's string keys
        expected_result = [{"hi": 7, "bye": 4, "from_user": 0}]
        self.assertEqual(loaded_json, expected_result)
    def test_case_2(self):
        # Test with a list of dictionaries with integer keys and values
        result = [{1: 2, 3: 4, 5: 6}]
        task_func(result, self.f_2, self.j_2)
        self.assertTrue(os.path.exists(self.f_2))
        self.assertTrue(os.path.exists(self.j_2))
        with open(self.j_2, 'r') as f:
            loaded_json = json.load(f)
        # Adjusting the expected result for JSON's string keys
        expected_result = [{"1": 2, "3": 4, "5": 6}]
        self.assertEqual(loaded_json, expected_result)
    def test_case_3(self):
        # Test with an empty list
        result = []
        task_func(result, self.f_3, self.j_3)
        self.assertTrue(os.path.exists(self.f_3))
        self.assertTrue(os.path.exists(self.j_3))
        with open(self.j_3, 'r') as f:
            loaded_json = json.load(f)
        # Adjusting the expected result for JSON's string keys
        expected_result = []
        self.assertEqual(loaded_json, expected_result)
    def test_case_4(self):
        # Test with a list of dictionaries with string keys and integer values
        result = [
            {"hi": 7, "bye": 4, "from_user": 3}
        ]
        task_func(result, self.f_4, self.j_4)
        self.assertTrue(os.path.exists(self.f_4))
        self.assertTrue(os.path.exists(self.j_4))
        with open(self.j_4, 'r') as f:
            loaded_json = json.load(f)
        # Adjusting the expected result for JSON's string keys
        expected_result = [{"hi": 7, "bye": 4, "from_user": 3}]
        self.assertEqual(loaded_json, expected_result)
    def test_case_5(self):
        # Test with a list of dictionaries with string keys and integer values
        result = [
            {"hi": 7, "bye": 4, "from_user": 11}
        ]
        task_func(result, self.f_5, self.j_5)
        self.assertTrue(os.path.exists(self.f_5))
        df = pd.read_csv(self.f_5)
        self.assertEqual(df.loc[0, "hi"], 7)
        self.assertEqual(df.loc[0, "bye"], 4)
        self.assertEqual(df.loc[0, "from_user"], 11)
        self.assertTrue(os.path.exists(self.j_5))
        with open(self.j_5, 'r') as f:
            loaded_json = json.load(f)
        # Adjusting the expected result for JSON's string keys
        expected_result = [{"hi": 7, "bye": 4, "from_user": 11}]
        self.assertEqual(loaded_json, expected_result)

Instruction:
Write a function called `def task_func(result, csv_file_path="test.csv", json_file_path="test.json"):` to: Save the list of dictionaries provided in the 'result' parameter to a CSV file (without index) and a JSON file.
The function should output with:
    None
You should start with:
```
import json
import pandas as pd
def task_func(result, csv_file_path="test.csv", json_file_path="test.json"):
```


Prompt:
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime

# Constants
PLOT_TITLE = 'Square root plot'
X_LABEL = 'x'
Y_LABEL = 'sqrt(x)'
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'

def task_func(result):
    """
    Plots the square root function for values associated with the key 'from_user' from the input list of dictionaries. Annotates the graph with the current date and time.
    - Round each square root value to 2 decimals.

    Parameters:
    result (list): A list of dictionaries containing numeric values with the key 'from_user'.

    Returns:
    - numpy.ndarray: list of square values associated with the key 'from_user' from the input list of dictionaries.
    - matplotlib.axes.Axes: plot of square root values.

    Requirements:
    - numpy
    - matplotlib.pyplot
    - datetime

    Constants:
    - PLOT_TITLE: Title of the plot (default is 'Square root plot').
    - X_LABEL: Label for the x-axis (default is 'x').
    - Y_LABEL: Label for the y-axis (default is 'sqrt(x)').
    - TIME_FORMAT: Format for displaying the current date and time (default is '%Y-%m-%d %H:%M:%S').

    Example:
    >>> result = [{"hi": 7, "bye": 4, "from_user": 16}, {"some_key": 2, "another_key": 4, "from_user": 9}]
    >>> square_roots, ax = task_func(result)
    >>> print(square_roots)
    [4. 3.]
    """

    # Extract the 'from_user' values
    from_user_values = [d['from_user'] for d in result if 'from_user' in d]

    # Calculate the square roots
    square_roots = np.round(np.sqrt(from_user_values), 2)

    # Plot the square root function
    plt.figure()
    plt.plot(from_user_values, square_roots)
    plt.title(PLOT_TITLE)
    plt.xlabel(X_LABEL)
    plt.ylabel(Y_LABEL)

    # Annotate the plot with the current date and time
    now = datetime.now()
    now_str = now.strftime(TIME_FORMAT)
    plt.annotate(now_str, (0.05, 0.95), xycoords='axes fraction')
    ax = plt.gca()
    return square_roots, ax

    from_user_values = [d['from_user'] for d in result if 'from_user' in d]
    square_roots = np.round(np.sqrt(from_user_values), 2)
    plt.figure()
    plt.plot(from_user_values, square_roots)
    plt.title(PLOT_TITLE)
    plt.xlabel(X_LABEL)
    plt.ylabel(Y_LABEL)
    now = datetime.now()
    now_str = now.strftime(TIME_FORMAT)
    plt.annotate(now_str, (0.05, 0.95), xycoords='axes fraction')
    ax = plt.gca()
    return square_roots, ax

import unittest
import matplotlib
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        # Input 1: Normal case with 2 dictionaries with 'from_user' keys.
        data = [
            {"key_1": 7, "key_2": 4, "from_user": 16},
            {"key_1": 2, "key_2": 4, "from_user": 9},
        ]
        square_roots, ax = task_func(data)
        self.assertEqual(ax.get_title(), PLOT_TITLE)
        self.assertEqual(ax.get_xlabel(), X_LABEL)
        self.assertEqual(ax.get_ylabel(), Y_LABEL)
        np.testing.assert_array_equal(square_roots, np.array([4.0, 3.0]))
        annotations = [child for child in ax.get_children() if isinstance(child, matplotlib.text.Annotation)]
        try:
            datetime.strptime(annotations[0].get_text(), TIME_FORMAT)
        except:
            raise ValueError(f"The datetime in annotation ({annotations[0]}) does not have the right format ({TIME_FORMAT}).")
    def test_case_2(self):
        # Input 2: List with 1 dictionary without the 'from_user' key.
        data = [
            {
                "key_1": 7,
                "key_2": 4
            }
        ]
        square_roots, ax = task_func(data)
        self.assertEqual(len(square_roots), 0)
    def test_case_3(self):
        # Input 3: Empty list.
        data = []
        square_roots, ax = task_func(data)
        self.assertEqual(len(square_roots), 0)
    def test_case_4(self):
        # Input 4: Normal case with 5 dictionaries with 'from_user' keys.
        data = [
            {
                "from_user": 121,
                "unused_key": 45,
            },
            {
                "from_user": 169,
                "unused_key": -1,
            },
            {
                "from_user": 225,
            },
            {
                "from_user": 9,
            },
            {
                "from_user": 49,
            },
        ]
        square_roots, ax = task_func(data)
        np.testing.assert_array_equal(square_roots, np.array([11.0, 13.0, 15.0, 3.0, 7.0]))
    def test_case_5(self):
        # Input 5: List with 1 dictionary with the 'from_user' key.
        data = [{"from_user": 7, "bye": 4}]
        square_roots, ax = task_func(data)
        np.testing.assert_array_equal(square_roots, np.array([2.65]))

Constants:

Instruction:
Write a function called `def task_func(result):` to: Plots the square root function for values associated with the key 'from_user' from the input list of dictionaries. Annotates the graph with the current date and time. - Round each square root value to 2 decimals. Constants: - PLOT_TITLE: Title of the plot (default is 'Square root plot'). - X_LABEL: Label for the x-axis (default is 'x'). - Y_LABEL: Label for the y-axis (default is 'sqrt(x)'). - TIME_FORMAT: Format for displaying the current date and time (default is '%Y-%m-%d %H:%M:%S').
The function should output with:
    numpy.ndarray: list of square values associated with the key 'from_user' from the input list of dictionaries.
    matplotlib.axes.Axes: plot of square root values.
You should start with:
```
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
# Constants
PLOT_TITLE = 'Square root plot'
X_LABEL = 'x'
Y_LABEL = 'sqrt(x)'
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
def task_func(result):
```


Prompt:
import random
import matplotlib.pyplot as plt
import seaborn as sns

def task_func(result, colors=['b', 'g', 'r', 'c', 'm', 'y', 'k']):
    """
    Draws a histogram of the "from_user" values in the provided result. The color of the histogram bars is selected at random from the provided colors list.

    Parameters:
    result (list): A list of dictionaries containing the key "from_user".
    colors (list, optional): A list of colors to choose from for the histogram bars. Defaults is ['b', 'g', 'r', 'c', 'm', 'y', 'k'].

    Returns:
    None: The function displays the histogram and does not return any value.

    Requirements:
    - random
    - matplotlib
    - seaborn

    Example:
    >>> result = [{"from_user": 0}, {"from_user": 0}, {"from_user": 1}]
    >>> task_func(result)
    """

    from_user_values = [d['from_user'] for d in result if 'from_user' in d]
    color = random.choice(colors)
    plt.figure()
    sns.histplot(from_user_values, color=color)
    plt.show()

import unittest
from unittest.mock import patch
class TestCases(unittest.TestCase):
    """Test cases for the task_func function."""
    def test_case_1(self):
        random.seed(42)
        result = [
            {"from_user": 0},
            {"from_user": 0},
            {"from_user": 1}
        ]
        with patch("matplotlib.pyplot.show") as mocked_show:
            task_func(result)
            mocked_show.assert_called_once()
    def test_case_2(self):
        random.seed(42)
        result = []
        with patch("matplotlib.pyplot.show") as mocked_show:
            task_func(result)
            mocked_show.assert_called_once()
    def test_case_3(self):
        random.seed(42)
        result = [
            {"hello": 0},
            {"world": 1}
        ]
        with patch("matplotlib.pyplot.show") as mocked_show:
            task_func(result)
            mocked_show.assert_called_once()
    def test_case_4(self):
        random.seed(42)
        result = [
            {"from_user": 0},
            {"from_user": 1},
            {"from_user": 2}
        ]
        colors = ["orange", "purple"]
        with patch("matplotlib.pyplot.show") as mocked_show, patch("random.choice", return_value="orange") as mocked_choice:
            task_func(result, colors)
            mocked_choice.assert_called_with(colors)
            mocked_show.assert_called_once()
    def test_case_5(self):
        random.seed(42)
        result = [
            {
                "hello": 0,
                "from_user": 1,
            },
            {
                "world": 1,
                "from_user": 1
            },
            {
                "love": 1,
                "from_user": 1
            }
        ]
        with patch("matplotlib.pyplot.show") as mocked_show:
            task_func(result)
            mocked_show.assert_called_once()

Instruction:
Write a function called `def task_func(result, colors=['b', 'g', 'r', 'c', 'm', 'y', 'k']):` to: Draws a histogram of the "from_user" values in the provided result. The color of the histogram bars is selected at random from the provided colors list.
The function should output with:
    None: The function displays the histogram and does not return any value.
You should start with:
```
import random
import matplotlib.pyplot as plt
import seaborn as sns
def task_func(result, colors=['b', 'g', 'r', 'c', 'm', 'y', 'k']):
```