Wednesday, 16 October 2013

jQuery check if element is visible or hidden

Useful jQuery toggle visibility methods.

Or you may check if element is visible or hidden with jQuery. Hide or show it according to its visibility.
Test code:
html:
<div class="wrap-js-action"><span class="click js-action">click to show or hide (display:block|none;)</span></div>
<div class="target">target</div>
 
<div class="wrap-js-action"><span class="click-toggle js-action">click to show or hide by toggle (display:block|none;)</span></div>
<div class="target-toggle">target-toggle</div>
 
<div class="wrap-js-action"><span class="click-visibility js-action">click to show or hide (visibility:hidden|visible)</span></div>
<div class="target-visibility">target visibility</div>
 
<div class="wrap-js-action"><span class="click-opacity js-action">click to show or hide (opacity:0|1)</span></div>
<div class="target-opacity">target opacity</div>
 
<div>last line</div>
jQuery:
$('.click').click(function() {
    if ($('.target').is(':hidden')) {
        $('.target').show();
    } else {
        $('.target').hide();
    }
});
 
 
$('.click-toggle').click(function() {
    $('.target-toggle').toggle();
});
 
$('.click-visibility').click(function() {
    if ($('.target-visibility').css('visibility') == 'hidden'){
        $('.target-visibility').css({'visibility': 'visible', display: ''});
    }else{
        $('.target-visibility').css({'visibility': 'hidden', display: ''});
    }
});
 
$('.click-opacity').click(function() {
    if ($('.target-opacity').css('opacity') == '0'){
        $('.target-opacity').css({'opacity': '1', display: ''});
    }else{
        $('.target-opacity').css({'opacity': '0', display: ''});
    }
});
​​
.js-action {
    cursor: pointer;
    border-bottom:1px dashed #555;
}

.wrap-js-action {
    margin:15px 0 0 0;
}
Difference between "display:none", "visibility:hidden" and "opacity:0":
  • display:none hides the element and it does not take up any space;
  • visibility:hidden hides the element, but it still takes up space in the layout;
  • opacity:0 hides the element as "visibility:hidden" and it still takes up space in the layout; the only difference is that opacity let to do element partly transparent;
Another difference between visibility:hidden and opacity:0 is that the element will still respond to events (like clicks) with opacity:0.

Friday, 4 October 2013

Using Callable to Return Results From Runnables

The Runnable interface has been around since the beginning of time for the Java platform. It allows you to define a task to be completed by a thread. As most people probably know already, it offers a single method run() that accepts no arguments and returns no values, nor can it throw any checked exceptions. If you need to get a value back from the now-completed task, you must use a method outside the interface and wait for some kind of notification message that the task completed. For example, the following demonstrates what you might do for just such a scenario:
  Runnable runnable = ...;
  Thread t = new Thread(runnable);
  t.start();
  t.join();
  String value = someMethodtoGetSavedValue()
Nothing is inherently wrong with this code, but it can be done differently now, thanks to the Callable interface introduced in J2SE 5.0. Instead of having a run() method, the Callable interface offers a call() method, which can return an Object or, more specifically, any type that is introduced in the genericized form:
  public interface Callable<V> {
     V call() throws Exception;
  }
Because you cannot pass a Callable into a Thread to execute, you instead use the ExecutorService to execute the Callable object. The service accepts Callable objects to run by way of the submit() method:
  <T> Future<T> submit(Callable<T> task)
As the method definition shows, submitting a Callable object to the ExecutorService returns a Future object. Theget() method of Future will then block until the task is completed. This is the equivalent of the join() call in the first example. Actually, it is the equivalent of both the join() call and the get value call as get() returns the value calculated by the Callable instance.
To demonstrate, the following example creates separate Callable instances for each word passed in on the command line and sums up their length. Each Callable will just calculate the sum of its individual word. The set ofFuture objects are saved to acquire the calculated value from each. If the order of the returned values needed to be preserved, a List could be used instead.
import java.util.\*;
import java.util.concurrent.\*;

public class CallableExample {

  public static class WordLengthCallable
        implements Callable {
    private String word;
    public WordLengthCallable(String word) {
      this.word = word;
    }
    public Integer call() {
      return Integer.valueOf(word.length());
    }
  }

  public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<Future≶Integer>>();
    for (String word: args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }
    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }
    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
  }
}
The WordLengthCallable saves each word and uses the word's length as the value returned by the call()method. This value could take some time to generate but in this case is known immediately. The only requirement ofcall() is the value is returned at the end of the call. When the get() method of Future is later called, the Futurewill either have the value immediately if the task runs quickly, as in this case, or will wait until the value is done generating. Multiple calls to get() will not cause the task to be rerun in the thread.
Because the goal of the program is to calculate the sum of all word lengths, it doesn't matter in which order theCallable tasks finish. It is perfectly OK if the last task completes before the first three. The first get() call to Futurewill just wait for the first task in the Set to complete. This does not block other tasks from running to completion separately. It is just waiting for that one thread or task to complete.

Daemon Threads

A “daemon” thread is one that is supposed to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the non-daemon threads complete, the program is terminated. Conversely, if there are any non-daemon threads still running, the program doesn’t terminate. There is, for instance, a non-daemon thread that runs main( ).
//: c13:SimpleDaemons.java
// Daemon threads don't prevent the program from ending.

public class SimpleDaemons extends Thread {
  public SimpleDaemons() {
    setDaemon(true); // Must be called before start()
    start();
  }
  public void run() {
    while(true) {
      try {
        sleep(100);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      System.out.println(this);
    }
  }
  public static void main(String[] args) {
    for(int i = 0; i < 10; i++)
      new SimpleDaemons();
  }
} ///:~

You must set the thread to be a daemon by calling setDaemon( ) before it is started. In run( ), the thread is put to sleep for a little bit. Once the threads are all started, the program terminates immediately, before any threads can print themselves, because there are no non-daemon threads (other than main( )) holding the program open. Thus, the program terminates without printing any output.
You can find out if a thread is a daemon by calling isDaemon( ). If a thread is a daemon, then any threads it creates will automatically be daemons, as the following example demonstrates:
//: c13:Daemons.java
// Daemon threads spawn other daemon threads.
import java.io.*;
import com.bruceeckel.simpletest.*;

class Daemon extends Thread {
  private Thread[] t = new Thread[10];
  public Daemon() {
    setDaemon(true);
    start();
  }
  public void run() {
    for(int i = 0; i < t.length; i++)
      t[i] = new DaemonSpawn(i);
    for(int i = 0; i < t.length; i++)
      System.out.println("t[" + i + "].isDaemon() = "
        + t[i].isDaemon());
    while(true)
      yield();
  }
}

class DaemonSpawn extends Thread {
  public DaemonSpawn(int i) {
    start();
    System.out.println("DaemonSpawn " + i + " started");
  }
  public void run() {
    while(true)
      yield();
  }
}

public class Daemons {
  private static Test monitor = new Test();
  public static void main(String[] args) throws Exception {
    Thread d = new Daemon();
    System.out.println("d.isDaemon() = " + d.isDaemon());
    // Allow the daemon threads to
    // finish their startup processes:
    Thread.sleep(1000);
    monitor.expect(new String[] {
      "d.isDaemon() = true",
      "DaemonSpawn 0 started",
      "DaemonSpawn 1 started",
      "DaemonSpawn 2 started",
      "DaemonSpawn 3 started",
      "DaemonSpawn 4 started",
      "DaemonSpawn 5 started",
      "DaemonSpawn 6 started",
      "DaemonSpawn 7 started",
      "DaemonSpawn 8 started",
      "DaemonSpawn 9 started",
      "t[0].isDaemon() = true",
      "t[1].isDaemon() = true",
      "t[2].isDaemon() = true",
      "t[3].isDaemon() = true",
      "t[4].isDaemon() = true",
      "t[5].isDaemon() = true",
      "t[6].isDaemon() = true",
      "t[7].isDaemon() = true",
      "t[8].isDaemon() = true",
      "t[9].isDaemon() = true"
    }, Test.IGNORE_ORDER + Test.WAIT);
  }
} ///:~

The Daemon thread sets its daemon flag to “true” and then spawns a bunch of other threads—which do not set themselves to daemon mode—to show that they are daemons anyway. Then it goes into an infinite loop that calls yield( ) to give up control to the other processes.
There’s nothing to keep the program from terminating once main( ) finishes its job, since there are nothing but daemon threads running. So that you can see the results of starting all the daemon threads, the main( ) thread is put to sleep for a second. Without this, you see only some of the results from the creation of the daemon threads. (Try sleep( ) calls of various lengths to see this behavior.)

Thursday, 3 October 2013

Bubble Sort

Bubble Sort
Pseudocode and Flowchart

BubbleSort( int a[], int n)

Begin
 for i = 1 to n-1
  sorted = true
       for j = 0 to n-1-i
                 if a[j] > a[j+1]
                 temp = a[j]
                 a[j] = a[j+1]
                 a[j+1] = temp
           sorted = false
        end for
       if sorted
         break from i loop
 end for
End


Bubble sort uses a loop (inside j loop) to travel thru’ an array comparing adjacent
values as it moves along. If an array element a[j] is greater than the element
immediately to its right a[j+1], it swaps them. The first time around, this process will
move or bubble the largest value to the end of the array. So for instance

5 3 1 9 8 2 4 7
will end up as
3 1 5 8 2 4 7 9


This process is repeated, on the second iteration, the second largest value will be
moved to the second last array position and so on.

In all, the bubble process (inside j loop) is repeated n-1 times for an array of size n.

Note for array of size 8, outside i loop repeats 7 times.
Complexity
Clearly for an array of size n, the outside loop repeats n-1 times.

To begin with the inside loop does n-1 comparisons, next time n-2 and so on. Finally
on the last iteration of the outside loop, the inside loop does 1 comparison. So on
average the inside loop does ((n-1) + 1) / 2 ≈ n/2 comparisons.

Therefore, the overall number of computation steps is n * n/2 = n2/2

Complexity of bubble sort = O(n2)

Wednesday, 2 October 2013

Examples from Java I/O, 2nd Edition

The complete set of examples is also available for anonymous from ftp://ftp.ibiblio.org/pub/languages/java/javafaq/ioexamples2.zip 

Please feel free to use any fragment of this code you need in your own work. As far as I am concerned, it's in the public domain. No permission is necessary or required. Credit is always appreciated if you use a large chunk or base a significant product on one of my examples, but that's not required either.

How would I do $push using MongoRepository in Spring Data?

Yes, you must implement a custom method on the repository and your push method would be something like this :


public class FooRepositoryImpl implements
    AppointmentWarehouseRepositoryCustom {

    @Autowired
    protected MongoTemplate mongoTemplate;

    public void pushMethod(String objectId, Object... events) {
        mongoTemplate.updateFirst(
            Query.query(Criteria.where("id").is(objectId)), 
            new Update().pushAll("events", events), Foo.class);
    }
}
You can do this but I ran into an issue where the "_class" field wasn't being preserved. 
The pushed object itself was run through the configured converter but for some reason the "_class" field of that pushed object wasn't written. 
However, if I injected the converter and wrote the object to a DBObject myself, then the "_class" field was preserved and written. The thus becomes:

public class FooRepositoryImpl implements
AppointmentWarehouseRepositoryCustom {

@Autowired
protected MongoTemplate mongoTemplate;

public void pushMethod(String objectId, Object event) {
    DBObject eventObj = new BasicDBObject();
    converter.write(event, eventObj);
    mongoTemplate.updateFirst(
        Query.query(Criteria.where("id").is(objectId)), 
        new Update().push("events", eventObj), Foo.class);
  }
}

Flip in image in JavaFX


For Flip Horizontal

You can do this by setting the scaleX variable of the ImageView to -1.

For Flip Vertical

You can do this by setting the scaleY variable of the ImageView to -1.