cabbage972/GitChameleon-2.0 huggingface dataset:
Library: seaborn==0.13.0 (Python 3.10, released 2023-09)
Additional dependencies: pandas==2.0.0 numpy==1.26.4

Problem: Write a custom_pointplot function that visualizes x and y from a Pandas DataFrame, with remove connecting lines

Starting code:
import seaborn as sns
import pandas as pd
from matplotlib.axes import Axes

def custom_pointplot(data: pd.DataFrame) -> Axes:
    return 

Solution:
sns.pointplot(x='x', y='y', data=data, markers="o", linestyles="none")

Test:
data = pd.DataFrame({'x': [1, 2, 3, 4], 'y': [10, 15, 13, 17]})

import warnings
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    
    output = custom_pointplot(data)
    
    warning_messages = [word for warn in w for word in str(warn.message).strip().lower().split()]

    if any("dataframegroupby.apply" in msg for msg in warning_messages):
        pass  
    elif any("deprecated" in msg and "removed" in msg for msg in warning_messages):
        raise AssertionError("Expected deprecation warning was not raised.")

    for line in output.lines:
        
        if line.get_linestyle() != "None":
            raise AssertionError("Linestyle is not set to 'none' as expected.")
        break
Library: seaborn==0.13.0 (Python 3.10, released 2023-09)
Additional dependencies: pandas==2.0.0 numpy==1.26.4

Problem: Write a custom_pointplot function that visualizes x and y from a Pandas DataFrame, adjust error bar width to 2.

Starting code:
import seaborn as sns
import pandas as pd
from matplotlib.axes import Axes

def custom_pointplot(data: pd.DataFrame) -> Axes:
    return 

Solution:
sns.pointplot(x='x', y='y', data=data, err_kws={"linewidth": 2})

Test:
data = pd.DataFrame({'x': [1, 2, 3, 4], 'y': [10, 15, 13, 17]})

import warnings
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    
    output = custom_pointplot(data)
    
    warning_messages = [word for warn in w for word in str(warn.message).strip().lower().split()]

    if any("dataframegroupby.apply" in msg for msg in warning_messages):
        pass  
    elif any("deprecated" in msg and "removed" in msg for msg in warning_messages):
        raise AssertionError("Expected deprecation warning was not raised.")
    
    found_correct_linewidth = False
    for line in output.lines: 
        linewidth = line.get_linewidth()
        if linewidth == 2:
            found_correct_linewidth = True
            break

    if not found_correct_linewidth:
        raise AssertionError("Error bar linewidth is not set to 2 as expected.")
Library: seaborn==0.13.0 (Python 3.10, released 2023-09)
Additional dependencies: pandas==2.0.0 numpy==1.26.4

Problem: Write a custom_violinplot function that visualizes x and y from a Pandas DataFrame, scales the bandwidth to 1.5.

Starting code:
import seaborn as sns
import pandas as pd
from matplotlib.axes import Axes

def custom_violinplot(data: pd.DataFrame) -> Axes:
    return 

Solution:
sns.violinplot(x='x', y='y', data=data, bw_adjust=1.5)

Test:
data = pd.DataFrame({'x': ['A', 'B', 'C'], 'y': [5, 10, 15]})
import warnings

with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    
    output = custom_violinplot(data)
    
    warning_messages = [str(warn.message).strip().lower() for warn in w]
    if any("bw" in msg and "deprecated" in msg for msg in warning_messages):
        raise AssertionError("bw parameter should not be used. Use bw_method and bw_adjust instead.")

    for collection in output.collections:
            if hasattr(collection, "get_paths"):
                assertion_value = sns.violinplot.__defaults__[0] == 1.5
                assert assertion_value
Library: seaborn==0.13.0 (Python 3.10, released 2023-09)
Additional dependencies: pandas==2.0.0 numpy==1.26.4

Problem: Write a custom_violinplot function that visualizes x and y from a Pandas DataFrame, choose bandwidth to scott.

Starting code:
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.axes import Axes

def custom_violinplot(data: pd.DataFrame) -> Axes:
    return 

Solution:
sns.violinplot(x='x', y='y', data=data, bw_method="scott")

Test:
data = pd.DataFrame({'x': ['A', 'B', 'C'], 'y': [5, 10, 15]})

import warnings

with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    
    output = custom_violinplot(data)
    
    warning_messages = [str(warn.message).strip().lower() for warn in w]
    if any("bw" in msg and "deprecated" in msg for msg in warning_messages):
        raise AssertionError("bw parameter should not be used. Use bw_method and bw_adjust instead.")
    
    collections = [c for c in output.collections if isinstance(c, plt.Line2D)]  # Extract violin plot lines
    
    assertion_value = output is not None
    assert assertion_value
Library: seaborn==0.13.0 (Python 3.10, released 2023-09)
Additional dependencies: pandas==2.0.0 numpy==1.26.4

Problem: Write a custom_barplot function that visualizes x and y from a Pandas DataFrame, adjust error bar with color red and linewidth 2.

Starting code:
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.axes import Axes


def custom_barplot(data: pd.DataFrame) -> Axes:
    return 

Solution:
sns.barplot(x='x', y='y', data=data, err_kws={'color': 'red', 'linewidth': 2})

Test:
data = pd.DataFrame({'x': ['A', 'B', 'C'], 'y': [5, 10, 15]})
import warnings
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    
    ax = custom_barplot(data)
    
    warning_messages = [str(warn.message).strip().lower() for warn in w]
    if any("errcolor" in msg or "errwidth" in msg for msg in warning_messages):
        raise AssertionError("errcolor and errwidth should not be used. Use err_kws instead.")

    for line in ax.lines:
        if line.get_linewidth() == 2 and line.get_color() == 'red':
            break
    else:
        raise AssertionError("Error bars are not set with err_kws correctly.")
Library: seaborn==0.13.0 (Python 3.10, released 2023-09)
Additional dependencies: pandas==2.0.0 numpy==1.26.4

Problem: Write a custom_boxenplot function that visualizes x and y from a Pandas DataFrame, make width method to exponential.

Starting code:
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.axes import Axes


def custom_boxenplot(data: pd.DataFrame) -> Axes:
    return 

Solution:
sns.boxenplot(x='x', y='y', data=data, width_method='exponential')

Test:

import warnings

data = pd.DataFrame({'x': ['A', 'B', 'C'], 'y': [5, 10, 15]})

with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    
    output = custom_boxenplot(data)

    warning_messages = [str(warn.message).strip().lower() for warn in w]
    if any("scale" in msg and "deprecated" in msg for msg in warning_messages):
        raise AssertionError("scale should not be used in boxenplot. Use width_method instead.")

    for artist in output.get_children():
        if hasattr(artist, "get_linestyle") and artist.get_linestyle() in ["-", "--"]:
            break
    else:
        raise AssertionError("Boxen elements are missing, width_method might not be applied.")
Library: seaborn==0.12.0 (Python 3.10, released 2022-09)
Additional dependencies: pandas==1.4.0 numpy==1.26.4

Problem: Write a custom function that visualizes x and y from a Pandas DataFrame, set the X label to be "My X Label" and Y label to be "My Y Label".

Starting code:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.axes import Axes


def custom_set_axis_labels(data: pd.DataFrame) -> Axes:
    ax = sns.scatterplot(x='x', y='y', data=data)
    ax.

Solution:
set(xlabel="My X Label", ylabel="My Y Label")
    return ax

Test:
data = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})

ax = custom_set_axis_labels(data)
x_expect = "My X Label"
y_expect = "My Y Label"
assert ax.get_xlabel() == x_expect and ax.get_ylabel() == y_expect, (
    "Axis labels not set correctly using ax.set()."
)
Library: seaborn==0.12.0 (Python 3.10, released 2022-09)
Additional dependencies: scipy==1.8.0

Problem: Write a custom function to compute iqr for input data. If needed, use another library.

Starting code:
import numpy as np


def custom_iqr(data: np.ndarray) -> float:
    from 

Solution:
scipy.stats import iqr
    return iqr(data)


Test:
data_array = np.array([1, 2, 3, 4, 5])

computed_iqr = custom_iqr(data_array)
expect = 2
assert computed_iqr == expect
Library: mitmproxy==9.0.1 (Python 3.10, released 2022-11)

Problem: Write a custom function named custom_client that create a client connection by specifying the IP address (ip_address), the input port (i_port), the output port (o_port), and the timestamp (using time.time() for the current time). Store the resulting client connection in the variable output_client.

Starting code:
import time
import mitmproxy.connection as conn

def custom_client(ip_address: str, i_port: int, o_port: int) -> conn.Client:
    return 

Solution:
 conn.Client(
    peername=(ip_address, i_port),
    sockname=(ip_address, o_port),
    timestamp_start=time.time()
)

Test:
ip_address = "127.0.0.1"
i_port = 111
o_port = 222
output_client = custom_client(ip_address, i_port, o_port)

expect_peername = ("127.0.0.1", 111)
expect_sockname = ("127.0.0.1", 222)

assert output_client.peername == expect_peername
assert output_client.sockname == expect_sockname
Library: mitmproxy==9.0.1 (Python 3.10, released 2022-11)

Problem: Write a custom function named custom_server that create a server connection with the given parameters: an IP address (ip_address), a server port (server_port), and store the resulting instance in the variable output_server. 

Starting code:
import mitmproxy.connection as conn

def custom_server(ip_address: str, server_port: int) -> conn.Server:
    return 

Solution:
conn.Server(address=(ip_address, server_port))

Test:
ip_address = "192.168.1.1"
server_port = 80
output_server = custom_server(ip_address, server_port)
expect = ("192.168.1.1", 80)
assert output_server.address == expect
Library: mitmproxy==7.0.0 (Python 3.10, released 2021-07)

Problem: Using mitmproxy’s connection API, create a Python class named ConnectionLogger that implements a server connected event hook. When a server connection is established, your implementation should define a method that is automatically called with a parameter named server_conn. This parameter represents the connection object, and your method must print the server’s local address by accessing server_conn.sockname. The printed output should follow the exact format: Server connected with local address {server_conn.sockname}. You must not modify the provided start code, which already includes the definitions for DummyServerConn and an empty ConnectionLogger class. Instead, complete the solution by dynamically adding the required method in the solution() function.

Starting code:
import contextlib

class DummyServerConn:
    def __init__(self, sockname):
        self.sockname = sockname

class ConnectionLogger:
    pass
        

def solution() -> None:
    def 

Solution:
 server_connected(self, server_conn: DummyServerConn) -> None:
        print(server_conn.sockname)

    ConnectionLogger.server_connected = server_connected

Test:
    
import unittest
import io

class TestConnectionLogger(unittest.TestCase):
    def test_server_connected(self):
        # Update the ConnectionLogger class with the new method.
        solution()
        logger = ConnectionLogger()
        dummy_conn = DummyServerConn(('127.0.0.1', 8080))
        
        output = io.StringIO()
        with contextlib.redirect_stdout(output):
            logger.server_connected(dummy_conn)
        print(output.getvalue())
        expect = "('127.0.0.1', 8080)"
        
        self.assertIn(expect, output.getvalue())
        
unittest.main()
Library: mitmproxy==7.0.0 (Python 3.10, released 2021-07)

Problem: Using mitmproxy’s connection API, create a Python class named ConnectionLogger that implements a server connect event hook. When a server connection is established, your implementation should define a method that is automatically called with a parameter named server_conn. This parameter represents the connection object, and your method must print the server’s local address by accessing server_conn.sockname. The printed output should follow the exact format: Server connect to local address {server_conn.sockname}. You must not modify the provided start code, which already includes the definitions for DummyServerConn and an empty ConnectionLogger class. Instead, complete the solution by dynamically adding the required method in the solution() function.

Starting code:
import contextlib

class DummyServerConn:
    def __init__(self, sockname):
        self.sockname = sockname

class ConnectionLogger:
    pass
        

def solution() -> None:
    def 

Solution:
 server_connect(self, server_conn: DummyServerConn) -> None:
        print(server_conn.sockname)

    ConnectionLogger.server_connect = server_connect


Test:

import unittest
import io
class TestConnectionLogger(unittest.TestCase):
    def test_server_connect(self):
        logger = ConnectionLogger()
        solution()
        dummy_conn = DummyServerConn(('127.0.0.1', 8080))
        
        output = io.StringIO()
        with contextlib.redirect_stdout(output):
            logger.server_connect(dummy_conn)
            
        expect = "('127.0.0.1', 8080)"
        
        self.assertIn(expect, output.getvalue())
        
unittest.main()
Library: mitmproxy==7.0.0 (Python 3.10, released 2021-07)

Problem: Using mitmproxy’s connection API, create a Python class named ConnectionLogger that implements a server disconnected event hook. When a server connection is established, your implementation should define a method that is automatically called with a parameter named server_conn. This parameter represents the connection object, and your method must print the server’s local address by accessing server_conn.sockname. The printed output should follow the exact format: Server disconnected with local address {server_conn.sockname}. You must not modify the provided start code, which already includes the definitions for DummyServerConn and an empty ConnectionLogger class. Instead, complete the solution by dynamically adding the required method in the solution() function.

Starting code:
import contextlib

class DummyServerConn:
    def __init__(self, sockname):
        self.sockname = sockname

class ConnectionLogger:
    pass
        

def solution() -> None:
    def 

Solution:
server_disconnected(self, server_conn: DummyServerConn) -> None:
        print(server_conn.sockname)

    ConnectionLogger.server_disconnected = server_disconnected

Test:

import unittest
import io
class TestConnectionLogger(unittest.TestCase):
    def test_server_disconnected(self):
        logger = ConnectionLogger()
        solution()
        dummy_conn = DummyServerConn(('127.0.0.1', 8080))
        
        output = io.StringIO()
        with contextlib.redirect_stdout(output):
            logger.server_disconnected(dummy_conn)
            
        expect = "('127.0.0.1', 8080)"
        
        self.assertIn(expect, output.getvalue())
        
unittest.main()
Library: mitmproxy==7.0.0 (Python 3.10, released 2021-07)

Problem: Using mitmproxy’s connection API, create a Python class named ConnectionLogger that implements a client connected event hook. When a client connection is established, your implementation should define a method that is automatically called with a parameter named client_conn. This parameter represents the connection object, and your method must print the client's local address by accessing client_conn.peername. The printed output should follow the exact format: Client connected: {client_conn.peername}. You must not modify the provided start code, which already includes the definitions for DummyServerConn and an empty ConnectionLogger class. Instead, complete the solution by dynamically adding the required method in the solution() function.

Starting code:
import contextlib

class DummyClientConn:
    def __init__(self, peername):
        self.peername = peername

class ConnectionLogger:
    pass

def solution() -> None:
    def 

Solution:
client_connected(self, client_conn: DummyClientConn) -> None:
        print(client_conn.peername)

    ConnectionLogger.client_connected = client_connected

Test:
    
import unittest
import io
class TestConnectionLogger(unittest.TestCase):
    def test_client_connected(self):
        logger = ConnectionLogger()
        solution()
        dummy_conn = DummyClientConn(('127.0.0.1', 8080))
        
        output = io.StringIO()
        with contextlib.redirect_stdout(output):
            logger.client_connected(dummy_conn)
            
        expect = "('127.0.0.1', 8080)"
        
        self.assertIn(expect, output.getvalue())
        
unittest.main()
Library: mitmproxy==7.0.0 (Python 3.10, released 2021-07)

Problem: Using mitmproxy’s connection API, create a Python class named `ConnectionLogger` that implements the client disconnected event hook. When a client connection is terminated, your implementation should define a method that is automatically called with a parameter named `client_conn`. This parameter represents the connection object, and your method must print the client's local address by accessing `client_conn.peername`. The printed output should follow the exact format: `Client disconnected: {client_conn.peername}`. You must not modify the provided start code, which already includes the definitions for `DummyServerConn` and an empty `ConnectionLogger` class. Instead, complete the solution by dynamically adding the required method in the `solution()` function.

Starting code:
import contextlib

class DummyClientConn:
    def __init__(self, peername):
        self.peername = peername

class ConnectionLogger:
    pass

def solution() -> None:
    def 

Solution:
client_disconnected(self, client_conn) -> None:
        print(client_conn.peername)
        
    ConnectionLogger.client_disconnected = client_disconnected

Test:
        
import unittest
import io
class TestConnectionLogger(unittest.TestCase):
    def test_client_disconnected(self):
        logger = ConnectionLogger()
        solution()
        dummy_conn = DummyClientConn(('127.0.0.1', 8080))
        
        output = io.StringIO()
        with contextlib.redirect_stdout(output):
            logger.client_disconnected(dummy_conn)
            
        expect = "('127.0.0.1', 8080)"
        
        self.assertIn(expect, output.getvalue())
        
unittest.main()
Library: mitmproxy==7.0.0 (Python 3.10, released 2021-07)

Problem: Mitmproxy triggers a logging event that passes a log entry object containing a message in its msg attribute. Using mitmproxy’s logging API, create a Python class named MyAddon that implements a log event handler. When a logging event occurs, your implementation should define a method that is automatically called with a parameter named entry. This parameter represents the log entry object, and your method must print the log message by accessing entry.msg using f-string formatting. The printed output should match exactly what is contained in entry.msg. You must not modify the provided start code, which already includes the definitions for DummyLogEntry and an empty MyAddon class. Instead, complete the solution by dynamically adding the required method in the solution() function. Provide the complete code for the MyAddon class.


Starting code:
import contextlib

class DummyLogEntry:
    def __init__(self, msg):
        self.msg = msg

class MyAddon:
    pass

def solution() -> None:
    def 

Solution:
add_log(self, entry):
        print(f"{entry.msg}")
    
    MyAddon.add_log = add_log

Test:
    
import unittest
import io
class TestMyAddonLogging(unittest.TestCase):
    def test_logging_event(self):
        addon = MyAddon()
        solution()
        dummy_entry = DummyLogEntry("Test log message")
        
        output = io.StringIO()
        with contextlib.redirect_stdout(output):
            addon.add_log(dummy_entry)
        print(output.getvalue())
        expect = "Test log message"
        self.assertIn(expect, output.getvalue())

unittest.main()
Library: mitmproxy==7.0.0 (Python 3.10, released 2021-07)

Problem: Complete the implementation of the generate_cert_new function so that it obtains a certificate object by calling the correct method on the CA, and returns a tuple containing the certificate PEM and key PEM.

Starting code:
import types

class DummyCert:
    def __init__(self, hostname):
        self.cert_pem = f"Dummy certificate for {hostname}"
        self.key_pem = f"Dummy key for {hostname}"

class DummyCA:
    def __init__(self, path):
        self.path = path

    def get_cert(self, hostname):
        return DummyCert(hostname)

certs = types.ModuleType("certs")
certs.CA = DummyCA

def generate_cert_new(hostname: str) -> tuple[str, str]:

    ca = certs.CA("dummy/path")
    cert_obj = 

Solution:
ca.get_cert(hostname)
    return cert_obj.cert_pem, cert_obj.key_pem

Test:
def test_generate_cert_new():
    hostname = "example.com"
    cert_pem, key_pem = generate_cert_new(hostname)
    assertion_value = hostname in cert_pem
    assert assertion_value
    assertion_value = cert_pem.strip() != ""
    assert assertion_value
    assertion_value = key_pem.strip() != ""
    assert assertion_value

test_generate_cert_new()
Library: mitmproxy==7.0.0 (Python 3.10, released 2021-07)

Problem: Update the code by writing the correct import statement for the Headers class from mitmproxy.http. Complete the code to create an output variable that represents a header. The header object takes header_name and initial_value as inputs.

Starting code:
from mitmproxy.http import Headers

def custom_function(header_name: bytes, initial_value: bytes) -> Headers:
    return 

Solution:
Headers([(header_name, initial_value)])

Test:

header_name = b"Content-Type"
initial_value = b"text/html"

expect = "text/html"
results = custom_function(header_name, initial_value)
assert results.get(header_name) == expect
Library: pytest==7.0.0 (Python 3.10, released 2022-02)

Problem: Update the code by writing the correct import statement for the hook implementation decorator from the testing framework. Then, complete the code to define a hook implementation function named pytest_runtest_call that uses this decorator with its execution priority parameter set to false; the function body should contain only the pass statement.

Starting code:
import pytest

@pytest.

Solution:
hookimpl(tryfirst=False)
def pytest_runtest_call():
    pass

Test:
import pluggy

def test_hookimpl_configuration_with_plugin_manager():
    pm = pluggy.PluginManager("pytest")
    
    class DummyPlugin:
        pytest_runtest_call = pytest_runtest_call

    plugin = DummyPlugin()
    pm.register(plugin)
    
    hookimpls = pm.hook.pytest_runtest_call.get_hookimpls()
    
    for impl in hookimpls:
        if impl.plugin is plugin:
            opts = impl.opts 
            assert opts.get("tryfirst") is False
            break
    else:
        pytest.fail("pytest_runtest_call implementation not found in plugin manager.")



test_hookimpl_configuration_with_plugin_manager()