hello
- User
hello
- Assistant
Hello! How can I help you today?
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
hello
Hello! How can I help you today?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// // SerialRecords.swift // Foxtronic // //
import Foundation
struct SerialRecord: Identifiable, Encodable, Decodable { var id = UUID() let model: Model let serial: String let date: Date var isDuplicated: Bool
enum CodingKeys: String, CodingKey {
case id
case model
case serial
case date
case isDuplicated
}
init(model: Model, serial: String, date: Date, isDuplicated: Bool = false) {
self.model = model
self.serial = serial
self.date = date
self.isDuplicated = isDuplicated
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey:.id)
try container.encode(model, forKey:.model)
try container.encode(serial, forKey:.serial)
try container.encode(date, forKey:.date)
try container.encode(isDuplicated, forKey:.isDuplicated)
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(UUID.self, forKey:.id)
model = try container.decode(Model.self, forKey:.model)
serial = try container.decode(String.self, forKey:.serial)
date = try container.decode(Date.self, forKey:.date)
isDuplicated = try container.decode(Bool.self, forKey:.isDuplicated)
}
}
class SerialHistory: ObservableObject { @Published var records: [SerialRecord] = [] { didSet { saveRecords() } }
private let recordsKey = "GenereeritudSerialid"
init() {
loadRecords()
}
func addRecord(serial: String, model: Model) {
let isDuplicated = records.contains { $0.serial == serial }
let newRecord = SerialRecord(
model: model,
serial: serial,
date: Date(),
isDuplicated: isDuplicated
)
records.indices.filter { records[$0].serial == serial }.forEach { records[$0].isDuplicated = true }
records.append(newRecord)
}
private func saveRecords() {
let encoder = JSONEncoder()
if let encodedData = try? encoder.encode(records) {
UserDefaults.standard.set(encodedData, forKey: recordsKey)
}
}
private func loadRecords() {
if let savedData = UserDefaults.standard.data(forKey: recordsKey) {
let decoder = JSONDecoder()
if let decodedRecords = try? decoder.decode([SerialRecord].self, from: savedData) {
records = decodedRecords
}
}
}
}
// // SerialHistoryView.swift // Foxtronic // //
import SwiftUI import UniformTypeIdentifiers
struct SerialHistoryView: View { @EnvironmentObject var serialHistory: SerialHistory @Environment(.dismiss) private var dismiss @State private var searchText: String = "" @State private var selection: Set<SerialRecord.ID> = [] @State private var recentSearches: [String] = [] @State private var isShowingDialog = false @State private var isShowingExportSheet = false @State var sortOrder: [KeyPathComparator] = [ .init(.model.name, order: SortOrder.forward) ] let suggestedSearchTerms = ["MacBook Pro", "iMac", "MacBook Air"] // Property to store the selected serial number for QR code display @State private var selectedSerialForQR: String?
// Property to control the visibility of the QR code sheet
@State private var isQRSheetPresented = false
var body: some View {
if serialHistory.records.isEmpty {
ContentUnavailableView {
Label("Seerianumbrid puuduvad", systemImage: "exclamationmark.triangle.fill")
} description: {
Text("Genereeritud seerianumbrid ilmuvad siia.")
}
} else {
Table(selection: $selection, sortOrder: $sortOrder) {
TableColumn("Mudel", value: \.model.name)
TableColumn("Mudeli number", value: \.model.modelNumber)
TableColumn("Mudeli identifikaator", value: \.model.identifier)
TableColumn("Seerianumber", value: \.serial) { record in
Button(action: {
selectedSerialForQR = record.serial
isQRSheetPresented = true
}) {
Text(record.serial)
.lineLimit(1)
}
}
TableColumn("Kuupäev", value: \.date) { record in
Text(dateFormatter.string(from: record.date))
}
TableColumn("Kas on duplikaat?", value: \.isDuplicated, comparator: BoolComparator()) { record in
Text(record.isDuplicated ? "Jah" : "Ei")
.foregroundColor(record.isDuplicated ? .red : .green)
}
} rows: {
ForEach(searchText.isEmpty ? serialHistory.records.sorted(using: sortOrder) : serialHistory.records.filter {
$0.model.name.localizedCaseInsensitiveContains(searchText) ||
$0.serial.localizedCaseInsensitiveContains(searchText) || $0.model.identifier.localizedCaseInsensitiveContains(searchText) ||
$0.model.modelNumber.localizedCaseInsensitiveContains(searchText) ||
dateFormatter.string(from: $0.date).localizedCaseInsensitiveContains(searchText) ||
($0.isDuplicated ? "Jah" : "Ei").localizedCaseInsensitiveContains(searchText)
}
.sorted(using: sortOrder)) { record in
TableRow(record)
}
.contextMenu {
Button("Kopeeri") {
print("Copy action triggered.")
copyRows(Array(selection))
}
Button("Kustuta") {
print("Delete action triggered.")
deleteRows(Array(selection))
}
}
}
.sheet(isPresented: $isQRSheetPresented) {
if let selectedSerial = selectedSerialForQR {
QRCodeSheet(serial: selectedSerial)
}
}
.searchable(text: $searchText, placement: .automatic) {
Section("Kiire otsing") {
ForEach(suggestedSearchTerms.filter { $0.hasPrefix(searchText) || searchText.isEmpty }, id: \.self) { term in
Text(term).searchCompletion(term)
}
}
if !recentSearches.isEmpty {
Section("Hiljutised otsingud") {
ForEach(recentSearches, id: \.self) { term in
Text(term).searchCompletion(term)
}
}
}
}
.onSubmit(of: .search) {
addRecentSearch(searchText)
}
.toolbar {
ToolbarItem(placement: .automatic) {
Button {
exportTableToFile()
} label: {
Label("Export", systemImage: "square.and.arrow.up")
}
.keyboardShortcut("e", modifiers: .command)
.fileExporter(
isPresented: $isShowingExportSheet,
document: SerialRecordDocument(records: serialHistory.records),
contentType: UTType.plainText,
defaultFilename: "SerialHistory"
) { result in
switch result {
case .success(let url):
print("File exported to: \(url)")
case .failure(let error):
print("Export failed: \(error.localizedDescription)")
}
}
}
ToolbarItem(placement: .automatic) {
Button(action: { isShowingDialog = true }) {
Label("Tühjenda", systemImage: "trash")
.labelStyle(.iconOnly)
}
.disabled(serialHistory.records.isEmpty)
.confirmationDialog(
"Oled kindel, et soovid genereeritud seerianumbrid tühjendada?",
isPresented: $isShowingDialog
) {
Button("Kustuta", role: .destructive) {
clearAllData()
dismiss()
}
} message: {
Text("Seda toimingut ei saa tagasi võtta!")
}
Button("OK") {
dismiss()
}
}
}
.navigationTitle("Genereeritud seerianumbrid")
.navigationSubtitle("Genereeritud seerianumbrite ajalugu")
}
}
private func exportTableToFile() {
isShowingExportSheet = true
}
private func isSerialDuplicated(_ record: SerialRecord) -> Bool {
let count = serialHistory.records.filter { $0.serial == record.serial }.count
return count > 0
}
private func addRecentSearch(_ term: String) {
if !recentSearches.contains(term) {
recentSearches.append(term)
if recentSearches.count > 5 { // Limit to 5 recent searches
recentSearches.removeFirst()
}
}
}
private func copyRows(_ selectedRows: [SerialRecord.ID]) {
let copiedText = selectedRows
.compactMap { id in serialHistory.records.first { $0.id == id } }
.map { record in
"""
Mudel: \(record.model.name)
Mudeli number: \(record.model.modelNumber)
Mudeli identifikaator: \(record.model.identifier)
Seerianumber: \(record.serial)
Kuupäev: \(dateFormatter.string(from: record.date))
Kas on duplikaat?: \(record.isDuplicated ? "Jah" : "Ei")
"""
}
.joined(separator: "\n\n")
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(copiedText, forType: .string)
}
private func deleteRows(_ selectedRows: [SerialRecord.ID]) {
serialHistory.records.removeAll { record in
selectedRows.contains(record.id)
}
}
private func clearAllData() {
serialHistory.records = []
}
}
private let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long formatter.timeStyle = .medium return formatter }()
// Updated KeyPathComparator to handle Bool private struct BoolComparator: SortComparator { typealias Compared = Bool
func compare(_ lhs: Bool, _ rhs: Bool) -> ComparisonResult {
return lhs == rhs ? .orderedSame : (lhs ? .orderedAscending : .orderedDescending)
}
var order: SortOrder = .forward
} // // SerialHistoryViewModel.swift // Foxtronic // //
import Foundation import SwiftUI
class SerialHistoryViewModel: ObservableObject { @Published var records: [SerialRecord] = [] @Published var searchText: String = "" @Published var selection: Set<SerialRecord.ID> = [] @Published var sortOrder: [KeyPathComparator] = [ .init(.model.name, order: SortOrder.forward) ]
private var recentSearches: [String] = []
init(serialHistory: SerialHistory) {
self.serialHistory = serialHistory
loadRecords()
}
func addRecentSearch(_ term: String) {
if !recentSearches.contains(term) {
recentSearches.append(term)
if recentSearches.count > 5 {
recentSearches.removeFirst()
}
}
}
func copyRows(_ selectedRows: [SerialRecord.ID]) {
let copiedText = selectedRows
.compactMap { id in records.first { $0.id == id } }
.map { record in
"""
Mudel: \(record.model.name)
Mudeli number: \(record.model.modelNumber)
Mudeli identifikaator: \(record.model.identifier)
Seerianumber: \(record.serial)
Kuupäev: \(dateFormatter.string(from: record.date))
Kas on duplikaat?: \(record.isDuplicated ? "Jah" : "Ei")
"""
}
.joined(separator: "\n\n")
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(copiedText, forType: .string)
}
func deleteRows(_ selectedRows: [SerialRecord.ID]) {
records.removeAll { record in
selectedRows.contains(record.id)
}
}
func clearAllData() {
records = []
}
// DateFormatter moved here
private let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .medium
return formatter
}()
private let recordsKey = "GenereeritudSerialid"
private let serialHistory: SerialHistory
private func loadRecords() {
if let savedData = UserDefaults.standard.data(forKey: recordsKey) {
let decoder = JSONDecoder()
if let decodedRecords = try? decoder.decode([SerialRecord].self, from: savedData) {
records = decodedRecords
}
}
}
private func saveRecords() {
let encoder = JSONEncoder()
if let encodedData = try? encoder.encode(records) {
UserDefaults.standard.set(encodedData, forKey: recordsKey)
}
}
} // // SerialRecordDocuments.swift // Foxtronic // //
import SwiftUI import UniformTypeIdentifiers
struct SerialRecordDocument: FileDocument { static var readableContentTypes: [UTType] { [.plainText] }
var records: [SerialRecord]
init(records: [SerialRecord]) {
self.records = records
}
init(configuration: ReadConfiguration) throws {
guard let data = configuration.file.regularFileContents,
let decodedRecords = try? JSONDecoder().decode([SerialRecord].self, from: data) else {
throw CocoaError(.fileReadCorruptFile)
}
records = decodedRecords
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
// Encode your records as plain text
let plainText = records.map { "\($0.model.name), \($0.model.modelNumber), \($0.model.identifier), \($0.serial), \($0.date), \($0.isDuplicated)\n" }.joined()
let data = plainText.data(using: String.Encoding.utf8) ?? Data()
return FileWrapper(regularFileWithContents: data)
}
} import SwiftUI import Charts
struct SerialChartView: View { @State private var timeframe: Timeframe = .twoWeeks @State private var topModels: [Model] = []
var body: some View {
VStack {
Picker("Timeframe", selection: $timeframe) {
Text("2 Weeks").tag(Timeframe.twoWeeks)
Text("Month").tag(Timeframe.month)
Text("Year").tag(Timeframe.year)
}
.pickerStyle(.segmented)
.padding(.bottom, 10)
Text("Top Models")
.font(.subheadline)
.foregroundColor(.secondary)
Chart {
ForEach(topModels.indices, id: \.self) { index in
LineMark(
x:.value("Day", topModels[index].date),
y:.value("Count", topModels[index].serialCount)
)
.foregroundStyle(by:.value("Model", topModels[index].name))
.interpolationMethod(.cardinal)
.symbol(by:.value("Model", topModels[index].name))
}
}
.chartLegend(position:.top)
.chartYScale(domain:.automatic(includesZero: false))
.chartXAxis {
AxisMarks(values: .automatic(roundLowerBound: false, roundUpperBound: false)) { value in
if value.index < value.count - 1 {
AxisValueLabel(format: DateFormatterStyle())
}
AxisTick()
AxisGridLine()
}
}
.frame(minHeight: 300)
}
.padding()
.onAppear {
updateTopModels()
}
.onChange(of: timeframe) { newValue in
updateTopModels()
}
}
private func updateTopModels() {
// Get the serial history from your app's data storage
let serialHistory = SerialHistory()
// Filter the serial history based on the selected timeframe
let filteredSerials: [SerialRecord]
switch timeframe {
case.twoWeeks:
filteredSerials = serialHistory.records.filter { $0.date > Date().addingTimeInterval(-1209600) }
case.month:
filteredSerials = serialHistory.records.filter { $0.date > Date().addingTimeInterval(-2592000) }
case.year:
filteredSerials = serialHistory.records.filter { $0.date > Date().addingTimeInterval(-31536000) }
}
// Group the filtered serials by model and count the serials for each model
let modelCounts = filteredSerials.reduce(into: [:]) { dict, serial in
dict[serial.model, default: 0] += 1
}
// Get the top 3 models with the most serials
let topModels = modelCounts.sorted { $0.value > $1.value }.prefix(3).map { Model(name: $0.key.name, identifier: $0.key.identifier, modelNumber: $0.key.modelNumber, serialCount: $0.value, date: $0.key.date) }
self.topModels = topModels
}
}
enum Timeframe: String, CaseIterable { case twoWeeks, month, year }
struct DateFormatterStyle: FormatStyle { func format(_ value: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMM dd" // Customize the date format as needed return dateFormatter.string(from: value) } }
#Preview { SerialChartView() }
Help me fix the SerialChartView, i want the linear chart to be working correctly
To fix and improve the SerialChartView for it to work correctly with a linear chart using the Charts framework in SwiftUI, you must ensure several things are in order: proper data structure, correctly updating and filtering data based on the selected timeframe, and accurately configuring the chart. Given the previous context about SerialRecord and Model, let's assume that the structure for Model you provided in your code for charting (such as containing fields like serialCount and date) needs to be slightly adjusted to fit a typical use case for serial tracking.
A primary issue was that the Model structure did not naturally contain a serialCount or a specific date for the trending of serial numbers over time. Instead, you might be interested in counts of serials generated per timeframe (e.g., daily).
Here is a simplified and revised approach that can guide you to achieve a working linear chart that displays trends for the top models based on their serial counts over the selected timeframe.
First, ensure your Model struct matches what your application's logic actually supports. The existing approach tried to retrofit the Model object in a way that's not typical for a serial history tracking scenario.
For the chart to display trends correctly, you will need a way to aggregate serial records by date and by model. Let's create a simplified version focusing on the core functionality:
import SwiftUI
import Charts
struct ModelTrend: Identifiable {
let id = UUID()
let name: String
let date: Date
var count: Int
}
class SerialHistoryViewModel: ObservableObject {
// Sample data
@Published var records: [SerialRecord] = []
// Constructs trends data for charting
func constructTrends(forTimeframe timeframe: Timeframe) -> [ModelTrend] {
// Example logic to construct trends, this needs to be adapted to your app's logic
// This should aggregate `SerialRecord`s by model and by date (or date range based on the timeframe), then
// count occurrences to create a series of `ModelTrend`
// Return mocked data for demonstration
let now = Date()
return [
ModelTrend(name: "Model A", date: now, count: 10),
ModelTrend(name: "Model B", date: now.addingTimeInterval(-86400), count: 8),
// Add more points as needed for demonstration
]
}
}
struct SerialChartView: View {
@EnvironmentObject var viewModel: SerialHistoryViewModel
@State private var timeframe: Timeframe = .twoWeeks
var body: some View {
VStack {
Picker("Timeframe", selection: $timeframe) {
ForEach(Timeframe.allCases, id: \.self) { timeframe in
Text(timeframe.rawValue.capitalized).tag(timeframe)
}
}
.pickerStyle(.segmented)
.padding()
Chart {
ForEach(viewModel.constructTrends(forTimeframe: timeframe)) { trend in
LineMark(
x: .value("Date", trend.date, unit: .day),
y: .value("Count", trend.count)
)
.foregroundStyle(by: .value("Model", trend.name))
.interpolationMethod(.catmullRom)
}
}
.chartYScale(domain: .automatic(includesZero: true))
.frame(height: 300)
}
.padding()
.onChange(of: timeframe) { _ in
// Normally, you'd update the chart data based on the selected timeframe
// viewModel.updateChartData(for: timeframe)
}
}
}
enum Timeframe: String, CaseIterable {
case twoWeeks = "Two Weeks", month = "Month", year = "Year"
}
struct SerialChartView_Previews: PreviewProvider {
static var previews: some View {
SerialChartView().environmentObject(SerialHistoryViewModel())
}
}
In this corrected version:
ModelTrend structure to represent the count of serials for a model on a specific date. This is what you would actually plot in a timeseries chart.constructTrends(forTimeframe:) method in SerialHistoryViewModel is a placeholder where you should implement logic that aggregates serial numbers by model and date or date range, according to the selected timeframe. The actual implementation would depend on how your data is structured and how you wish to represent trends over time.SerialChartView, the chart uses .x and .y with .value modifiers to bind the date and count to the respective axes, ensuring the chart can render the data trends.Please adjust the aggregation logic inside constructTrends(forTimeframe:) according to your actual SerialRecord data structure and the specific requirements for how you want to display trends over different timeframes. The key here is properly preparing your data so it can be visualized as intended in the chart.
Not yet included in a published release.