AUDIOKIT - Why is the AKOscillatorBank RELASE, DECAY, SUSTAIN, and ATTACK being updated long after I change their values? - audio-player

I have a simple AudioKit app in the works.
I initialize an AKOsicillatorBANK at runtime and allow you to press a button to access a new viewCONTROLLER which has SLIDERS that when changed change the values of the oscillatorBANK properties [releaseDURATION, attackDURATION, decayDURATION, sustainLEVEL].
At the end of the slider's PANGESTURE [state == ended], I call a function that sets the oscillatorBANKS properties to their new values, which are stored in class variables.
I do not know why, but the changes only take effect some time (a few minutes) after the function is called. Does anyone know why this is?
ALSO PLEASE DO NOT COMMENT ON MY CAPITALIZATION STYLE. I PREFER THIS AS IT ALLOWS ME TO EMPHASIZE WHAT I BELIEVE TO BE IS IMPORTANT, WHICH CAN THEN HELP YOU SEE MY TRAIN OF THOUGHTS BETTER.
HERE IS THE CODE. Please note that I ONLY included the code for DECAY within the panGESTURE, because attack, release, and sustain code is all the same design:
// MAIN VIEW CONTROLLER CLASS, GLOBAL SCOPE, INITIALIZED WITH VIEW DID LOAD //
let bank = AKOscillatorBank()
var bankATTACK: Double = 0
var bankDECAY: Double = 0
var bankSUSTAIN: Double = 1
var bankRELEASE: Double = 0
func updateBANKWAVE() {
self.bank.rampDuration = 1
self.bank.attackDuration = self.bankATTACK
self.bank.decayDuration = self.bankDECAY
self.bank.sustainLevel = self.bankSUSTAIN
self.bank.releaseDuration = self.bankRELEASE
print("NEW BANK RAMP [\(self.bank.rampDuration)]")
print("NEW BANK ATTACK [\(self.bank.attackDuration)]")
print("NEW BANK DEC [\(self.bank.decayDuration)]")
print("NEW BANK SUS [\(self.bank.sustainLevel)]")
print("NEW BANK REL [\(self.bank.releaseDuration)]")
}
func prepareforSEGUE() {
if let sliderCONTROLLER = segue.destination as? SLIDERVIEWCONTROLLER {
sliderCONTROLLER.mainCONTROLLER = self
}
}
// SLIDER VIEW CONTROLLER CLASS //
if panGESTURE.state == changed {
// ... update a UILabel to reflect the value to be set ...
decayTEXT = String(format: "%.3f", (self.decayTRANSLATION.truncatingRemainder(dividingBy: 100.0)))
// ... update the MAIN controller variables ...
self.mainCONTROLLER.bankDECAY = Double(self.decayTRANSLATION.truncatingRemainder(dividingBy: 100.0))
// ... protect against values above 10 or below 0 ...
if decayTRANSLATION > 10 { decayVALUE.text = "10.000" ; decayTRANSLATION = 10.01 ; self.mainCONTROLLER.bankDECAY = 10 }
if decayTRANSLATION < 0 { decayVALUE.text = "0.000" ; decayTRANSLATION = -0.01 ; self.mainCONTROLLER.bankDECAY = 0 }
}
if panGESTURE.state == ended {
self.mainCONTROLLER.updateBANKWAVE()
}

By changing the oscillatorBANK.rampDURATION property to 0 instead of 1, I get instantaneous results. However, even though the release is being set to 1, the note can still be heard after 4 or 5 seconds... so...

Related

XCUIElementQuery in SwiftUI testing returns inconsistent count

I'm doing UI testing of a SwiftUI view, and I have the following code to fetch a List element to check the count of staticTexts in it:
let pred = NSPredicate(format: "identifier == 'detailViewTable'")
let detailViewTable = app.descendants(matching: .any).matching(pred).firstMatch
let arrOfTexts = detailViewTable.staticTexts
let ct = arrOfTexts.count
print("Count is: \(ct)") // This prints 0
print("Count is now: \(detailViewTable.staticTexts.count)") // Also prints 0
The count always prints as 0.
The SwiftUI view basically looks like this:
List {
Section(header: Text("Item list")) {
HStack {
Text("Number")
Spacer()
Text(rec.recNum)
}
}
// Lots more Sections/HStacks/Texts/etc here
// ...
// ...
}
.accessibility(identifier: "detailViewTable")
.listStyle(.grouped)
When I put a breakpoint as shown,
and use po in the Debug Console, I get 0 for ct, but 21 if calling count directly:
(lldb) po ct
0
(lldb) po detailViewTable.staticTexts.count
21
Pic here:
Why is the var ct set to 0, but calling the count directly gives me the correct number 21?
It makes me wonder if the XCUIElementQuery takes a moment to run and returns the answer in some kind of implicit callback, and the data isn't ready at the moment the variable ct is set, but will return the correct answer in the debug console because it waits for the response. However, I don't see any discussion of a callback in the Apple documentation:
https://developer.apple.com/documentation/xctest/xcuielementquery
This answer
https://stackoverflow.com/a/37320452
pointed me in the right direction. The fix is to put a pause in the form of sleep(1), to give the query time to do its fetch, I assume.
let pred = NSPredicate(format: "identifier == 'detailViewTable'")
let detailViewTable = app.descendants(matching: .any).matching(pred).firstMatch
let arrOfTexts = detailViewTable.staticTexts
sleep(1) // <-- Add this
let ct = arrOfTexts.count
print("Count is: \(ct)") // Now prints 21
print("Count is now: \(detailViewTable.staticTexts.count)") // Also prints 21

google-apps-script multiple criteria writing over headers

I have taken a bit of script from Serge which is great (original link here. I have added in a second criteria to exclude certain rows and it works great except, if there is not header in the sheet being copied to, it will not work (error: "The coordinates or dimensions of the range are invalid.") and if I enter a header or some other data, it overwrites it. Can anyone assist please? I have also found that is there is no match to the criteria I get following message "TypeError: Cannot read property "length" from undefined."
Also, what change would I need to make to change the cell 'dataSheetLog[i][12]' to the status variable, i.e. "COPIED" after I have copied it across. I have tried writing a setValue line but it is obviously the wrong instruction for that syntax.
Code is:
{
var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetLog = Spreadsheet.getSheetByName("LOG");
var sheetMaint = Spreadsheet.getSheetByName("MAINTENANCE");
var Alast = sheetLog.getLastRow();
var criteria = "08 - Maintenance"
var status = "COPIED"
var dataSheetLog = sheetLog.getRange(2,1,Alast,sheetLog.getLastColumn()).getValues();
var outData = [];
for (var i in dataSheetLog) {
if (dataSheetLog[i][2]==criteria && dataSheetLog[i][12]!=status){
outData.push(dataSheetLog[i]);
}
}
sheetMaint.getRange(sheetMaint.getLastRow(),1,outData.length,outData[0].length).setValues(outData);
}
In:
sheetMaint.getRange(sheetMaint.getLastRow(),1,outData.length,outData[0].length).setValues(outData);
getLastRow() refers to the last occupied row and should be ,getLastRow() + 1,to keep from overwriting your headers and other problems.
Edited:
{
var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetLog = Spreadsheet.getSheetByName("LOG");
var sheetMaint = Spreadsheet.getSheetByName("MAINTENANCE");
var Alast = sheetLog.getLastRow(); // Log
var criteria = "08 - Maintenance"
var status = "COPIED"
var dataSheetLog = sheetLog.getRange(2,1,Alast,sheetLog.getLastColumn()).getValues(); //Log
var dataSheetLogStatusRange = sheetLog.getRange(2,13,Alast,1); //Log
var dataSheetLogStatus = dataSheetLogStatusRange.getValues(); //Log
var outData = [];
for (var i =0; i < dataSheetLog.length; i++) {
if (dataSheetLog[i][2]==criteria && dataSheetLog[i][12]!=status){
outData.push(dataSheetLog[i]);
dataSheetLogStatus[i][0] = "COPIED";
}
}
if(outData.length > 0) {
sheetMaint.getRange(sheetMaint.getLastRow() + 1,1,outData.length,outData[0].length).setValues(outData);
dataSheetLogStatusRange.setValues(dataSheetLogStatus);
}
}
}
what change would I need to make to change the cell
'dataSheetLog[i][12]' to the status variable, i.e. "COPIED" after I
have copied it across.
You were trying to update the value in the array that was extracted from the sheet and not the sheet itself. As arrays are zero based and spreadsheets are not, to translate, +1 must be added to array row and column indices. I am assuming status is in column M of your sheet.

if does not work in changing color cell

After testing code below, all steps works except the if statement. Values of cells which are indeed "ik kom niet, mijn partner komt wel" >> but the color doesnot change into red.
Who is able to solve this problem?
function Changecolor (e)
{
var target = SpreadsheetApp.openById("1234");
var target_sheet = target.getSheetByName("lijst beschikbare bridgers");
var rows = target_sheet.getDataRange();
var numRows = rows.getNumRows();
var range = target_sheet.getRange("A1:K100");
range.setBackground('');
for (var i=2; i <= numRows; i++)
{
var value = target_sheet.getRange(i, 4).getValue();
if (value == "ik kom niet, mijn partner komt wel")
{
target_sheet.getRange(i,1).setBackground('red');
}
}
}
Mikeng ths for editing. I will change all my scripts like this.
Problem is solved. Actually there was no problem the script is OK and works. I just gave the wrong range:
var value = target_sheet.getRange(i, 4).getValue();
should be:
var value = target_sheet.getRange(i, 10).getValue();
Such a stupidy costs me at least 3 hours...

Flex: Spark List's Indeces in View change on Orientation Change

I have a spark list with a variable row_height (2 custom itemRenderer: Header 30 px, Contact 60 px) that on the only first orientation change after a scroll, change the indexes in view.
I tried to set Header to be 60 px height, and i had no problems with the orientation change.
I'm not setting the verticalScrollPosition anywhere. Adding an event listener on the viewport's list and watching the verticalScrollPosition, it doesn't change on orientation change.
I really don't know how can i fix that.
EDIT:
This is the code relative to the list:
<fx:Script>
protected function creationCompleteHandler(event:FlexEvent):void
{
addressBookViewModel = ViewModelFactory.getInstance().getAddressBookViewModel();
addressBookViewModel.getUserContacts(onDataReceived);
}
protected function pagedContactsList_initializeHandler(event:FlexEvent):void
{
asyncListView.list = pagedContactsList;
}
private function onDataReceived():void
{
pagedContactsList.length = (BusinessContext.getInstance().getTotalContacts() + BusinessContext.getInstance().getTotalLastNames());
loadPagedData();
}
private function createPendingItemFunctionHandler(index:int, ipe:ItemPendingError):Object
{
if(!addressBookViewModel.pageUp)
{
addressBookViewModel.pageUp = true;
addressBookViewModel.currentPage++;
addressBookViewModel.getMoreUserContacts(onMoreDataRecieved, onMoreDataMissing);
}
return loadingDataHeader;
}
private function onMoreDataRecieved():void
{
loadPagedData();
}
private function loadPagedData():void
{
for(var i:int = 0; i < addressBookViewModel.contacts.length; i++)
{
pagedContactsList.setItemAt(addressBookViewModel.contacts.getItemAt(i), pagedContactsList.lastItemInsertedIndex);
pagedContactsList.lastItemInsertedIndex++;
}
addressBookViewModel.pageUp = false;
}
internal var headerItemRender:ClassFactory = new ClassFactory(HeaderItemRenderer);
internal var contactItemRenderer:ClassFactory = new ClassFactory(ContactItemRenderer);
private function rendererFunction(item:Object):ClassFactory
{
return item.hasOwnProperty("isHeader") ? headerItemRender : contactItemRenderer;
}
</fx:Script>
<fx:Declarations>
<custom:PagedArrayList id="pagedContactsList" initialize="pagedContactsList_initializeHandler(event)"/>
</fx:Declarations>
<s:List id="list" width="100%"
height="100%" itemRendererFunction="rendererFunction" change="list1_changeHandler(event)">
<s:AsyncListView id="asyncListView" createPendingItemFunction="createPendingItemFunctionHandler" />
</s:List>
The curious thing is that before and after the orientation change the list.scroller.viewport.verticalScrollPosition has the same value even if the list has scrolled ~ 40 rows. (40 is the page size).
I have many lists in my app, and every list that has const row_height has no issue, but the 2 with a variable row_height have this problem. Maybe it's caused by the AsyncListView.
EDIT 2:
I removed the AsyncListView, binding directly addressBookViewModel.contacts to the list.dataProvider, removing the pagination and the issue is still there.
EDIT 3:
I think that the only thing to do is to put breakpoints everywhere in the Scroller's class.
EDIT 4:
This issue happens only when scrolling to the bottom of the list.
EDIT 5:
Find the issue!
VerticalLayout.as, in updateDisplayListVirtual(row 1797) there's a call to a method (updateLLV) that set up a LinearLayoutVector using a typicalLayoutElement. This is lazily init with the first itemRenderer added to the dataGroup of the list. In my case it's the HeaderItemRenderer (30px).
After the updateLLV, the startIndex (index of the first visible item) is setted by calling the indexOf on the LinearLayoutVector and passing the verticalScrollPosition. (briefly: verticalScrollPosition / typicalLayoutElement.height)
The problem is that nowhere is taken into consideration the variableRowHeight!
Workaround found! Not so elegant, but it works.
stage.eventListener(StageOrientationEvent.ORIENTATION_CHANGING, yourReorientHandler, false, 1)
Setting the priority is really important, otherwise the updateDisplayListVirtual will be called before your handler.
private function reorientHandler(event:StageOrientationEvent):void
{
var IndecesInView:Vector.<int> = list.dataGroup.getItemIndicesInView();
var firstInView:int = IndecesInView[0];
callLater(
function():void
{
if(!list.layout.getScrollPositionDeltaToElement(firstInView+1)) return;
list.scroller.viewport.verticalScrollPosition += list.layout.getScrollPositionDeltaToElement(firstInView+1).y;
});
}

Restrict TextField to act like a numeric stepper

I am making a numeric stepper from scratch, so I want my text field to only accept numbers in this format: xx.x, x.x, x, or xx where x is a number. For example:
Acceptable numbers:
1
22
15.5
3.5
None Acceptable numbers:
213
33.15
4332
1.65
Maybe this will help some how:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html#restrict
This is what I got so far:
var tx:TextField = new TextField();
tx.restrict="0-9."; //Maybe there is a regular expression string for this?
tx.type=TextFieldType.INPUT;
tx.border=true;
You can copy past this in flash and it should work.
Thank you very much for your help good sirs.
Very similar to TheDarklins answer, but a little more elegant. And actually renders _tf.restrict obsolete, but I would still recommend using it.
_tf.addEventListener(TextEvent.TEXT_INPUT, _onTextInput_validate);
Both of these event listeners here do the EXACT same function identically. One is written in a one line for those who like smaller code. The other is for those who like to see what's going on line by line.
private function _onTextInput_validate(__e:TextEvent):void
{
if ( !/^\d{1,2}(?:\.(?:\d)?)?$/.test(TextField(__e.currentTarget).text.substring(0, TextField(__e.currentTarget).selectionBeginIndex) + __e.text + TextField(__e.currentTarget).text.substring(TextField(__e.currentTarget).selectionEndIndex)) ) __e.preventDefault();
}
for a more broken down version of the event listener
private function _onTextInput_validate(__e:TextEvent):void
{
var __reg:RegExp;
var __tf:TextField;
var __text:String;
// set the textfield thats causing the event.
__tf = TextField(__e.currentTarget);
// Set the regular expression.
__reg = new RegExp("\\d{1,2}(?:\\.(?:\\d)?)?$");
// or depending on how you like to write it.
__reg = /^\d{1,2}(?:\.(?:\d)?)?$/;
// Set all text before the selection.
__text = __tf.text.substring(0, __tf.selectionBeginIndex);
// Set the text entered.
__text += __e.text;
// Set the text After the selection, since the entered text will replace any selected text that may be entered
__text += __tf.text.substring(__tf.selectionEndIndex);
// If test fails, prevent default
if ( !__reg.test(__text) )
{
__e.preventDefault();
}
}
I have had to allow xx. as a valid response otherwise you would need to type 123 then go back a space and type . for 12.3. That is JUST NOT NICE. So 12. is now technically valid.
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.events.TextEvent;
public class DecimalPlaces extends Sprite
{
public function DecimalPlaces()
{
var tf:TextField = new TextField();
tf.type = TextFieldType.INPUT;
tf.border = true;
tf.width = 200;
tf.height = 16;
tf.x = tf.y = 20;
tf.restrict = ".0-9"
tf.addEventListener(TextEvent.TEXT_INPUT, restrictDecimalPlaces);
addChild(tf);
}
function restrictDecimalPlaces(evt:TextEvent):void
{
var matches:Array = evt.currentTarget.text.match(/\./g);
var allowedDecimalPlaces:uint = 1;
if ((evt.text == "." && matches.length >= 1) ||
(matches.length == 1 && (evt.currentTarget.text.lastIndexOf(".") + allowedDecimalPlaces < evt.currentTarget.text.length)))
evt.preventDefault();
}
}
}