ronantakizawa/codereview-bench huggingface dataset:
Repository: Avaiga/taipy
File: doc/gui/examples/controls/menu_inactive.py (Python)

Code before:
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# -----------------------------------------------------------------------------------------
# To execute this script, make sure that the taipy-gui package is installed in your
# Python environment and run:
#     python <script>
# -----------------------------------------------------------------------------------------
from taipy.gui import Gui

lov = [("id1", "Menu option 1"), ("id2", "Menu option 2"), ("id3", "Menu option 3"), ("id4", "Menu option 4")]


md = """
<|menu|lov={lov}|active=False|>
"""

if __name__ == "__main__":
    Gui(md).run()


Review comment (suggestion):
```suggestion
<|menu|lov={options}|not active|>
```

Code after:
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# -----------------------------------------------------------------------------------------
# To execute this script, make sure that the taipy-gui package is installed in your
# Python environment and run:
#     python <script>
# -----------------------------------------------------------------------------------------
from taipy.gui import Gui

options = [("a", "Option A"), ("b", "Option B"), ("c", "Option C"), ("d", "Option D")]


page = """
<|menu|lov={options}|not active|>
"""

if __name__ == "__main__":
    Gui(page).run(title="Menu - Inactive")
Repository: Avaiga/taipy
File: doc/gui/examples/controls/menu_simple.py (Python)

Code before:
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# -----------------------------------------------------------------------------------------
# To execute this script, make sure that the taipy-gui package is installed in your
# Python environment and run:
#     python <script>
# -----------------------------------------------------------------------------------------
from taipy.gui import Gui

lov = [("id1", "Menu option 1"), ("id2", "Menu option 2"), ("id3", "Menu option 3"), ("id4", "Menu option 4")]


md = """
<|menu|lov={lov}|>
"""

if __name__ == "__main__":
    Gui(md).run()


Review comment (suggestion):
```suggestion
options = [("a", "Option A"), ("b", "Option B"), ("c", "Option C"), ("d", "Option D")]
```

Code after:
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# -----------------------------------------------------------------------------------------
# To execute this script, make sure that the taipy-gui package is installed in your
# Python environment and run:
#     python <script>
# -----------------------------------------------------------------------------------------
from taipy.gui import Gui

options = [("a", "Option A"), ("b", "Option B"), ("c", "Option C"), ("d", "Option D")]


page = """
<|menu|lov={options}|>
"""

if __name__ == "__main__":
    Gui(page).run(title="Menu - Simple")
Repository: Avaiga/taipy
File: doc/gui/examples/controls/menu_simple.py (Python)

Code before:
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# -----------------------------------------------------------------------------------------
# To execute this script, make sure that the taipy-gui package is installed in your
# Python environment and run:
#     python <script>
# -----------------------------------------------------------------------------------------
from taipy.gui import Gui

lov = [("id1", "Menu option 1"), ("id2", "Menu option 2"), ("id3", "Menu option 3"), ("id4", "Menu option 4")]


md = """
<|menu|lov={lov}|>
"""

if __name__ == "__main__":
    Gui(md).run()


Review comment (suggestion):
```suggestion
    Gui(page).run(title="Menu - Simple")
```

Code after:
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# -----------------------------------------------------------------------------------------
# To execute this script, make sure that the taipy-gui package is installed in your
# Python environment and run:
#     python <script>
# -----------------------------------------------------------------------------------------
from taipy.gui import Gui

options = [("a", "Option A"), ("b", "Option B"), ("c", "Option C"), ("d", "Option D")]


page = """
<|menu|lov={options}|>
"""

if __name__ == "__main__":
    Gui(page).run(title="Menu - Simple")
Repository: Avaiga/taipy
File: frontend/taipy-gui/src/components/Taipy/Alert.tsx (TypeScript)

Code before:
    const faviconUrl = useMemo(() => {
        const nodeList = document.getElementsByTagName("link");
        for (let i = 0; i < nodeList.length; i++) {
            if (nodeList[i].getAttribute("rel") == "icon" || nodeList[i].getAttribute("rel") == "shortcut icon") {
                return nodeList[i].getAttribute("href") || "/favicon.png";
            }
        }
        return "/favicon.png";
    }, []);

    useEffect(() => {
        if (alert) {
            if (alert.atype === "") {
                if (lastKey.current) {
                    closeSnackbar(lastKey.current);
                    lastKey.current = "";
                }
            } else {
                lastKey.current = enqueueSnackbar(alert.message, {
                    variant: alert.atype as VariantType,
                    action: notifAction,
                    autoHideDuration: alert.duration,
                });
                alert.system && new Notification(document.title || "Taipy", { body: alert.message, icon: faviconUrl });
            }
            dispatch(createDeleteAlertAction(alert.notification_id));
        }
    }, [alert, enqueueSnackbar, closeSnackbar, notifAction, faviconUrl, dispatch]);

    useEffect(() => {
        alert?.system && window.Notification && Notification.requestPermission();
    }, [alert?.system]);

    return null;
};

export default Alert;


Review comment (suggestion):
- on creation (type != ""), you need to pass the id as a key to `enqueueSnackbar` options
- on deletion, you need to use that id as an argument to  `closeSnackbar`
- I guess we don't need the lastKey ref anymore

Code after:
    const faviconUrl = useMemo(() => {
        const nodeList = document.getElementsByTagName("link");
        for (let i = 0; i < nodeList.length; i++) {
            if (nodeList[i].getAttribute("rel") == "icon" || nodeList[i].getAttribute("rel") == "shortcut icon") {
                return nodeList[i].getAttribute("href") || "/favicon.png";
            }
        }
        return "/favicon.png";
    }, []);

    useEffect(() => {
        if (alert) {
            const notificationId = nanoid(); 
            if (alert.atype === "") {
                closeSnackbar(notificationId);  
            } else {
                enqueueSnackbar(alert.message, {
                    variant: alert.atype as VariantType,
                    action: notifAction,  
                    autoHideDuration: alert.duration,
                    key: notificationId,  
                });
                alert.system && new Notification(document.title || "Taipy", { body: alert.message, icon: faviconUrl });
            }
            dispatch(createDeleteAlertAction(notificationId));
        }
    }, [alert, enqueueSnackbar, closeSnackbar, notifAction, faviconUrl, dispatch]);
    useEffect(() => {
        alert?.system && window.Notification && Notification.requestPermission();
    }, [alert?.system]);

    return null;
};

export default Alert;
Repository: Avaiga/taipy
File: frontend/taipy-gui/src/context/taipyReducers.ts (TypeScript)

Code before:

export interface AlertMessage {
    atype: string;
    message: string;
    system: boolean;
    duration: number;
    notification_id: string;
}

interface TaipyAction extends NamePayload, TaipyBaseAction {
    propagate?: boolean;
    context?: string;
}

interface TaipyMultipleAction extends TaipyBaseAction {
    payload: NamePayload[];
}

interface TaipyMultipleMessageAction extends TaipyBaseAction {
    actions: TaipyBaseAction[];
}

interface TaipyAlertAction extends TaipyBaseAction, AlertMessage {}

interface TaipyDeleteAlertAction extends TaipyBaseAction {
    notification_id: string;
}

export const BLOCK_CLOSE = { action: "", message: "", close: true, noCancel: false } as BlockMessage;

export interface BlockMessage {
    action: string;
    noCancel: boolean;
    close: boolean;
    message: string;
}

interface TaipyBlockAction extends TaipyBaseAction, BlockMessage {}

export interface NavigateMessage {
    to?: string;
    params?: Record<string, string>;
    tab?: string;
    force?: boolean;
}

interface TaipyNavigateAction extends TaipyBaseAction, NavigateMessage {}

export interface FileDownloadProps {
    content?: string;
    name?: string;

Review comment (suggestion):
I would even say:
```suggestion
    notification_id?: string;
```
Unidentified notifications cannot be revoked specifically.

Code after:
}

export interface AlertMessage {
    atype: string;
    message: string;
    system: boolean;
    duration: number;
    notificationId?: string;
}

interface TaipyAction extends NamePayload, TaipyBaseAction {
    propagate?: boolean;
    context?: string;
}

interface TaipyMultipleAction extends TaipyBaseAction {
    payload: NamePayload[];
}

interface TaipyMultipleMessageAction extends TaipyBaseAction {
    actions: TaipyBaseAction[];
}

interface TaipyAlertAction extends TaipyBaseAction, AlertMessage {}

interface TaipyDeleteAlertAction extends TaipyBaseAction {
    notificationId: string;
}

export const BLOCK_CLOSE = { action: "", message: "", close: true, noCancel: false } as BlockMessage;

export interface BlockMessage {
    action: string;
    noCancel: boolean;
    close: boolean;
    message: string;
}

interface TaipyBlockAction extends TaipyBaseAction, BlockMessage {}

export interface NavigateMessage {
    to?: string;
    params?: Record<string, string>;
    tab?: string;
    force?: boolean;
}

interface TaipyNavigateAction extends TaipyBaseAction, NavigateMessage {}

export interface FileDownloadProps {
    content?: string;
Repository: Avaiga/taipy
File: frontend/taipy-gui/src/context/taipyReducers.ts (TypeScript)

Code before:
    navigateTab?: string;
    navigateForce?: boolean;
    id: string;
    menu: MenuProps;
    download?: FileDownloadProps;
    ackList: string[];
}

/**
 * Application actions as used by the application reducer.
 */
export interface TaipyBaseAction {
    type: Types;
}

export interface NamePayload {
    name: string;
    payload: Record<string, unknown>;
}

export interface AlertMessage {
    atype: string;
    message: string;
    system: boolean;
    duration: number;
    notification_id: string;
}

interface TaipyAction extends NamePayload, TaipyBaseAction {
    propagate?: boolean;
    context?: string;
}

interface TaipyMultipleAction extends TaipyBaseAction {
    payload: NamePayload[];
}

interface TaipyMultipleMessageAction extends TaipyBaseAction {
    actions: TaipyBaseAction[];
}

interface TaipyAlertAction extends TaipyBaseAction, AlertMessage {}

interface TaipyDeleteAlertAction extends TaipyBaseAction {
    notification_id: string;
}

export const BLOCK_CLOSE = { action: "", message: "", close: true, noCancel: false } as BlockMessage;

export interface BlockMessage {
    action: string;

Review comment (suggestion):
```suggestion
    notification_id?: string;
```
See below

Code after:
    navigateParams?: Record<string, string>;
    navigateTab?: string;
    navigateForce?: boolean;
    id: string;
    menu: MenuProps;
    download?: FileDownloadProps;
    ackList: string[];
}

/**
 * Application actions as used by the application reducer.
 */
export interface TaipyBaseAction {
    type: Types;
}

export interface NamePayload {
    name: string;
    payload: Record<string, unknown>;
}

export interface AlertMessage {
    atype: string;
    message: string;
    system: boolean;
    duration: number;
    notificationId?: string;
}

interface TaipyAction extends NamePayload, TaipyBaseAction {
    propagate?: boolean;
    context?: string;
}

interface TaipyMultipleAction extends TaipyBaseAction {
    payload: NamePayload[];
}

interface TaipyMultipleMessageAction extends TaipyBaseAction {
    actions: TaipyBaseAction[];
}

interface TaipyAlertAction extends TaipyBaseAction, AlertMessage {}

interface TaipyDeleteAlertAction extends TaipyBaseAction {
    notificationId: string;
}

export const BLOCK_CLOSE = { action: "", message: "", close: true, noCancel: false } as BlockMessage;

export interface BlockMessage {
Repository: Avaiga/taipy
File: taipy/gui/utils/callable.py (Python)

Code before:
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.

import typing as t
from inspect import isclass
from types import LambdaType


def _is_function_like(s: t.Any) -> bool:
    return callable(s) and not isclass(s)


def _get_function_like_name(s: t.Any) -> str:
    if hasattr(s, "__name__"):
        return s.__name__
    elif callable(s):
        return f"<instance of {type(s).__name__}>"
    else:
        return str(s)


def _is_unnamed_function(s: t.Any):
    return isinstance(s, LambdaType) or (callable(s) and not hasattr(s, "__name__"))


Review comment (suggestion):
```suggestion
def _get_function_name(s: t.Any) -> str:
```
or even `_function_name()` 

Code after:
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.

import typing as t
from inspect import isclass
from types import LambdaType


def _is_function(s: t.Any) -> bool:
    return callable(s) and not isclass(s)


def _function_name(s: t.Any) -> str:
    if hasattr(s, "__name__"):
        return s.__name__
    elif callable(s):
        return f"<instance of {type(s).__name__}>"
    else:
        return str(s)


def _is_unnamed_function(s: t.Any):
    return isinstance(s, LambdaType) or (callable(s) and not hasattr(s, "__name__"))
Repository: Avaiga/taipy
File: doc/gui/examples/controls/column_name_styling.py (Python)

Code before:
# Example for column name styling

from taipy.gui import Gui
import pandas as pd

# Sample data in DataFrame format
df = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 35],
    "Occupation": ["Engineer", "Doctor", "Artist"]
})

# Define column properties
columns = [
    {"field": "Name", "header": "Name", "header_style": "color: blue; font-weight: bold;"},
    {"field": "Age", "header": "Age", "header_style": "color: blue; font-weight: bold;"},
    {"field": "Occupation", "header": "Occupation", "header_style": "color: blue; font-weight: bold;"}
]

# Page content with table and header styling
page = """
<|table|data={df}|columns={columns}|>
"""

if __name__ == "__main__":
    Gui(page).run(title="Column Name Styling Example")

Review comment (suggestion):
with columns names showing spaces or transformed characters:

```py
df = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 35],
    "Occupation or Job": ["Engineer", "Doctor", "Artist"]
})
```

you can define style at the page level like this :
```py
page = Markdown("""4
<|table|data={df}|columns={columns}|>
""", style={".taipy-table-name": {"color": "blue"}, ".taipy-table-occupation-or-job": {"color": "green"}})
```

Code after:
# Example for column name styling for header

import pandas as pd

from taipy.gui import Gui, Markdown

# Sample data in DataFrame format
df = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 35],
    "Job or Occupation": ["Engineer", "Doctor", "Artist"]
})


# Page content with table and header styling
page = Markdown("""
<|table|data={df}|columns={columns}|>
""", style={".taipy-table-name": {"color": "blue"}, ".taipy-table-job-or-occupation": {"color": "green"}})

if __name__ == "__main__":
    Gui(page).run(title="Column Name Styling Example")
Repository: Avaiga/taipy
File: tests/gui/data/test_accessors.py (Python)

Code before:

    def to_csv(self, var_name: str, value: t.Any) -> t.Optional[str]:
        pass


def mock_taipy_data(value):
    """Helper to mock _TaipyData objects."""
    mock_data = Mock(spec=_TaipyData)
    mock_data.get.return_value = value
    return mock_data


def test_custom_accessor(gui: Gui):
    """Test if get_data() uses the correct accessor."""
    data_accessors = _DataAccessors(gui)
    data = mock_taipy_data(123)

    # Testing when accessor is not registered
    data_accessor = data_accessors._DataAccessors__get_instance(mock_taipy_data)  # type: ignore
    assert isinstance(
        data_accessor, _InvalidDataAccessor
    ), f"Expected _InvalidDataAccessor but got {type(data_accessor)}"
    result = data_accessors.get_data("var_name", data, {})
    assert result == {}

    # Testing when accessor is not registered
    data_accessors._register(MyDataAccessor)

    result = data_accessors.get_data("var_name", data, {})
    assert isinstance(result, dict)
    assert result["value"] == 246

    data_accessors._unregister(MyDataAccessor)


Review comment (suggestion):
```suggestion
    # Testing when accessor is registered
```

Code after:

    def to_csv(self, var_name: str, value: t.Any) -> t.Optional[str]:
        pass


def mock_taipy_data(value):
    """Helper to mock _TaipyData objects."""
    mock_data = Mock(spec=_TaipyData)
    mock_data.get.return_value = value
    return mock_data


def test_custom_accessor(gui: Gui):
    """Test if get_data() uses the correct accessor."""
    data_accessors = _DataAccessors(gui)
    data = mock_taipy_data(123)

    # Testing when accessor is not registered
    data_accessor = data_accessors._DataAccessors__get_instance(mock_taipy_data)  # type: ignore
    assert isinstance(
        data_accessor, _InvalidDataAccessor
    ), f"Expected _InvalidDataAccessor but got {type(data_accessor)}"
    result = data_accessors.get_data("var_name", data, {})
    assert result == {}

    # Testing when accessor is registered
    data_accessors._register(MyDataAccessor)

    result = data_accessors.get_data("var_name", data, {})
    assert isinstance(result, dict)
    assert result["value"] == 246

    data_accessors._unregister(MyDataAccessor)