Flex how to use callLater? - apache-flex

In my flex mobile application, I have a loop running for over 100 iterations. In each iteration I'm updating some properties of specific Label(s). Since the loop is time consuming, I need to update the screen and display intermediate results at each iteration. How can I break the loop and refresh the display list?
function theFunction():void{
for var i:int = 0; i < n; i++{
doBusyStuff();
label_1.text = "iteration"+" i";
}
}

In that situation, I prefer to use flash.utils.setTimeout()
import flash.utils.setTimeout;
function theFunction(limit:int, current:int = 0):void
{
if (current >= limit)
return;
doBusyStuff();
label_1.text = "iteration "+ current.toString();
setTimeout(theFunction, 0, limit, current+1);
}
However, both setTimeout() and callLater() depend on the tick or the frame rate, meaning that they won't do as fast as they can. So if you also want it to run faster, you should have it run a few loops per each call.

Another solution, similar to Chaniks' answer, uses DateTime to check how long the loop has been running on each iteration. Once it detects that it's been running for too long, it ends the loop and picks up again on the next Frame.
var i:int;
function callingFunction():void {
i = 0;
stage.addEventListener(Event.ENTER_FRAME, theFunction);
}
function theFunction(e:Event):void {
var time:DateTime = new DateTime();
var allowableTime:int = 30; //Allow 30ms per frame
while ((new DateTime().time - time.time < allowableTime) && i < n) {
doBusyStuff();
i++;
}
if (i >= n) {
stage.removeEventListener(Event.ENTER_FRAME, theFunction);
}
label_1.text = "iteration"+" i";
}

There are several methods to force redraw of components:
invalidateDisplayList();
invalidateProperties();
invalidateSize();
Just use whatever you need for your components inside a function and call it after your script using callLater(yourRedrawFunction);
EDIT: For example, in your case:
function theFunction():void{
for var i:int = 0; i < n; i++{
doBusyStuff();
label_1.text = "iteration"+" i";
}
callLater(yourRedrawFunction);
}

Related

How to script editor to clear cells but keep formula in certain cells

Is there a way to keep formulas in certain cells when I have a clear cell script. At the moment it clears everything and removes my formula.
Cells with formulas are - 'H2' & 'K2'
function reset() {
var sheet = SpreadsheetApp.getActive();
sheet.getRange("F3:K8").clearContent();
}
Clearing your content will always clear the formula in a cell. A cell has a text/number literal or a formula in it. There's not a function that will clear one and not the other.
But, you can check to see if a cell contains a formula, and if so, don't clear the content for it. That will functionally do what you want.
function reset() {
var sheet = SpreadsheetApp.getActive();
var range = sheet.getRange('F3:K8');
var numRows = range.getNumRows();
var numCols = range.getNumColumns();
for (var i = 1; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++) {
if (range.getCell(i,j).getFormula());
{
range.getCell(i,j).clearContent();
}
}
}
}

ConcurrentModificationException when reinserting a node JavaFX [duplicate]

We all know you can't do the following because of ConcurrentModificationException:
for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
But this apparently works sometimes, but not always. Here's some specific code:
public static void main(String[] args) {
Collection<Integer> l = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
l.add(4);
l.add(5);
l.add(6);
}
for (int i : l) {
if (i == 5) {
l.remove(i);
}
}
System.out.println(l);
}
This, of course, results in:
Exception in thread "main" java.util.ConcurrentModificationException
Even though multiple threads aren't doing it. Anyway.
What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?
I'm also using an arbitrary Collection here, not necessarily an ArrayList, so you can't rely on get.
Iterator.remove() is safe, you can use it like this:
List<String> list = new ArrayList<>();
// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
// Iterator<String> iterator = list.iterator();
// while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String string = iterator.next();
if (string.isEmpty()) {
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
Note that Iterator.remove() is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
Source: docs.oracle > The Collection Interface
And similarly, if you have a ListIterator and want to add items, you can use ListIterator#add, for the same reason you can use Iterator#remove — it's designed to allow it.
In your case you tried to remove from a list, but the same restriction applies if trying to put into a Map while iterating its content.
This works:
Iterator<Integer> iter = l.iterator();
while (iter.hasNext()) {
if (iter.next() == 5) {
iter.remove();
}
}
I assumed that since a foreach loop is syntactic sugar for iterating, using an iterator wouldn't help... but it gives you this .remove() functionality.
With Java 8 you can use the new removeIf method. Applied to your example:
Collection<Integer> coll = new ArrayList<>();
//populate
coll.removeIf(i -> i == 5);
Since the question has been already answered i.e. the best way is to use the remove method of the iterator object, I would go into the specifics of the place where the error "java.util.ConcurrentModificationException" is thrown.
Every collection class has a private class which implements the Iterator interface and provides methods like next(), remove() and hasNext().
The code for next looks something like this...
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch(IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
Here the method checkForComodification is implemented as
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
So, as you can see, if you explicitly try to remove an element from the collection. It results in modCount getting different from expectedModCount, resulting in the exception ConcurrentModificationException.
You can either use the iterator directly like you mentioned, or else keep a second collection and add each item you want to remove to the new collection, then removeAll at the end. This allows you to keep using the type-safety of the for-each loop at the cost of increased memory use and cpu time (shouldn't be a huge problem unless you have really, really big lists or a really old computer)
public static void main(String[] args)
{
Collection<Integer> l = new ArrayList<Integer>();
Collection<Integer> itemsToRemove = new ArrayList<>();
for (int i=0; i < 10; i++) {
l.add(Integer.of(4));
l.add(Integer.of(5));
l.add(Integer.of(6));
}
for (Integer i : l)
{
if (i.intValue() == 5) {
itemsToRemove.add(i);
}
}
l.removeAll(itemsToRemove);
System.out.println(l);
}
In such cases a common trick is (was?) to go backwards:
for(int i = l.size() - 1; i >= 0; i --) {
if (l.get(i) == 5) {
l.remove(i);
}
}
That said, I'm more than happy that you have better ways in Java 8, e.g. removeIf or filter on streams.
Same answer as Claudius with a for loop:
for (Iterator<Object> it = objects.iterator(); it.hasNext();) {
Object object = it.next();
if (test) {
it.remove();
}
}
With Eclipse Collections, the method removeIf defined on MutableCollection will work:
MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.lessThan(3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);
With Java 8 Lambda syntax this can be written as follows:
MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.cast(integer -> integer < 3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);
The call to Predicates.cast() is necessary here because a default removeIf method was added on the java.util.Collection interface in Java 8.
Note: I am a committer for Eclipse Collections.
Make a copy of existing list and iterate over new copy.
for (String str : new ArrayList<String>(listOfStr))
{
listOfStr.remove(/* object reference or index */);
}
People are asserting one can't remove from a Collection being iterated by a foreach loop. I just wanted to point out that is technically incorrect and describe exactly (I know the OP's question is so advanced as to obviate knowing this) the code behind that assumption:
for (TouchableObj obj : untouchedSet) { // <--- This is where ConcurrentModificationException strikes
if (obj.isTouched()) {
untouchedSet.remove(obj);
touchedSt.add(obj);
break; // this is key to avoiding returning to the foreach
}
}
It isn't that you can't remove from the iterated Colletion rather that you can't then continue iteration once you do. Hence the break in the code above.
Apologies if this answer is a somewhat specialist use-case and more suited to the original thread I arrived here from, that one is marked as a duplicate (despite this thread appearing more nuanced) of this and locked.
With a traditional for loop
ArrayList<String> myArray = new ArrayList<>();
for (int i = 0; i < myArray.size(); ) {
String text = myArray.get(i);
if (someCondition(text))
myArray.remove(i);
else
i++;
}
ConcurrentHashMap or ConcurrentLinkedQueue or ConcurrentSkipListMap may be another option, because they will never throw any ConcurrentModificationException, even if you remove or add item.
Another way is to use a copy of your arrayList just for iteration:
List<Object> l = ...
List<Object> iterationList = ImmutableList.copyOf(l);
for (Object curr : iterationList) {
if (condition(curr)) {
l.remove(curr);
}
}
A ListIterator allows you to add or remove items in the list. Suppose you have a list of Car objects:
List<Car> cars = ArrayList<>();
// add cars here...
for (ListIterator<Car> carIterator = cars.listIterator(); carIterator.hasNext(); )
{
if (<some-condition>)
{
carIterator().remove()
}
else if (<some-other-condition>)
{
carIterator().add(aNewCar);
}
}
Now, You can remove with the following code
l.removeIf(current -> current == 5);
I know this question is too old to be about Java 8, but for those using Java 8 you can easily use removeIf():
Collection<Integer> l = new ArrayList<Integer>();
for (int i=0; i < 10; ++i) {
l.add(new Integer(4));
l.add(new Integer(5));
l.add(new Integer(6));
}
l.removeIf(i -> i.intValue() == 5);
Java Concurrent Modification Exception
Single thread
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String value = iter.next()
if (value == "A") {
list.remove(it.next()); //throws ConcurrentModificationException
}
}
Solution: iterator remove() method
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String value = iter.next()
if (value == "A") {
it.remove()
}
}
Multi thread
copy/convert and iterate over another one collection. For small collections
synchronize[About]
thread safe collection[About]
I have a suggestion for the problem above. No need of secondary list or any extra time. Please find an example which would do the same stuff but in a different way.
//"list" is ArrayList<Object>
//"state" is some boolean variable, which when set to true, Object will be removed from the list
int index = 0;
while(index < list.size()) {
Object r = list.get(index);
if( state ) {
list.remove(index);
index = 0;
continue;
}
index += 1;
}
This would avoid the Concurrency Exception.
for (Integer i : l)
{
if (i.intValue() == 5){
itemsToRemove.add(i);
break;
}
}
The catch is the after removing the element from the list if you skip the internal iterator.next() call. it still works! Though I dont propose to write code like this it helps to understand the concept behind it :-)
Cheers!
Example of thread safe collection modification:
public class Example {
private final List<String> queue = Collections.synchronizedList(new ArrayList<String>());
public void removeFromQueue() {
synchronized (queue) {
Iterator<String> iterator = queue.iterator();
String string = iterator.next();
if (string.isEmpty()) {
iterator.remove();
}
}
}
}
I know this question assumes just a Collection, and not more specifically any List. But for those reading this question who are indeed working with a List reference, you can avoid ConcurrentModificationException with a while-loop (while modifying within it) instead if you want to avoid Iterator (either if you want to avoid it in general, or avoid it specifically to achieve a looping order different from start-to-end stopping at each element [which I believe is the only order Iterator itself can do]):
*Update: See comments below that clarify the analogous is also achievable with the traditional-for-loop.
final List<Integer> list = new ArrayList<>();
for(int i = 0; i < 10; ++i){
list.add(i);
}
int i = 1;
while(i < list.size()){
if(list.get(i) % 2 == 0){
list.remove(i++);
} else {
i += 2;
}
}
No ConcurrentModificationException from that code.
There we see looping not start at the beginning, and not stop at every element (which I believe Iterator itself can't do).
FWIW we also see get being called on list, which could not be done if its reference was just Collection (instead of the more specific List-type of Collection) - List interface includes get, but Collection interface does not. If not for that difference, then the list reference could instead be a Collection [and therefore technically this Answer would then be a direct Answer, instead of a tangential Answer].
FWIWW same code still works after modified to start at beginning at stop at every element (just like Iterator order):
final List<Integer> list = new ArrayList<>();
for(int i = 0; i < 10; ++i){
list.add(i);
}
int i = 0;
while(i < list.size()){
if(list.get(i) % 2 == 0){
list.remove(i);
} else {
++i;
}
}
One solution could be to rotate the list and remove the first element to avoid the ConcurrentModificationException or IndexOutOfBoundsException
int n = list.size();
for(int j=0;j<n;j++){
//you can also put a condition before remove
list.remove(0);
Collections.rotate(list, 1);
}
Collections.rotate(list, -1);
Try this one (removes all elements in the list that equal i):
for (Object i : l) {
if (condition(i)) {
l = (l.stream().filter((a) -> a != i)).collect(Collectors.toList());
}
}
You can use a while loop.
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
if(entry.getKey().equals("test")) {
iterator.remove();
}
}
I ended up with this ConcurrentModificationException, while iterating the list using stream().map() method. However the for(:) did not throw the exception while iterating and modifying the the list.
Here is code snippet , if its of help to anyone:
here I'm iterating on a ArrayList<BuildEntity> , and modifying it using the list.remove(obj)
for(BuildEntity build : uniqueBuildEntities){
if(build!=null){
if(isBuildCrashedWithErrors(build)){
log.info("The following build crashed with errors , will not be persisted -> \n{}"
,build.getBuildUrl());
uniqueBuildEntities.remove(build);
if (uniqueBuildEntities.isEmpty()) return EMPTY_LIST;
}
}
}
if(uniqueBuildEntities.size()>0) {
dbEntries.addAll(uniqueBuildEntities);
}
If using HashMap, in newer versions of Java (8+) you can select each of 3 options:
public class UserProfileEntity {
private String Code;
private String mobileNumber;
private LocalDateTime inputDT;
// getters and setters here
}
HashMap<String, UserProfileEntity> upMap = new HashMap<>();
// remove by value
upMap.values().removeIf(value -> !value.getCode().contains("0005"));
// remove by key
upMap.keySet().removeIf(key -> key.contentEquals("testUser"));
// remove by entry / key + value
upMap.entrySet().removeIf(entry -> (entry.getKey().endsWith("admin") || entry.getValue().getInputDT().isBefore(LocalDateTime.now().minusMinutes(3)));
The best way (recommended) is use of java.util.concurrent package. By
using this package you can easily avoid this exception. Refer
Modified Code:
public static void main(String[] args) {
Collection<Integer> l = new CopyOnWriteArrayList<Integer>();
for (int i=0; i < 10; ++i) {
l.add(new Integer(4));
l.add(new Integer(5));
l.add(new Integer(6));
}
for (Integer i : l) {
if (i.intValue() == 5) {
l.remove(i);
}
}
System.out.println(l);
}
Iterators are not always helpful when another thread also modifies the collection. I had tried many ways but then realized traversing the collection manually is much safer (backward for removal):
for (i in myList.size-1 downTo 0) {
myList.getOrNull(i)?.also {
if (it == 5)
myList.remove(it)
}
}
In case ArrayList:remove(int index)- if(index is last element's position) it avoids without System.arraycopy() and takes not time for this.
arraycopy time increases if(index decreases), by the way elements of list also decreases!
the best effective remove way is- removing its elements in descending order:
while(list.size()>0)list.remove(list.size()-1);//takes O(1)
while(list.size()>0)list.remove(0);//takes O(factorial(n))
//region prepare data
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Integer> toRemove = new ArrayList<Integer>();
Random rdm = new Random();
long millis;
for (int i = 0; i < 100000; i++) {
Integer integer = rdm.nextInt();
ints.add(integer);
}
ArrayList<Integer> intsForIndex = new ArrayList<Integer>(ints);
ArrayList<Integer> intsDescIndex = new ArrayList<Integer>(ints);
ArrayList<Integer> intsIterator = new ArrayList<Integer>(ints);
//endregion
// region for index
millis = System.currentTimeMillis();
for (int i = 0; i < intsForIndex.size(); i++)
if (intsForIndex.get(i) % 2 == 0) intsForIndex.remove(i--);
System.out.println(System.currentTimeMillis() - millis);
// endregion
// region for index desc
millis = System.currentTimeMillis();
for (int i = intsDescIndex.size() - 1; i >= 0; i--)
if (intsDescIndex.get(i) % 2 == 0) intsDescIndex.remove(i);
System.out.println(System.currentTimeMillis() - millis);
//endregion
// region iterator
millis = System.currentTimeMillis();
for (Iterator<Integer> iterator = intsIterator.iterator(); iterator.hasNext(); )
if (iterator.next() % 2 == 0) iterator.remove();
System.out.println(System.currentTimeMillis() - millis);
//endregion
for index loop: 1090 msec
for desc index: 519 msec---the best
for iterator: 1043 msec
you can also use Recursion
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.

Iterating over basic “for” loop using Handlebars.js

I’m new to Handlebars.js and just started using it. Most of the examples are based on iterating over an object. I wanted to know how to use handlebars in basic for loop.
Example.
for(i=0 ; i<100 ; i++) {
create li's with i as the value
}
How can this be achieved?
There's nothing in Handlebars for this but you can add your own helpers easily enough.
If you just wanted to do something n times then:
Handlebars.registerHelper('times', function(n, block) {
var accum = '';
for(var i = 0; i < n; ++i)
accum += block.fn(i);
return accum;
});
and
{{#times 10}}
<span>{{this}}</span>
{{/times}}
If you wanted a whole for(;;) loop, then something like this:
Handlebars.registerHelper('for', function(from, to, incr, block) {
var accum = '';
for(var i = from; i < to; i += incr)
accum += block.fn(i);
return accum;
});
and
{{#for 0 10 2}}
<span>{{this}}</span>
{{/for}}
Demo: http://jsfiddle.net/ambiguous/WNbrL/
Top answer here is good, if you want to use last / first / index though you could use the following
Handlebars.registerHelper('times', function(n, block) {
var accum = '';
for(var i = 0; i < n; ++i) {
block.data.index = i;
block.data.first = i === 0;
block.data.last = i === (n - 1);
accum += block.fn(this);
}
return accum;
});
and
{{#times 10}}
<span> {{#first}} {{#index}} {{#last}}</span>
{{/times}}
If you like CoffeeScript
Handlebars.registerHelper "times", (n, block) ->
(block.fn(i) for i in [0...n]).join("")
and
{{#times 10}}
<span>{{this}}</span>
{{/times}}
This snippet will take care of else block in case n comes as dynamic value, and provide #index optional context variable, it will keep the outer context of the execution as well.
/*
* Repeat given markup with given times
* provides #index for the repeated iteraction
*/
Handlebars.registerHelper("repeat", function (times, opts) {
var out = "";
var i;
var data = {};
if ( times ) {
for ( i = 0; i < times; i += 1 ) {
data.index = i;
out += opts.fn(this, {
data: data
});
}
} else {
out = opts.inverse(this);
}
return out;
});
Couple of years late, but there's now each available in Handlebars which allows you to iterate pretty easily over an array of items.
https://handlebarsjs.com/guide/builtin-helpers.html#each

How to Hold and Continue FOR-LOOP from the same spot

Hi guys I got a for/foreach loop the calls a function inside of it. The prolem is that the function being-called doesnt fininsh it's job before the loop goes over again/
Here is my code:
private function ziv(result:Array,fail:Object):void
{
var i:uint = result.length;
for each(var f:Object in result)
{
var item:Object = f;
notfriend=item;
FacebookDesktop.fqlQuery("SELECT uid1, uid2 FROM friend WHERE uid1 = me() AND uid2 = "+item.id,myfriends);
}
}
private function myfriends(result:Object,fail:Object):void
{
if (result.length != 0)
myfriend.addItem(notfriend);
}
As you can see i want to add an item (notfriend) in MYFRIENDS function, "notfriend" is defined inside the loop, but by the time "MYFRIENDS" function finish loading the item already changes to the next item even though i was originally refering to the previous item.
Is there a way to maybe hold the FORloop until "myfriends" function finish loading.
I wanted to use Eventlistener on "myfriends" function , but then what do i do to stop\hold the loop? all i know is BREAK-which destroyes the FOR-LOOP and CONTINUE-which continue the loop from the next iterate.
10x alot , im really braking my head here!
Maybe look at not using a for loop and do your loop manually (example below uses recursion)
ie
private var index=0;
private function processArray() {
proccessArrayItem(array[index])
}
private function proccessArrayItem(obj) {
//after complete then call function recursively
index++;
if (index<array.length) proccessArrayItem(array[index])
}
U can use recursive function in some cases
like
private function setZoom():void
{
var zoomLevel:Number = new Number(myPanel);
if(zoomLevel != 100)
{
if(zoomLevel < 100)
{
myPanel.zoomIN();
setZoom();
}
else
{
myPanel.zoomOUT();
setZoom();
}
}
}
but some cases we cant do that
by only one solution we can achieve by
using TimerFunctions
setTimeout() or callLater();

getCharIndexAtPoint() equivalent in Spark RichEditableText

I want to find a way to get the character index in a Spark based RichEditableText based on mouse x, y position.
The mx.controls.TextArea has a protected getCharIndexAtPoint() method but I can't find an equivalent of this in the Spark RichEditableText which is disappointing.
Any ideas or recommendations?
I can see why. seems RichEditableText uses FTE, while TextArea uses TextField, so you can just use TextField::getCharIndexAtPoint. you may just as well have no char at a point.
It's a long time since I've had a a look at FTE, but I think TextLine::getAtomIndexAtPoint would be a good start. Also, you should have a look at TLFTextField::getCharIndexAtPoint.
I was looking for a similar solution after the heads up from back2dos i came up with the following solution, probably needs a bit of work but it functions
http://www.justinpante.net/?p=201
Here's what I used:
private function getCharAtPoint(ta:RichEditableText, x:Number, y:Number) : int
{
var globalPoint:Point = ta.localToGlobal(new Point(x, y));
var flowComposer:IFlowComposer = ta.textFlow.flowComposer;
for (var i:int = 0; i < flowComposer.numLines; i++){
var textFlowLine:TextFlowLine = flowComposer.getLineAt(i);
if (y >= textFlowLine.y && y < textFlowLine.height + textFlowLine.y)
{
return textFlowLine.absoluteStart
+ textFlowLine.getTextLine(true)
.getAtomIndexAtPoint(globalPoint.x, globalPoint.y);
}
}
return -1;
}
I had the same problem. The answer Even Mien gave did not work for me, initially.
With the below changes I got it working.
var globalPoint:Point = new Point(stage.mouseX, stage.mouseY);
var flowComposer:IFlowComposer = this.textFlow.flowComposer;
for (var i:int = 0; i < flowComposer.numLines; i++)
{
var textFlowLine:TextFlowLine = flowComposer.getLineAt(i);
var textLine:TextLine = textFlowLine.getTextLine(true);
var textRect:Rectangle = textLine.getRect(stage);
if (globalPoint.y >= textRect.top && globalPoint.y < textRect.bottom)
{
return textFlowLine.absoluteStart + textLine.getAtomIndexAtPoint(globalPoint.x, globalPoint.y);
}
}
return 0;

Categories

Resources