Custom Checkbox Category Selector - google-visualization

I want to filter my Data Array by different categories. It is working, but it should pick the rows of multiple categories. if multiple checkboxes are checked. How can I implement this code?
Here is my code:
check_cells = function() {
var values = [];
if (document.getElementById("checkbox_pouch").checked == true) {
values.push('pouch');
}
if (document.getElementById("checkbox_18650").checked == true) {
values.push('18650');
}
if (document.getElementById("checkbox_21700").checked == true) {
values.push('21700');
}
if (document.getElementById("checkbox_pouch").checked == false && document.getElementById("checkbox_18650").checked == false && document.getElementById("checkbox_21700").checked == false) {
values.push('empty');
}
if (values.length > 0) {
view.setRows(data.getFilteredRows([{
column:2,
test: function (value) {
return (values.indexOf(value) > -1);
}
}]));
}
dashboard.draw(view, drawOptions);
}
else {
view.setRows(data.getFilteredRows([{column:2}]));
dashboard.draw(view);
}
}
var view = new google.visualization.DataView(data);
var drawOptions = {
showRowNumber: false,
allowHtml: true,
};
// Inititial Draw of the dashboard.
dashboard.draw(view, drawOptions);

when filtering on multiple values,
you will need to combine those into one filter setting.
the data view will not let you have multiple filters on the same column.
in this case, you can use the test callback function, rather than the value key.
here, an array is used to gather the values,
and the test callback to filter the column...
check_pouch = function() {
var values = [];
if (document.getElementById("checkbox_pouch").checked == true) {
values.push('pouch');
}
if (document.getElementById("checkbox_18650").checked == true) {
values.push('18650');
}
if (values.length > 0) {
view.setRows(data.getFilteredRows([{
column:2,
test: function (value) {
return (values.indexOf(value) > -1);
}
}]));
}
dashboard.draw(view);
}

Related

Deleting SwiftUI Items from List Based on Section

I have a TodoListView which displays a List in sections. The sections can be pending or completed as shown below. I am using Realm for my app. The problem is that how can I find out the task I want to delete, since they can belong in different sections.
What should I do in my onDelete function to delete the task in a particular section.
enum Sections: String, CaseIterable {
case pending = "Pending"
case completed = "Completed"
}
struct TodoListView: View {
#ObservedResults(Task.self) var tasks: Results<Task>
var pendingTasks: [Task] {
tasks.filter { $0.isCompleted == false }
}
var completedTasks: [Task] {
tasks.filter { $0.isCompleted == true }
}
var body: some View {
let _ = print(Self._printChanges())
List {
ForEach(Sections.allCases, id: \.self) { section in
Section {
let filteredTasks = section == .pending ? pendingTasks: completedTasks
if filteredTasks.isEmpty {
Text("No tasks")
}
ForEach(filteredTasks, id: \._id) { task in
HStack {
TaskCellView(task: task)
}
}.onDelete { indexSet in
// What to do here:
// can I get the element which I swiped to delete on
}
} header: {
Text(section.rawValue)
}
}
}.listStyle(.plain)
}
}
UPDATE:
I was able to write the following code and it seems to be working fine:
.onDelete { indexSet in
var filteredTasks: [Task] = []
switch section {
case .pending:
filteredTasks = tasks.filter { $0.isCompleted == false }
case .completed:
filteredTasks = tasks.filter { $0.isCompleted == true }
}
indexSet.forEach { index in
let task = filteredTasks[index]
$tasks.remove(task)
}
}

Trouble looping with AVFoundation audio recorder & audioplayer

I am trying to make an app that records and loops an audio clip.
I have this function in my AudioPlayer struct:
func loop(nums:Int){
audioPlayer!.numberOfLoops = nums
}
And I am referencing it in my swiftUI struct. For some reason it crashes the app. Here is where I reference the function:
Button(action:{
if !canRecord && !edit && slot.beenRecorded == true{
if isInfinite{
audioPlayer.loop(nums: -1)
}
else{
audioPlayer.loop(nums: myInt)
}
if let recording = audioRecorder.recordings.first(where: { $0.fileURL.lastPathComponent == "\(index).m4a" }) {
self.audioPlayer.startPlayback(audio: recording.fileURL)
}
else {
print("No audio url was saved")
}
if audioPlayer.isPlaying == false {
print("audio is playing")
}
}
if canRecord && oneIsRecording == false{
slot.beenRecorded = true
UserDefaults.standard.set(true, forKey: slot.id)
isActive = true
}
})

Password Filed Validation not working in Swift 3

I had multiple images based on the text changes in textfield I need to change the image as selected like when user enter capital letter and small letter and special character and number based on that image get selected ..but I can't change according that.
here is my code:
#IBAction func textFieldEditingChanged(_ sender: Any) {
if isValidated(passwordTextField.text!){
print("succ")
}
}
func isValidated(_ password: String) -> Bool {
var lowerCaseLetter: Bool = false
var upperCaseLetter: Bool = false
var digit: Bool = false
var specialCharacter: Bool = false
for char in password.unicodeScalars {
if !lowerCaseLetter {
lowerCaseLetter = CharacterSet.lowercaseLetters.contains(char)
}
if !upperCaseLetter {
upperCaseLetter = CharacterSet.uppercaseLetters.contains(char)
}
if !digit {
digit = CharacterSet.decimalDigits.contains(char)
}
if !specialCharacter {
specialCharacter = CharacterSet.punctuationCharacters.contains(char)
}
}
if (specialCharacter) {
//do what u want
self.SpecialCharacter_img.image = UIImage(named: "GreenTick")
return false
}
if ( digit) {
//do what u want
self.onenumberImageCondiotion_img.image = UIImage(named: "GreenTick")
return false
}
if ( lowerCaseLetter && upperCaseLetter) {
//do what u want
self.UpperCaseImageConditions_img.image = UIImage(named: "GreenTick")
return false
}
else {
self.UpperCaseImageConditions_img.image = UIImage(named: "redtick")
self.SpecialCharacter_img.image = UIImage(named: "redtick")
self.onenumberImageCondiotion_img.image = UIImage(named: "redtick")
return false
}
}
Your code in the isValidated method just needs a little tweaking:
I changed it a little bit and it works in my test project.
func isValidated(_ password: String) -> Bool {
var lowerCaseLetter: Bool = false
var upperCaseLetter: Bool = false
var digit: Bool = false
var specialCharacter: Bool = false
for char in password.unicodeScalars {
if !lowerCaseLetter {
lowerCaseLetter = CharacterSet.lowercaseLetters.contains(char)
}
if !upperCaseLetter {
upperCaseLetter = CharacterSet.uppercaseLetters.contains(char)
}
if !digit {
digit = CharacterSet.decimalDigits.contains(char)
}
if !specialCharacter {
specialCharacter = CharacterSet.punctuationCharacters.contains(char)
}
}
if (lowerCaseLetter) {
lowercaseLabel.text = "✅ Has a lowercase letter"
lowercaseLabel.textColor = .green
lowercaseLabel.sizeToFit()
} else {
lowercaseLabel.text = "Does not have a lowercase letter"
lowercaseLabel.textColor = .red
lowercaseLabel.sizeToFit()
}
if (upperCaseLetter) {
uppercaseLabel.text = "✅ Has an uppercase letter"
uppercaseLabel.textColor = .green
uppercaseLabel.sizeToFit()
} else {
uppercaseLabel.text = "Does not have an uppercase letter"
uppercaseLabel.textColor = .red
uppercaseLabel.sizeToFit()
}
if (specialCharacter) {
specialLabel.text = "✅ Has a special character"
specialLabel.textColor = .green
specialLabel.sizeToFit()
} else {
specialLabel.text = "Does not have a special character"
specialLabel.textColor = .red
specialLabel.sizeToFit()
}
if (digit) {
numberLabel.text = "✅ Has a number"
numberLabel.textColor = .green
numberLabel.sizeToFit()
} else {
numberLabel.text = "Does not have a number"
numberLabel.textColor = .red
numberLabel.sizeToFit()
}
if lowerCaseLetter && upperCaseLetter && digit && specialCharacter {
return true
} else {
return false
}
The last part is important where you have to check that all the conditions are true, or else return false. Also, I removed the return false code in each of the sections where you put '// do what you want' because I don't think the function should return false except at the final check.
Then in the specific 'if statements' where you check for each subcondition being true, add an else statement that will toggle/set your images for either state (e.g. green tick for true, red X for false).
Project Code:
https://github.com/Wattholm/PasswordValidator

Treating adjacent tracking areas as one contiguous area

I'm trying to present a UI of a title/less window when a mouse leaves a window's title or contentview, but not when moving from one to the other; in essence have the two tracking areas function as one (I resorted to this as I couldn't figure out how to create a single area when the title view is hidden):
override func mouseEntered(with theEvent: NSEvent) {
let hideTitle = (doc?.settings.autoHideTitle.value == true)
if theEvent.modifierFlags.contains(.shift) {
NSApp.activate(ignoringOtherApps: true)
}
switch theEvent.trackingNumber {
case closeTrackingTag:
Swift.print("close entered")
closeButton?.image = closeButtonImage
break
default:
Swift.print(String(format: "%# entered",
(theEvent.trackingNumber == titleTrackingTag
? "title" : "view")))
let lastMouseOver = mouseOver
mouseOver = true
updateTranslucency()
// view or title entered
if hideTitle && (lastMouseOver != mouseOver) {
updateTitleBar(didChange: !lastMouseOver)
}
}
}
override func mouseExited(with theEvent: NSEvent) {
let hideTitle = (doc?.settings.autoHideTitle.value == true)
switch theEvent.trackingNumber {
case closeTrackingTag:
Swift.print("close exited")
closeButton?.image = nullImage
break
default:
Swift.print(String(format: "%# exited",
(theEvent.trackingNumber == titleTrackingTag
? "title" : "view")))
let lastMouseOver = mouseOver
mouseOver = false
updateTranslucency()
if hideTitle && (lastMouseOver != mouseOver) {
updateTitleBar(didChange: lastMouseOver)
}
}
}
Additionally, there's a tracking rect on the close button to appear only when over. Anyway, from my tracer output I see the issue - mouse over window from beneath to over its title:
view entered
updateTitleBar
**view entered**
view exited
updateTitleBar
title entered
updateTitleBar
title exited
Note sure why I'm getting a second view entered event (view entered), but the movement out of the view and onto the adjacent title each triggers an updateTilebar() call which is visually stuttering - not remedied so far with animation:
fileprivate func docIconToggle() {
let docIconButton = panel.standardWindowButton(.documentIconButton)
if settings.autoHideTitle.value == false || mouseOver {
if let doc = self.document {
docIconButton?.image = (doc as! Document).displayImage
}
else
{
docIconButton?.image = NSApp.applicationIconImage
}
docIconButton?.isHidden = false
self.synchronizeWindowTitleWithDocumentName()
}
else
{
docIconButton?.isHidden = true
}
}
#objc func updateTitleBar(didChange: Bool) {
if didChange {
Swift.print("updateTitleBar")
if settings.autoHideTitle.value == true && !mouseOver {
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = 1.0
panel.animator().titleVisibility = NSWindowTitleVisibility.hidden
panel.animator().titlebarAppearsTransparent = true
panel.animator().styleMask.formUnion(.fullSizeContentView)
}, completionHandler: {
self.docIconToggle()
})
} else {
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = 1.0
panel.animator().titleVisibility = NSWindowTitleVisibility.visible
panel.animator().titlebarAppearsTransparent = false
panel.animator().styleMask.formSymmetricDifference(.fullSizeContentView)
}, completionHandler: {
self.docIconToggle()
})
}
}
}
So my question is about how to defer the actions when areas are adjacent.
They (titlebar & content view) are not siblings of each other so didn't think a hitTest() was doable but basically if I could tell if I was moving into the adjacent tracking area, I'd like it to be a no-op.
Any help with why animation isn't working would be a plus.
Not a true answer, but if you know the adjacent view's rect you can use the event's location to probe whether you'd want to ignore movements among adjacent views:
override func mouseExited(with theEvent: NSEvent) {
let hideTitle = (doc?.settings.autoHideTitle.value == true)
let location : NSPoint = theEvent.locationInWindow
switch theEvent.trackingNumber {
case closeTrackingTag:
Swift.print("close exited")
closeButton?.image = nullImage
break
default:
let vSize = self.window?.contentView?.bounds.size
// If we exit to the title bar area we're still "inside"
// and visa-versa, leaving title to content view.
if theEvent.trackingNumber == titleTrackingTag, let tSize = titleView?.bounds.size {
if location.x >= 0.0 && location.x <= (vSize?.width)! && location.y < ((vSize?.height)! + tSize.height) {
Swift.print("title -> view")
return
}
}
else
if theEvent.trackingNumber == viewTrackingTag {
if location.x >= 0.0 && location.x <= (vSize?.width)! && location.y > (vSize?.height)! {
Swift.print("view -> title")
return
}
}
mouseOver = false
updateTranslucency()
if hideTitle {
updateTitleBar(didChange: true)
}
Swift.print(String(format: "%# exited",
(theEvent.trackingNumber == titleTrackingTag
? "title" : "view")))
}
}

data-bind if statement on click function in knockout js

I need help on executing an one-liner if statement on my data-bind
this is the HTML
<div data-bind="text: Fields.FieldDescription, click:function() { $root.selectedToListRule.push(Fields.FieldCode());}" onmousedown="this.style.backgroundColor='#4BA6FF'"></div>
this is the js code
var RemovefieldCodeRule = function (parent, data) {
//console.log(parent.InitiatorFields(), data.selectedApproverFields());
var sel = selectedToListRule();
//console.log(sel);
for (var i = 0; i < sel.length; i++) {
var selCat = sel[i];
var result = data.selectedApproverFields.remove(function (item) {
return item.FieldCode() == selCat;
});
if (result && result.length > 0) {
//Add to WorkflowObject - InitiatorFields
var obj = dataservice.getEmptyObjects("WorkFlowObjectFields");
obj.done(function (data) {
var wfo = model.genericObject(data);
wfo.ID(result[0].ID);
wfo.WorkFlowObjects_ID(parent.ID());
wfo.FieldCode(result[0].FieldCode());
wfo.FieldDescription(result[0].FieldDescription());
parent.InitiatorFields.push(wfo);
});
}
}
selectedToListRule.removeAll();
parent.InitiatorFields.sort(function (left, right) { return left.FieldDescription() == right.FieldDescription() ? 0 : (left.FieldDescription() < right.FieldDescription() ? -1 : 1) });
data.selectedApproverFields.sort(function (left, right) { return left.FieldDescription() == right.FieldDescription() ? 0 : (left.FieldDescription() < right.FieldDescription() ? -1 : 1) });
}
on my data-bind, there's a click event wherein i will need to select from the dynamically generated div. what i want to happen is when the user clicks on a certain div (it gets selected) and if the user changes his mind to unselect the div he previously selected.
How can i can achieve this on one-liner if statement using knockout