cabbage972/GitChameleon-2.0 huggingface dataset:
Library: flask==3.0.0 (Python 3.10, released 2023-09)

Problem: 
Complete the app_set_up function that set-up the app in such manner that the json encoding returns a sorted list
 when called with the eval function provided with the variable 
 num_set being a set of numbers, use other libraries if needed. Do not run the app in your code.

Starting code:
import flask

app = flask.Flask('test')
@app.route('/data')
def data(num_set):
    return flask.jsonify({'numbers':num_set})

def eval(app, data_fn, num_set):
    with app.test_request_context():
        response = data_fn(num_set)
        return response.get_data(as_text=True)

def app_set_up(app: flask.Flask) -> None: 
    

Solution:

    class MyCustomJSONHandler(flask.json.provider.DefaultJSONProvider):
        def default(self, obj):
            if isinstance(obj, set):
                return sorted(list(obj))
            return super().default(obj)
    app.json_provider_class = MyCustomJSONHandler
    app.json = app.json_provider_class(app)


Test:

import json
app_set_up(app)
app2 = flask.Flask('test2')
@app2.route('/data2')
def data2(num_set):
    return flask.jsonify({'numbers': num_set})
class MyCustomJSONHandler2(flask.json.provider.DefaultJSONProvider):
    def default(self, obj):
        if isinstance(obj, set):
            return sorted(list(obj))
        return super().default(obj)
app2.json_provider_class = MyCustomJSONHandler2
app2.json = app2.json_provider_class(app2)

assertion_result = eval(app2, data2, {3, 1, 2, 6, 5, 4}) == eval(app, data, {3, 1, 2, 6, 5, 4})
assert assertion_result
Library: flask==2.0.0 (Python 3.10, released 2021-05)
Additional dependencies: werkzeug==2.0.0

Problem: 
Complete the download definition to download the data in the variable attachment_filename. Do not run the app in your code.

Starting code:
from flask import Flask, send_file
from io import BytesIO

app1 = Flask(__name__)

def get_content_disp(app, download_fn):
    with app.test_request_context():
        response = download_fn()
    content_disp = response.headers.get('Content-Disposition')
    return content_disp

@app1.route('/download')
def download():
    data = BytesIO(b'Hello, World!')
    attachment_filename = 'hello.txt'
    return send_file(data, as_attachment=True,


Solution:
attachment_filename=attachment_filename)


Test:

content_disp = get_content_disp(app1, download)
assertion_result = 'filename=hello.txt' in content_disp
assert assertion_result
Library: flask==3.0.0 (Python 3.10, released 2023-09)

Problem: 
Complete the download definition to download the data in the variable attachment_filename. Do not run the app in your code.

Starting code:
from flask import Flask, send_file
from io import BytesIO

app1 = Flask(__name__)

def get_content_disp(app, download_fn):
    with app.test_request_context():
        response = download_fn()
    content_disp = response.headers.get('Content-Disposition')
    return content_disp

@app1.route('/download')
def download():
    data = BytesIO(b'Hello, World!')
    attachment_filename = 'hello.txt'
    return send_file(data, as_attachment=True,



Solution:
download_name=attachment_filename)


Test:

content_disp = get_content_disp(app1, download)
assertion_result = 'filename=hello.txt' in content_disp
assert assertion_result
Library: flask==2.0.1 (Python 3.10, released 2021-05)
Additional dependencies: werkzeug==2.0.0

Problem: 
Implement the function to load the JSON file to config the Flask app. Do not run the app in your code.

Starting code:
import json
import tempfile
from flask import Flask

config_data = {'DEBUG': True, 'SECRET_KEY': 'secret'}
with tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.json') as tmp:
    json.dump(config_data, tmp)
    tmp.flush()
    config_file = tmp.name

app = Flask(__name__)

def load_config(config_file: str) -> None:
    

Solution:
    app.config.from_json(config_file)


Test:
load_config(config_file)
assertion_result= app.config['DEBUG'] is True and app.config['SECRET_KEY'] == 'secret'
assert assertion_result
Library: flask==3.0.0 (Python 3.10, released 2023-09)

Problem: 
Load the json file to config the Flask app. Do not run the app in your code.

Starting code:
import json
import tempfile
from flask import Flask

config_data = {'DEBUG': True, 'SECRET_KEY': 'secret'}
with tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.json') as tmp:
    json.dump(config_data, tmp)
    tmp.flush()
    config_file = tmp.name

app = Flask(__name__)

def load_config(config_file: str) -> None:
    

Solution:
    app.config.from_file(config_file, load=json.load)


Test:
load_config(config_file)
assertion_result= app.config['DEBUG'] is True and app.config['SECRET_KEY'] == 'secret'
assert assertion_result
Library: flask==2.0.1 (Python 3.10, released 2021-05)
Additional dependencies: werkzeug==2.0.0

Problem: 
Complete the safe_join_fail_404 to safely join the path and the subpath, use other libraries if needed. Do not run the app in your code.

Starting code:
import flask
import werkzeug

error404 = werkzeug.exceptions.NotFound

def safe_join_fail_404(base_path: str, sub_path: str) -> str:
    # Attempt to join the base path and sub path.
    # If the joined path is outside the base path, raise a 404 error.


Solution:

    joined = flask.safe_join(base_path, sub_path)

    return joined


Test:

base_path = '/var/www/myapp'
sub_path = '../secret.txt'

try : 
    joined = safe_join_fail_404(base_path, sub_path)
except werkzeug.exceptions.NotFound as e:
    assertion_result = True
else:
    assertion_result = False
assert assertion_result

base_path = '/var/www/myapp'
sub_path = 'secret.txt'
joined = safe_join_fail_404(base_path, sub_path)
assertion_result = joined == '/var/www/myapp/secret.txt'
assert assertion_result
Library: flask==3.0.0 (Python 3.10, released 2023-09)

Problem: 
Complete the safe_join_fail_404 to safely join the path and the subpath, use other libraries if needed. Do not run the app in your code.

Starting code:
import flask
import werkzeug

error404 = werkzeug.exceptions.NotFound

def safe_join_fail_404(base_path: str, sub_path: str) -> str:
    # Attempt to join the base path and sub path.
    # If the joined path is outside the base path, raise a 404 error.


Solution:

    joined = werkzeug.utils.safe_join(base_path, sub_path)
    if joined is None:
        raise error404
    return joined


Test:

base_path = '/var/www/myapp'
sub_path = '../secret.txt'

try : 
    joined = safe_join_fail_404(base_path, sub_path)
except werkzeug.exceptions.NotFound as e:
    assertion_result = True
else:
    assertion_result = False
assert assertion_result

base_path = '/var/www/myapp'
sub_path = 'secret.txt'
joined = safe_join_fail_404(base_path, sub_path)
assertion_result = joined == '/var/www/myapp/secret.txt'
assert assertion_result
Library: flask==2.0.1 (Python 3.10, released 2021-05)
Additional dependencies: werkzeug==2.0.0

Problem: 
Complete the function convert_timedelta_to_seconds, use other libraries if needed. Do not run the app in your code.

Starting code:
import flask
import datetime

def convert_timedelta_to_seconds(td: datetime.timedelta) -> int:
    

Solution:

    return flask.helpers.total_seconds(td)


Test:

import datetime
td = datetime.timedelta(hours=2, minutes=30,microseconds=1)
assertion_results = convert_timedelta_to_seconds(td)==9000
assert assertion_results
Library: flask==3.0.0 (Python 3.10, released 2023-09)

Problem: 
Complete the function convert_timedelta_to_seconds, use other libraries if needed. Do not run the app in your code.

Starting code:
import flask
import datetime

def convert_timedelta_to_seconds(td: datetime.timedelta):


Solution:

    return td.total_seconds()


Test:

import datetime
td = datetime.timedelta(hours=2, minutes=30,microseconds=1)
assertion_results = convert_timedelta_to_seconds(td)==9000.000001
assert assertion_results
Library: jinja2==2.11 (Python 3.10, released 2020-01)
Additional dependencies: markupsafe==2.0.1

Problem: 
Implement the solution function to return a custom filter. This filter should: 
accept the context and a parameter name, 
retrieve a variable prefix from the context (defaulting to 'Hello' if not provided), 
return a greeting message combining the prefix and the name. Do not run the app in your code.

Starting code:
import jinja2 
from jinja2.runtime import Context
from typing import Callable

def setup_environment(filtername: str, filter: Callable[[Context, str], str]) -> jinja2.Environment:
    env = jinja2.Environment()
    env.filters[filtername] = filter
    return env

def solution() -> Callable[[Context, str], str]:


Solution:
    @jinja2.contextfilter
    def greet(ctx, name):
        prefix = ctx.get('prefix', 'Hello')
        return f'{prefix}, {name}!'
        
    return greet

Test:
greet = solution()
env = setup_environment('greet',greet)
template = env.from_string('''
{{ 'World'| greet }}''')
assertion_results = 'Hi, World!' in template.render(prefix='Hi')
assert assertion_results 
assertion_results = 'Hello, World!' in template.render()
assert assertion_results
Library: jinja2==3.1 (Python 3.10, released 2022-03)

Problem: 
Implement the solution function to return a custom filter. This filter should: 
accept the context and a parameter name, 
retrieve a variable prefix from the context (defaulting to 'Hello' if not provided), 
return a greeting message combining the prefix and the name.. Do not run the app in your code.

Starting code:
import jinja2 
from jinja2.runtime import Context
from typing import Callable

def setup_environment(filtername: str,filter) -> jinja2.Environment:
    env = jinja2.Environment()
    env.filters[filtername] = filter
    return env

def solution() -> Callable[[Context, str], str]:


Solution:
    @jinja2.pass_context
    def greet(ctx, name):
        prefix = ctx.get('prefix', 'Hello')
        return f'{prefix}, {name}!'
        
    return greet

Test:
greet = solution()
env = setup_environment('greet',greet)
template = env.from_string('''
{{ 'World'| greet }}''')
assertion_results = 'Hi, World!' in template.render(prefix='Hi')
assert assertion_results 
assertion_results = 'Hello, World!' in template.render()
assert assertion_results
Library: jinja2==2.11 (Python 3.10, released 2020-01)
Additional dependencies: markupsafe==2.0.1

Problem: 
Implement the nl2br function which is a custom filter that takes the evaluation context 
and a text value, then replaces every occurrence of the substring 'Hello' 
with the HTML string '<br>Hello</br>', while respecting the autoescape setting.
You can use the nl2br_core function. Do not run the app in your code.

Starting code:
import re
from jinja2 import Environment, evalcontextfilter
from markupsafe import Markup, escape
from jinja2.runtime import Context
from typing import Callable

def get_output(env, filter_fn):
    env.filters['nl2br'] = filter_fn
    template = env.from_string('{{ text | nl2br }}')
    output = template.render(text='Hello World')
    return output

def nl2br_core(eval_ctx, value):
    br = '<br>Hello</br>'
    if eval_ctx.autoescape:
        value = escape(value)
        br = Markup(br)
    result = re.sub(r'Hello', br, value)
    return Markup(result) if eval_ctx.autoescape else result

def solution() -> Callable[[Context, str], str]:


Solution:
    @evalcontextfilter
    def nl2br(eval_ctx, value):
        return nl2br_core(eval_ctx, value)

    return nl2br


Test:
nl2br = solution()
env = Environment(autoescape=True)
output = get_output(env,nl2br)
expected = '<br>Hello</br> World'

assert output == expected
Library: jinja2==3.1 (Python 3.10, released 2022-03)

Problem: 
Write the nl2br function which is a custom filter that takes the evaluation context 
and a text value, then replaces every occurrence of the substring 'Hello' 
with the HTML string '<br>Hello</br>', while respecting the autoescape setting.
You can use the nl2br_core function. Do not run the app in your code.

Starting code:
import re
from jinja2 import Environment, pass_eval_context
from markupsafe import Markup, escape
from typing import Callable, Union
from jinja2.runtime import EvalContext

def get_output(env, filter_fn):
    env.filters['nl2br'] = filter_fn
    template = env.from_string('{{ text | nl2br }}')
    output = template.render(text='Hello World')
    return output

def nl2br_core(eval_ctx, value):
    br = '<br>Hello</br>'
    if eval_ctx.autoescape:
        value = escape(value)
        br = Markup(br)
    result = re.sub(r'Hello', br, value)
    return Markup(result) if eval_ctx.autoescape else result

def solution() -> Callable[[EvalContext, str], Markup | str]:

Solution:

    @pass_eval_context
    def nl2br(eval_ctx, value):
        return nl2br_core(eval_ctx, value)
    
    return nl2br

Test:

nl2br_filter = solution()

env = Environment(autoescape=True)
output = get_output(env,nl2br_filter)
expected = '<br>Hello</br> World'

assert output == expected
Library: scipy==1.11.1 (Python 3.10, released 2023-06)
Additional dependencies: numpy==1.25.1

Problem: 
complete the following function that check if all the batch of matrices are invertible, using numpy 1.25.1.

Starting code:
import warnings
from scipy.linalg import det
import numpy as np
warnings.filterwarnings('error')

def check_invertibility(matrices: np.ndarray) -> np.bool_:

Solution:

    return np.all(det(matrices))


Test:

matrices = np.array([
    [[1, 2],
     [3, 4]],
    
    [[0, 1],
     [1, 0]],
    
    [[2, 0],
     [0, 2]]
])
assertion_value = check_invertibility(matrices)
assert assertion_value
matrices = np.array([
    [[1, 2],
     [3, 4]],
    
    [[0, 1],
     [1, 0]],
    
    [[2, 0],
     [0, 2]],

    [[0, 0],
     [0, 0]]
])
assertion_value = not check_invertibility(matrices)
assert assertion_value
Library: scipy==1.9.1 (Python 3.10, released 2022-10)
Additional dependencies: numpy==1.21.6

Problem: 
complete the following function that check if all the batch of matrices are invertible, using numpy 1.21.6

Starting code:
import warnings
from scipy.linalg import det
import numpy as np
warnings.filterwarnings('error')

def check_invertibility(matrices : np.ndarray) -> np.bool_ :

Solution:

    return np.alltrue([det(A) for A in matrices])


Test:

matrices = np.array([
    [[1, 2],
     [3, 4]],
    
    [[0, 1],
     [1, 0]],
    
    [[2, 0],
     [0, 2]]
])
assertion_value = check_invertibility(matrices)
assert assertion_value
matrices = np.array([
    [[1, 2],
     [3, 4]],
    
    [[0, 1],
     [1, 0]],
    
    [[2, 0],
     [0, 2]],

    [[0, 0],
     [0, 0]]
])
assertion_value = not check_invertibility(matrices)
assert assertion_value
Library: scipy==1.11.1 (Python 3.10, released 2023-06)
Additional dependencies: numpy==1.25.1

Problem: 
Complete the function count_unique_hmean that takes a 2D numpy array as 
input and returns the number of unique harmonic mean values across 
the rows of the array, counting each nan value as unique. We are using numpy 1.25.1

Starting code:
import numpy as np
from scipy.stats import hmean

def count_unique_hmean(data: np.ndarray) -> int:
    # data shape: (n, m)
    # n: number of arrays
    # m: number of elements in each array 

Solution:

    hmean_values = hmean(np.asarray(data), axis=1)
    unique_vals = np.unique(hmean_values, equal_nan=False).shape[0]
    return unique_vals



Test:

data = np.array([
    [1, 2, 3],
    [2, 2, 2],
    [1, np.nan, 3],
    [4, 5, 6],
    [np.nan, 1, np.nan],
    [1, 2, 3]
])
assertion_value = count_unique_hmean(data) == 5
assert assertion_value
Library: scipy==1.8.1 (Python 3.10, released 2022-05)
Additional dependencies: numpy==1.21.6

Problem: 
Complete the function count_unique_hmean that takes a 2D numpy array as 
input and returns the number of unique harmonic mean values across 
the rows of the array, counting each nan value as unique. We are using numpy 1.21.6

Starting code:
import numpy as np
from scipy.stats import hmean

def count_unique_hmean(data: np.ndarray) -> int:
    # data shape: (n, m)
    # n: number of arrays
    # m: number of elements in each array 

Solution:

    hmean_values = []
    for arr in data:
        if np.isnan(arr).any():
            hm = np.nan
        else:
            hm = hmean(arr)
        hmean_values.append(hm)
    
    hmean_values = np.asarray(hmean_values)
    non_nan_vals = hmean_values[~np.isnan(hmean_values)]
    counts_non_nan = np.unique(non_nan_vals).shape[0]
    nan_count = np.sum(np.isnan(hmean_values))
    return counts_non_nan + nan_count


Test:


data = np.array([
    [1, 2, 3],
    [2, 2, 2],
    [1, np.nan, 3],
    [4, 5, 6],
    [np.nan, 1, np.nan],
    [1, 2, 3]
])
assertion_value = count_unique_hmean(data) == 5
assert assertion_value
Library: scipy==1.11.1 (Python 3.10, released 2023-06)
Additional dependencies: numpy==1.25.1

Problem: 
Complete the function compute_hilbert_transform. We are using numpy 1.25.1

Starting code:
import numpy as np
from scipy.signal import hilbert

def compute_hilbert_transform(a, b, dtype=np.float64):
    # compute_hilbert_transform should return the Hilbert transform of the
    # a and b arrays stacked vertically, with safe casting and the specified
    # dtype. 
    # raise TypeError if needed
    

Solution:

    stacked = np.vstack((a, b), dtype=dtype,
                         casting='safe')
    return hilbert(stacked)


Test:


a = np.array([1.0, 2.0, 3.0], dtype=np.float32)
b = np.array([4.0, 5.0, 6.0], dtype=np.float64)
assertion_value = False
try :
    compute_hilbert_transform(a, b, dtype=np.float32)
except TypeError:
    assertion_value = True
assert assertion_value
b=b.astype(np.float32)
computed = compute_hilbert_transform(a, b, dtype=np.float32)
expected = hilbert(np.vstack([a.astype(np.float64), b.astype(np.float64)])).astype(dtype=np.complex64)
assertion_value = np.allclose(computed, expected) & (computed.dtype == np.complex64)
assert assertion_value
a=a.astype(np.float64)
b=b.astype(np.float64)
computed = compute_hilbert_transform(a, b, dtype=np.float64)
expected = expected.astype(dtype=np.complex128)
assertion_value = np.allclose(computed, expected) & (computed.dtype == np.complex128)
assert assertion_value
Library: scipy==1.8.1 (Python 3.10, released 2022-05)
Additional dependencies: numpy==1.21.6

Problem: 
Complete the function compute_hilbert_transform. We are using numpy 1.25.1

Starting code:
import numpy as np
from scipy.signal import hilbert

def compute_hilbert_transform(a: np.ndarray, b: np.ndarray, dtype=np.float64) -> np.ndarray:
    # compute_hilbert_transform should return the Hilbert transform of the
    # a and b arrays stacked vertically, with safe casting and the specified
    # dtype.
    # raise TypeError if needed
    

Solution:

    if not (np.can_cast(a.dtype, dtype, casting='safe') and np.can_cast(b.dtype, dtype, casting='safe')):
        raise TypeError('Unsafe casting from input dtype to specified dtype')
    
    a_cast = a.astype(dtype, copy=False)
    b_cast = b.astype(dtype, copy=False)
    
    stacked = np.vstack((a_cast, b_cast))
    
    result = hilbert(stacked)
    
    if dtype == np.float32:
        complex_dtype = np.complex64
    elif dtype == np.float64:
        complex_dtype = np.complex128
    else:
        complex_dtype = np.complex128

    return result.astype(complex_dtype)
    

Test:

a = np.array([1.0, 2.0, 3.0], dtype=np.float32)
b = np.array([4.0, 5.0, 6.0], dtype=np.float64)
assertion_value = False
try :
    compute_hilbert_transform(a, b, dtype=np.float32)
except TypeError:
    assertion_value = True
assert assertion_value
b=b.astype(np.float32)
computed = compute_hilbert_transform(a, b, dtype=np.float32)
expected = hilbert(np.vstack([a.astype(np.float64), b.astype(np.float64)])).astype(dtype=np.complex64)
assertion_value = np.allclose(computed, expected) & (computed.dtype == np.complex64)
assert assertion_value

a=a.astype(np.float64)
b=b.astype(np.float64)
computed = compute_hilbert_transform(a, b, dtype=np.float64)
expected = expected.astype(dtype=np.complex128)
assertion_value = np.allclose(computed, expected) & (computed.dtype == np.complex128)
assert assertion_value
Library: flask==2.0.0 (Python 3.10, released 2021-05)
Additional dependencies: numpy==1.21.6 werkzeug==2.0.0

Problem:  
Complete the app set-up for the json encoding to return only the unique values (each NaN being a different value) contained 
in the numpy array when called, we are using numpy 1.21.6. Do not run the app in your code.

Starting code:
import flask
import json
import numpy as np
app = flask.Flask('test1')
@app.route('/data')
def data(num_arr):
    return flask.jsonify({'numbers': num_arr})

def eval(app, data_fn, num_arr):
    with app.test_request_context():
        response = data_fn(num_arr)
        return response.get_data(as_text=False)

class MyCustomJSONHandler(json.JSONEncoder):
    def default(self, obj: object) -> object:
        if isinstance(obj, np.ndarray):

Solution:

            n_nan = np.sum(np.isnan(obj))
            unique_vals = obj[~np.isnan(obj)]
            unique_vals = np.append(np.unique(unique_vals), [np.nan]*n_nan).tolist()
            return unique_vals
        return super().default(obj)

app.json_encoder = MyCustomJSONHandler


Test:

app2 = flask.Flask('test2')
@app2.route('/data2')
def data2(num_arr):
    return flask.jsonify({'numbers': num_arr})
class MyCustomJSONHandler2(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            n_nan = np.sum(np.isnan(obj))
            unique_vals = obj[~np.isnan(obj)]
            unique_vals = np.append(np.unique(unique_vals), [np.nan]*n_nan).tolist()
            return unique_vals
        return super().default(obj)

app2.json_encoder = MyCustomJSONHandler2
assertion_results = eval(app2, data2,np.array([3, 3, 1, np.nan, 2, 6, 5, np.nan])) == eval(app, data,np.array([3, 3, 1, np.nan, 2, 6, 5, np.nan]))
assert assertion_results
Library: flask==3.0.0 (Python 3.10, released 2023-09)
Additional dependencies: numpy==1.25.1

Problem:  
Complete the app set-up for the json encoding to return only the unique values (each NaN being a different value) contained 
in the numpy array when called, we are using numpy 1.25.1. Do not run the app in your code.

Starting code:
import flask
import numpy as np

app = flask.Flask('test1')

@app.route('/data')
def data(num_arr):
    return flask.jsonify({'numbers': num_arr})

def eval_app(app, data_fn, num_arr):
    with app.test_request_context():
        response = data_fn(num_arr)
        return response.get_data(as_text=True)

class MyCustomJSONHandler(flask.json.provider.DefaultJSONProvider):
    def default(self, obj: object) -> object:
    

Solution:

        if isinstance(obj, np.ndarray):
            unique_vals = np.unique(obj, equal_nan=False)
            return unique_vals.tolist()
        return super().default(obj)

app.json_provider_class = MyCustomJSONHandler
app.json = app.json_provider_class(app)


Test:

app2 = flask.Flask('test2')

@app2.route('/data2')
def data2(num_arr):
    return flask.jsonify({'numbers': num_arr})

class MyCustomJSONHandler2(flask.json.provider.DefaultJSONProvider):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            n_nan = np.sum(np.isnan(obj))
            unique_vals = obj[~np.isnan(obj)]
            unique_vals = np.append(np.unique(unique_vals), [np.nan]*n_nan).tolist()
            return unique_vals
        return super().default(obj)

app2.json_provider_class = MyCustomJSONHandler2
app2.json = app2.json_provider_class(app2)

assertion_results = eval_app(app2, data2,np.array([3, 3, 1, np.nan, 2, 6, 5, np.nan])) == eval_app(app, data,np.array([3, 3, 1, np.nan, 2, 6, 5, np.nan]))
assert assertion_results