ronantakizawa/codereview-bench huggingface dataset:
Repository: CodeEditApp/CodeEdit
File: CodeEdit/Features/Search/Views/QuickSearchResultLabel.swift (Swift)

Code before:
//
//  QuickSearchResultLabel.swift
//  CodeEdit
//
//  Copyright © 2024-present Paul Ebose. All rights reserved.
//

import SwiftUI

/// Implementation of command palette entity. While swiftui does not allow to use NSMutableAttributeStrings,
/// the only way to fallback to UIKit and have NSViewRepresentable to be a bridge between UIKit and SwiftUI.
/// Highlights currently entered text query

struct QuickSearchResultLabel: NSViewRepresentable {

    var labelName: String
    var textToMatch: String

    public func makeNSView(context: Context) -> some NSTextField {
        let label = NSTextField(wrappingLabelWithString: labelName)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.drawsBackground = false
        label.textColor = .labelColor
        label.isEditable = false
        label.isSelectable = false
        label.font = .labelFont(ofSize: 13)
        label.allowsDefaultTighteningForTruncation = false
        label.cell?.truncatesLastVisibleLine = true
        label.cell?.wraps = true
        label.maximumNumberOfLines = 1

Review comment (suggestion):
Due to the license of the project, we cannot include copyrighted code. Can we ask you resubmit a new implementation or a version without the notice? It needs to replace this commit entirely otherwise it will still be in the commit history.

Code after:
//
//  QuickSearchResultLabel.swift
//  CodeEdit
//
//  Created by Paul Ebose on 2024/7/2.
//

import SwiftUI

/// Implementation of command palette entity. While swiftui does not allow to use NSMutableAttributeStrings,
/// the only way to fallback to UIKit and have NSViewRepresentable to be a bridge between UIKit and SwiftUI.
/// Highlights currently entered text query
struct QuickSearchResultLabel: NSViewRepresentable {
    let labelName: String
    let charactersToHighlight: [NSRange]
    var nsLabelName: NSAttributedString?

    public func makeNSView(context: Context) -> some NSTextField {
        let label = NSTextField(wrappingLabelWithString: labelName)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.drawsBackground = false
        label.textColor = .labelColor
        label.isEditable = false
        label.isSelectable = false
        label.font = .labelFont(ofSize: 13)
        label.allowsDefaultTighteningForTruncation = false
        label.cell?.truncatesLastVisibleLine = true
        label.cell?.wraps = true
        label.maximumNumberOfLines = 1
        label.attributedStringValue = nsLabelName ?? highlight()
Repository: CodeEditApp/CodeEdit
File: CodeEdit/Features/Search/Views/QuickSearchResultLabel.swift (Swift)

Code before:
        let label = NSTextField(wrappingLabelWithString: labelName)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.drawsBackground = false
        label.textColor = .labelColor
        label.isEditable = false
        label.isSelectable = false
        label.font = .labelFont(ofSize: 13)
        label.allowsDefaultTighteningForTruncation = false
        label.cell?.truncatesLastVisibleLine = true
        label.cell?.wraps = true
        label.maximumNumberOfLines = 1
        label.attributedStringValue = nsLabelName ?? highlight()
        return label
    }

    func highlight() -> NSAttributedString {
        let attribText = NSMutableAttributedString(string: self.labelName)
        for range in charactersToHighlight {
            attribText.addAttribute(.foregroundColor, value: NSColor(Color(.labelColor)), range: range)
            attribText.addAttribute(.font, value: NSFont.boldSystemFont(ofSize: NSFont.systemFontSize), range: range)
        }
        return attribText
    }

    func updateNSView(_ nsView: NSViewType, context: Context) {
        nsView.textColor = nsLabelName == nil && charactersToHighlight.isEmpty ? .labelColor : .secondaryLabelColor
        nsView.attributedStringValue = nsLabelName ?? highlight()
    }
}


Review comment (suggestion):
```suggestion
        nsView.textColor = if nsLabelName == nil && charactersToHighlight.isEmpty {
            .controlTextColor
        } else {
            .secondaryLabelColor
        }
```

Code after:
        let label = NSTextField(wrappingLabelWithString: labelName)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.drawsBackground = false
        label.textColor = .labelColor
        label.isEditable = false
        label.isSelectable = false
        label.font = .labelFont(ofSize: 13)
        label.allowsDefaultTighteningForTruncation = false
        label.cell?.truncatesLastVisibleLine = true
        label.cell?.wraps = true
        label.maximumNumberOfLines = 1
        label.attributedStringValue = nsLabelName ?? highlight()
        return label
    }

    func highlight() -> NSAttributedString {
        let attribText = NSMutableAttributedString(string: self.labelName)
        for range in charactersToHighlight {
            attribText.addAttribute(.foregroundColor, value: NSColor.controlTextColor, range: range)
            attribText.addAttribute(.font, value: NSFont.boldSystemFont(ofSize: NSFont.systemFontSize), range: range)
        }
        return attribText
    }

    func updateNSView(_ nsView: NSViewType, context: Context) {
        nsView.textColor = if nsLabelName == nil && charactersToHighlight.isEmpty {
            .controlTextColor
        } else {
            .secondaryLabelColor
        }
        nsView.attributedStringValue = nsLabelName ?? highlight()
    }
}
Repository: CodeEditApp/CodeEdit
File: CodeEdit/Features/Documents/Controllers/CodeEditWindowController.swift (Swift)

Code before:
//
//  CodeEditWindowController.swift
//  CodeEdit
//
//  Created by Pavel Kasila on 18.03.22.
//

import Cocoa
import SwiftUI
import Combine

final class CodeEditWindowController: NSWindowController, NSToolbarDelegate, ObservableObject, NSWindowDelegate {
    @Published var navigatorCollapsed = false
    @Published var inspectorCollapsed = false
    @Published var toolbarCollapsed = false

    private var modalOpen = false

    var observers: [NSKeyValueObservation] = []

    var workspace: WorkspaceDocument?
    var workspaceSettingsWindow: NSWindow?
    var quickOpenPanel: SearchPanel?
    var commandPalettePanel: SearchPanel?
    var navigatorSidebarViewModel: NavigatorSidebarViewModel?

    internal var cancellables = [AnyCancellable]()

    var splitViewController: CodeEditSplitViewController? {
        contentViewController as? CodeEditSplitViewController
    }

    init(
        window: NSWindow?,
        workspace: WorkspaceDocument?
    ) {
        super.init(window: window)
        window?.delegate = self
        guard let workspace else { return }
        self.workspace = workspace
        guard let splitViewController = setupSplitView(with: workspace) else {
            fatalError("Failed to set up content view.")

Review comment (suggestion):
You might call this "panelOpen".

```suggestion
    private var panelOpen = false
```

Code after:
//
//  CodeEditWindowController.swift
//  CodeEdit
//
//  Created by Pavel Kasila on 18.03.22.
//

import Cocoa
import SwiftUI
import Combine

final class CodeEditWindowController: NSWindowController, NSToolbarDelegate, ObservableObject, NSWindowDelegate {
    @Published var navigatorCollapsed = false
    @Published var inspectorCollapsed = false
    @Published var toolbarCollapsed = false

    private var panelOpen = false

    var observers: [NSKeyValueObservation] = []

    var workspace: WorkspaceDocument?
    var workspaceSettingsWindow: NSWindow?
    var quickOpenPanel: SearchPanel?
    var commandPalettePanel: SearchPanel?
    var navigatorSidebarViewModel: NavigatorSidebarViewModel?

    internal var cancellables = [AnyCancellable]()

    var splitViewController: CodeEditSplitViewController? {
        contentViewController as? CodeEditSplitViewController
    }

    init(
        window: NSWindow?,
        workspace: WorkspaceDocument?
    ) {
        super.init(window: window)
        window?.delegate = self
        guard let workspace else { return }
        self.workspace = workspace
        guard let splitViewController = setupSplitView(with: workspace) else {
            fatalError("Failed to set up content view.")
Repository: CodeEditApp/CodeEdit
File: CodeEdit/AppDelegate.swift (Swift)

Code before:

    /// Terminates running language servers. Used during app termination to ensure resources are freed.
    private func terminateLanguageServers() {
        Task {
            await withTaskGroup(of: Void.self) { group in
                await lspService.languageClients.forEach { (key, value) in
                    group.addTask {
                        do {
                            try await value.shutdown()
                        } catch {
                            self.logger.error("Shutting down \(key.languageId.rawValue): Error \(error)")
                        }
                    }
                }
            }
            await MainActor.run {
                NSApplication.shared.reply(toApplicationShouldTerminate: true)
            }
        }
    }

    /// Terminates all running tasks. Used during app termination to ensure resources are freed.
    private func terminateTasks() {
        let documents = CodeEditDocumentController.shared.documents.compactMap({ $0 as? WorkspaceDocument })
        documents.forEach { workspace in
            workspace.taskManager?.terminateActiveTask()
        }
    }

    /// Setup all the services into a ServiceContainer for the application to use.
    @MainActor
    private func setupServiceContainer() {
        ServiceContainer.register(
            LSPService()
        )
    }
}

extension AppDelegate {
    static let recoverWorkspacesKey = "recover.workspaces"
}


Review comment (suggestion):
All tasks should be terminated, not just the active one. `stopAllTasks()` currently sends a `SIGINT`, but we should consider sending a `SIGTERM`.
```suggestion
            workspace.taskManager?.stopAllTasks()
```

Code after:

    /// Terminates running language servers. Used during app termination to ensure resources are freed.
    private func terminateLanguageServers() {
        Task {
            await lspService.stopAllServers()
            await MainActor.run {
                NSApplication.shared.reply(toApplicationShouldTerminate: true)
            }
        }
    }

    /// Terminates all running tasks. Used during app termination to ensure resources are freed.
    private func terminateTasks() {
        let documents = CodeEditDocumentController.shared.documents.compactMap({ $0 as? WorkspaceDocument })
        documents.forEach { workspace in
            workspace.taskManager?.stopAllTasks()
        }
    }

    /// Setup all the services into a ServiceContainer for the application to use.
    @MainActor
    private func setupServiceContainer() {
        ServiceContainer.register(
            LSPService()
        )
    }
}

extension AppDelegate {
    static let recoverWorkspacesKey = "recover.workspaces"
}
Repository: CodeEditApp/CodeEdit
File: CodeEdit/Features/Documents/WorkspaceDocument/WorkspaceDocument.swift (Swift)

Code before:
//
//  WorkspaceDocument.swift
//  CodeEdit
//
//  Created by Pavel Kasila on 17.03.22.
//

import AppKit
import SwiftUI
import Combine
import Foundation
import LanguageServerProtocol

@objc(WorkspaceDocument)
final class WorkspaceDocument: NSDocument, ObservableObject, NSToolbarDelegate {
    @Published var sortFoldersOnTop: Bool = true
    @Published var filter: String = ""

    private var workspaceState: [String: Any] {
        get {
            let key = "workspaceState-\(self.fileURL?.absoluteString ?? "")"
            return UserDefaults.standard.object(forKey: key) as? [String: Any] ?? [:]
        }
        set {
            let key = "workspaceState-\(self.fileURL?.absoluteString ?? "")"
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }

    var workspaceFileManager: CEWorkspaceFileManager?

    var editorManager: EditorManager? = EditorManager()
    var statusBarViewModel: StatusBarViewModel? = StatusBarViewModel()
    var utilityAreaModel: UtilityAreaViewModel? = UtilityAreaViewModel()
    var searchState: SearchState?
    var openQuicklyViewModel: OpenQuicklyViewModel?
    var commandsPaletteState: QuickActionsViewModel?
    var listenerModel: WorkspaceNotificationModel = .init()
    var sourceControlManager: SourceControlManager?

    var taskManager: TaskManager?
    var workspaceSettingsManager: CEWorkspaceSettings?

Review comment (suggestion):
This should be renamed to something a little more descriptive. Maybe `fileFilter`? Also a doc comment here explaining that this is for the project navigator would make this okay.

Code after:
//
//  WorkspaceDocument.swift
//  CodeEdit
//
//  Created by Pavel Kasila on 17.03.22.
//

import AppKit
import SwiftUI
import Combine
import Foundation
import LanguageServerProtocol

@objc(WorkspaceDocument)
final class WorkspaceDocument: NSDocument, ObservableObject, NSToolbarDelegate {
    @Published var sortFoldersOnTop: Bool = true
    /// A string used to filter the displayed files and folders in the project navigator area based on user input.
    @Published var navigatorFilter: String = ""

    private var workspaceState: [String: Any] {
        get {
            let key = "workspaceState-\(self.fileURL?.absoluteString ?? "")"
            return UserDefaults.standard.object(forKey: key) as? [String: Any] ?? [:]
        }
        set {
            let key = "workspaceState-\(self.fileURL?.absoluteString ?? "")"
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }

    var workspaceFileManager: CEWorkspaceFileManager?

    var editorManager: EditorManager? = EditorManager()
    var statusBarViewModel: StatusBarViewModel? = StatusBarViewModel()
    var utilityAreaModel: UtilityAreaViewModel? = UtilityAreaViewModel()
    var searchState: SearchState?
    var openQuicklyViewModel: OpenQuicklyViewModel?
    var commandsPaletteState: QuickActionsViewModel?
    var listenerModel: WorkspaceNotificationModel = .init()
    var sourceControlManager: SourceControlManager?

    var taskManager: TaskManager?
Repository: CodeEditApp/CodeEdit
File: CodeEdit/Features/NavigatorArea/OutlineView/StandardTableViewCell.swift (Swift)

Code before:
//
//  StandardTableViewCell.swift
//  CodeEdit
//
//  Created by TAY KAI QUAN on 17/8/22.
//

import SwiftUI

class StandardTableViewCell: NSTableCellView {

    weak var secondaryLabel: NSTextField?
    var workspace: WorkspaceDocument?

    var secondaryLabelRightAligned: Bool = true {
        didSet {
            resizeSubviews(withOldSize: .zero)
        }
    }

    /// Initializes the `TableViewCell` with an `icon` and `label`
    /// Both the icon and label will be colored, and sized based on the user's preferences.
    /// - Parameters:
    ///   - frameRect: The frame of the cell.
    ///   - item: The file item the cell represents.
    ///   - isEditable: Set to true if the user should be able to edit the file name.
    init(frame frameRect: NSRect, isEditable: Bool = true, workspace: WorkspaceDocument?) {
        super.init(frame: frameRect)
        setupViews(frame: frameRect, isEditable: isEditable)
        self.workspace = workspace
    }

    // Default init, assumes isEditable to be false
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setupViews(frame: frameRect, isEditable: false)
    }


Review comment (suggestion):
Leaving out `weak` here worries me. I don't think this view should need to strongly reference the workspace object.

Code after:
//
//  StandardTableViewCell.swift
//  CodeEdit
//
//  Created by TAY KAI QUAN on 17/8/22.
//

import SwiftUI

class StandardTableViewCell: NSTableCellView {

    weak var secondaryLabel: NSTextField?
    weak var workspace: WorkspaceDocument?

    var secondaryLabelRightAligned: Bool = true {
        didSet {
            resizeSubviews(withOldSize: .zero)
        }
    }

    /// Initializes the `TableViewCell` with an `icon` and `label`
    /// Both the icon and label will be colored, and sized based on the user's preferences.
    /// - Parameters:
    ///   - frameRect: The frame of the cell.
    ///   - item: The file item the cell represents.
    ///   - isEditable: Set to true if the user should be able to edit the file name.
    init(frame frameRect: NSRect, isEditable: Bool = true) {
        super.init(frame: frameRect)
        setupViews(frame: frameRect, isEditable: isEditable)

    }

    // Default init, assumes isEditable to be false
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setupViews(frame: frameRect, isEditable: false)
    }
Repository: CodeEditApp/CodeEdit
File: CodeEdit/Features/Editor/TabBar/Tabs/Tab/Models/EditorTabFileObserver.swift (Swift)

Code before:
//
//  EditorTabFileObserver.swift
//  CodeEdit
//
//  Created by Filipp Kuznetsov on 25.02.2025.
//

import Foundation
import SwiftUI

/// Observer ViewModel for tracking file deletion
final class EditorTabFileObserver: ObservableObject, CEWorkspaceFileManagerObserver {
    @Published private(set) var isDeleted = false

    private let item: CEWorkspaceFile

    init(item: CEWorkspaceFile) {
        self.item = item
    }

    func fileManagerUpdated(updatedItems: Set<CEWorkspaceFile>) {
        guard let parent = item.parent else {
            return
        }

        if updatedItems.contains(parent) {
            isDeleted = item.doesExist == false
        }
    }
}


Review comment (suggestion):
I believe this can be simplified, and I’m fairly certain it should be updated on the main thread as well
```suggestion
  func fileManagerUpdated(updatedItems: Set<CEWorkspaceFile>) {
        if let parent = item.parent, updatedItems.contains(parent) {
            isDeleted = item.doesExist == false
        }
    }
```

Code after:
//
//  EditorTabFileObserver.swift
//  CodeEdit
//
//  Created by Filipp Kuznetsov on 25.02.2025.
//

import Foundation
import SwiftUI

/// Observer ViewModel for tracking file deletion
@MainActor
final class EditorTabFileObserver: ObservableObject,
    CEWorkspaceFileManagerObserver {
    @Published private(set) var isDeleted = false

    private let tabFile: CEWorkspaceFile

    init(file: CEWorkspaceFile) {
        self.tabFile = file
    }

    nonisolated func fileManagerUpdated(updatedItems: Set<CEWorkspaceFile>) {
        Task { @MainActor in
            if let parent = tabFile.parent, updatedItems.contains(parent) {
                isDeleted = tabFile.doesExist == false
            }
        }
    }
}
Repository: CorentinJ/Real-Time-Voice-Cloning
File: encoder/audio.py (Python)

Code before:
from scipy.ndimage.morphology import binary_dilation
from encoder.params_data import *
from pathlib import Path
from typing import Optional, Union
import numpy as np
import librosa
import struct
import warnings

try:
    import webrtcvad
except:
    print("WARNING: Unable to import 'webrtcvad'. Please install for better noise removal.")
    webrtcvad=None

int16_max = (2 ** 15) - 1


def preprocess_wav(fpath_or_wav: Union[str, Path, np.ndarray],
                   source_sr: Optional[int] = None):
    """
    Applies the preprocessing operations used in training the Speaker Encoder to a waveform 
    either on disk or in memory. The waveform will be resampled to match the data hyperparameters.

    :param fpath_or_wav: either a filepath to an audio file (many extensions are supported, not 
    just .wav), either the waveform as a numpy array of floats.
    :param source_sr: if passing an audio waveform, the sampling rate of the waveform before 
    preprocessing. After preprocessing, the waveform's sampling rate will match the data 
    hyperparameters. If passing a filepath, the sampling rate will be automatically detected and 
    this argument will be ignored.
    """
    # Load the wav from disk if needed
    if isinstance(fpath_or_wav, str) or isinstance(fpath_or_wav, Path):
        wav, source_sr = librosa.load(str(fpath_or_wav), sr=None)
    else:
        wav = fpath_or_wav
    
    # Resample the wav if needed

Review comment (suggestion):
```suggestion
    warn("Unable to import 'webrtcvad'. This package enables noise removal and is recommended.")
```

Code after:
from scipy.ndimage.morphology import binary_dilation
from encoder.params_data import *
from pathlib import Path
from typing import Optional, Union
from warnings import warn
import numpy as np
import librosa
import struct

try:
    import webrtcvad
except:
    warn("Unable to import 'webrtcvad'. This package enables noise removal and is recommended.")
    webrtcvad=None

int16_max = (2 ** 15) - 1


def preprocess_wav(fpath_or_wav: Union[str, Path, np.ndarray],
                   source_sr: Optional[int] = None):
    """
    Applies the preprocessing operations used in training the Speaker Encoder to a waveform 
    either on disk or in memory. The waveform will be resampled to match the data hyperparameters.

    :param fpath_or_wav: either a filepath to an audio file (many extensions are supported, not 
    just .wav), either the waveform as a numpy array of floats.
    :param source_sr: if passing an audio waveform, the sampling rate of the waveform before 
    preprocessing. After preprocessing, the waveform's sampling rate will match the data 
    hyperparameters. If passing a filepath, the sampling rate will be automatically detected and 
    this argument will be ignored.
    """
    # Load the wav from disk if needed
    if isinstance(fpath_or_wav, str) or isinstance(fpath_or_wav, Path):
        wav, source_sr = librosa.load(str(fpath_or_wav), sr=None)
    else:
        wav = fpath_or_wav
    
    # Resample the wav if needed