What is the purpose of Looper and how to use it?

Question: I am new to Android. I want to know what the Looper class does and also how to use it. I have read the Android Looper class documentation but I am unable to completely understand it.
I have seen it in a lot of places but unable to understand its purpose. Can anyone help me by defining the purpose of Looper and also by giving a simple example if possible?
Comment: I just found an extraordinarily thorough and clear explanation of Looper and its use on Safari Books Online. Unfortunately, I suspect access if free for only a limited time. https://www.safaribooksonline.com/library/view/efficient-android-threading/9781449364120/ch04.html
Comment: Android articles and reference pages require you to have and understanding of a previous article , before you can grasp the current one. I suggest you read the Activity and Service articles in the Api guides , and then read Handler and Looper. It also helps if you have an understanding of what a thread is(not an android thread, but a thread in general...e.g. POSIX).
Comment: I found this article useful: http://codetheory.in/android-handlers-runnables-loopers-messagequeue-handlerthread/
Comment: Creates an infinite loop for the thread to execute through so thread can check a task queue on each iteration, and execute the task. The task is called a message. This is a common design pattern called an event loop, just abstracted. If more than one thread share an event loop, you have a thread pool. Main thread must have the loop by default because is a non terminating thread that waits for ui event tasks. Other non terminating types of programs like video games have the event loop. Plain old threads do not have the loop, but can be added with looper api.
Comment: @JoeLapp It is year 2023 now and your [O'reilly Chapter 4. Thread Communication](https://www.oreilly.com/library/view/efficient-android-threading/9781449364120/ch04.html) link still works! Amazing.
Comment: @JoeLapp thanks for the link, I am trying to understand the code, and I believe the line: `while(Thread.currentThread().isInterrupted()){` inside `class TextHandlerTask` should be inverted for it to loop as in: `while(!Thread.currentThread().isInterrupted()){`, this means that it will reattempt reading UNTIL the thread gets interrupted, Am I getting this right?
Answer: What is Looper?
Looper is a class which is used to execute the Messages(Runnables) in a queue. Normal threads have no such queue, e.g. simple thread does not have any queue. It executes once and after method execution finishes, the thread will not run another Message(Runnable).
Where we can use Looper class?
If someone wants to execute multiple messages(Runnables) then he should use the Looper class which is responsible for creating a queue in the thread.
For example, while writing an application that downloads files from the internet, we can use Looper class to put files to be downloaded in the queue.
How it works?
There is prepare() method to prepare the Looper. Then you can use loop() method to create a message loop in the current thread and now your Looper is ready to execute the requests in the queue until you quit the loop.
Here is the code by which you can prepare the Looper.
class LooperThread extends Thread {
      public Handler mHandler;

      @Override
      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              @Override
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

Comment: An AsyncTask is better for that purpose and less complex as it encapsulates all the thread managing.
Comment: I think it would be better to use [HandlerThread](http://developer.android.com/reference/android/os/HandlerThread.html) which is a convenient class for a thread with a looper.
Comment: The documentation indicates that you must call looper.quit. In your code above, Looper.loop will block indefinitely.
Comment: Should have @Override annotations before the run() and handleMessage() methods
Comment: How to quit a loop. I mean where to include Looper.quit() in the above code example?
Comment: This doesn't explain why one would use this class, only how.
Comment: Amazing...Does anyone understand how to send message to LooperThread? Its totally unuseful example. Everyone just copied stupid example from documentation.
Comment: So looper could be used to update the main thread with lets say... a download percentage (10%, 20%, 30% ... etc). Essentially feedback which you could feed into a progressbar?
Comment: As we are overriding these method it should @override above these run and handleMessage methods
Comment: I'm confused, how to you get Looper.loop() to not block? Why would you call Looper.Quit() if you want the message loop for the thread to run?
Comment: As far as I know you can call Looper.myLooper().quit(); to quite the current lopper loop. You can call this method when you got particular message in handleMessage method.
Comment: Calling quit  is optional depending on  use case.
Comment: Andi; you would quit after processing messages so could then dedicate that thread to post monitoring duty for example. Eg thread sits there waiting for async seeds to arrive.  When has them quit monitoring and do some work on that same thread.
Comment: How to quit looper is simple just  call the quit method of the called Thread in  onDestroy(). mWorkerThread.quit()  will check it has looper or not and will be terminated. Javadoc:  "Causes the handler thread's looper to terminate without processing any more messages in the message queue"
Comment: @Andromeda Does `Looper.quit()`scope be available in `onDestroy()`  method?
Comment: @– rkm_Hodor  while onDestroy, just call the yourThread.quit()  method it will handle the looper inside of this. But this is valid for HandlerThreads which handle looper staff instead of you.  If you create your own thread and own Looper implementation you should handle with your looper by simply adding quit() method to your thread.   public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }
Answer: You can better understand what Looper is in the context of the GUI framework. Looper is made to do 2 things.

Looper transforms a normal thread into something run continuously until Android app is running.

Looper provides a queue where jobs to be done are enqueued.

As you may know, when an application is launched, the system creates a thread of execution for the application, called "main", and Android applications normally run entirely on a single thread by default the "main thread". But main thread is not a secret, special thread. It's just a normal thread similar to one you can create with new Thread(), which means it terminates when its run() method returns! Think of below example.
public class HelloRunnable implements Runnable {
    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }
}

Now, let's apply this simple principle to Android apps. What would happen if an Android app runs on a normal thread? A thread called "main" or "UI" or whatever starts your application and draws all UI. So the first screen is displayed to users. What now? The main thread terminates? No, it shouldn't. It should wait until users do something, right? But how can we achieve this behavior? Well, we can try with Object.wait() or Thread.sleep(). For example, main thread finishes its initial job to display first screen, and sleeps. It awakes, which means interrupted, when a new job to do is fetched. So far so good, but at this moment we need a queue-like data structure to hold multiple jobs. Think about a case when a user touches screen serially, and a task takes longer time to finish. So, we need to have a data structure to hold jobs to be done in first-in-first-out manner. Also, you may imagine, implementing ever-running-and-process-job-when-arrived thread using interrupt is not easy, and leads to complex and often unmaintainable code. We'd rather create a new mechanism for such purpose, and that is what Looper is all about. The official document of Looper class says, "Threads by default do not have a message loop associated with them", and Looper is a class "used to run a message loop for a thread". Now you can understand what it means.
To make things more clear, let's check the code where the main thread is transformed. It all happens in ActivityThread class. In its main() method, you can find below code, which turns a normal thread into something that we need.
public final class ActivityThread {
    ...
    public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
        Looper.loop();
        ...
    }
}

and Looper.loop() method loop infinitely and dequeue a message and process one at a time:
public static void loop() {
    ...
    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        ...
        msg.target.dispatchMessage(msg);
        ...
    }
}

So, basically, Looper is a class that is made to address a problem that occurs in the GUI framework. But this kind of need can also happen in other situations as well. Actually, it is a pretty famous pattern for multi-thread applications, and you can learn more about it in "Concurrent Programming in Java" by Doug Lea(Especially, chapter 4.1.4 "Worker Threads" would be helpful). Also, you can imagine this kind of mechanism is not unique in Android framework, but all GUI framework may need somewhat similar. You can find almost same mechanism in Java Swing framework too.
Comment: Quick question. You stated that in the main thread after it draws out all of the UI elements it is put to sleep. But let's say the user interacts with a button on the screen, isn't that button click even put into a main queue, then some object will dispatch it to the correct activity, then the main thread for that activity is awake and it will execute the code for in the callback for that button click?
Answer: Looper allows tasks to be executed sequentially on a single thread. And handler defines those tasks that we need to be executed. It is a typical scenario that I am trying to illustrate in this example:
class SampleLooper extends Thread {
@Override
public void run() {
  try {
    // preparing a looper on current thread
    // the current thread is being detected implicitly
    Looper.prepare();

    // now, the handler will automatically bind to the
    // Looper that is attached to the current thread
    // You don't need to specify the Looper explicitly
    handler = new Handler();

    // After the following line the thread will start
    // running the message loop and will not normally
    // exit the loop unless a problem happens or you
    // quit() the looper (see below)
    Looper.loop();
  } catch (Throwable t) {
    Log.e(TAG, "halted due to an error", t);
  }
}
}

Now we can use the handler in some other threads(say ui thread) to post the task on Looper to execute.
handler.post(new Runnable()
{
public void run() {
//This will be executed on thread using Looper.
    }
});

On UI thread we have an implicit Looper that allow us to handle the messages on ui thread.
Comment: Thanks for including sample on how to post "jobs" to the queue
Comment: This doesn't explain why one would use this class, only how.
Comment: it will not lock any UI Process, is it true?
Comment: Is SampleLooper inner class?
Answer: Android Looper is a wrapper to attach MessageQueue to Thread and it manages Queue processing. It looks very cryptic in Android documentation and many times we may face Looper related UI access issues. If we don't understand the basics it becomes very tough to handle.
Here is an article which explains Looper life cycle, how to use it and usage of Looper in Handler

Looper = Thread + MessageQueue
Comment: This doesn't explain why one would use this class, only how.
Comment: @AndrewKoster Thanks for explaining this. Do you know whether there is an upper limit to number of Looper instances in an Android app?
Comment: @AndrewKoster IMHO it addresses the "why" by *"to attach MessageQueue to Thread*".
Comment: @WebViewer The answer from 김준호 has a much more complete explanation. Attaching a MessageQueue to a Thread isn't a useful end goal, so it doesn't really get us much closer to answering "why". The answer from 김준호 gets into the use cases, and the use cases are the actual reason to use the class.
Answer: Simplest Definition of Looper & Handler:
Looper is a class that turns a thread into a Pipeline Thread and Handler gives you a mechanism to push tasks into this pipe from any other threads.
Details in general wording:
So a PipeLine Thread is a thread which can accept more tasks from other threads through a Handler.
The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because it is used to handle or accept that next task each time from any other thread and pass to Looper (Thread or PipeLine Thread).
Example:
A Looper and Handler or PipeLine Thread's very perfect example is to download more than one images or upload them to a server (Http) one by one in a single thread instead of starting a new Thread for each network call in the background.
Read more here about Looper and Handler and the definition of Pipeline Thread:
Android Guts: Intro to Loopers and Handlers
Answer: Understanding Looper Threads
A java Thread a unit of execution which was designed to perform a task in its run() method  & terminate after that:

But in Android there are many use cases where we need to keep a Thread alive and wait for user inputs/events for eg. UI thread aka Main Thread.
Main thread  in Android is a Java thread which is first started by JVM at the launch of an app and keeps on running till the user choose to close it or encounters unhandled exception.

When an application is launched, the system creates a thread of
  execution for the application, called "main." This thread is very
  important because it is in charge of dispatching events to the
  appropriate user interface widgets, including drawing events.

Now point to note here is although main thread is Java thread yet it keeps on listening to user events and draw 60 fps frames on screen and still it wont die after each cycle. how is it so?

The answer is Looper Class: Looper is a class which is used to keep a thread alive and manage a message queue to execute tasks on
  that thread.

Threads by default do not have a message loop associated with them but you can assign one by calling  Looper.prepare() in the run method and then call the Looper.loop().

Purpose of Looper is to keep a Thread alive and wait for next cycle of
  input Message object to perform computation which otherwise will get
  destroyed after first cycle of execution.

If you want to dig deeper how Looper manage Message object queue then you can have a look at source code of Looperclass:

https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/os/Looper.java

Below is an example of how you can create a Looper Thread and communicate with Activity class using LocalBroadcast
class LooperThread : Thread() {

    // sendMessage success result on UI
    private fun sendServerResult(result: String) {
        val resultIntent = Intent(ServerService.ACTION)
        resultIntent.putExtra(ServerService.RESULT_CODE, Activity.RESULT_OK)
        resultIntent.putExtra(ServerService.RESULT_VALUE, result)
        LocalBroadcastManager.getInstance(AppController.getAppController()).sendBroadcast(resultIntent)
    }

    override fun run() {
        val looperIsNotPreparedInCurrentThread = Looper.myLooper() == null

        // Prepare Looper if not already prepared
        if (looperIsNotPreparedInCurrentThread) {
            Looper.prepare()
        }

        // Create a handler to handle messaged from Activity
        handler = Handler(Handler.Callback { message ->
            // Messages sent to Looper thread will be visible here
            Log.e(TAG, "Received Message" + message.data.toString())

            //message from Activity
            val result = message.data.getString(MainActivity.BUNDLE_KEY)

            // Send Result Back to activity
            sendServerResult(result)
            true
        })

        // Keep on looping till new messages arrive
        if (looperIsNotPreparedInCurrentThread) {
            Looper.loop()
        }
    }

    //Create and send a new  message to looper
    fun sendMessage(messageToSend: String) {
        //Create and post a new message to handler
        handler!!.sendMessage(createMessage(messageToSend))
    }

    // Bundle Data in message object
    private fun createMessage(messageToSend: String): Message {
        val message = Message()
        val bundle = Bundle()
        bundle.putString(MainActivity.BUNDLE_KEY, messageToSend)
        message.data = bundle
        return message
    }

    companion object {
        var handler: Handler? = null // in Android Handler should be static or leaks might occur
        private val TAG = javaClass.simpleName

    }
}

Usage:
 class MainActivity : AppCompatActivity() {

    private var looperThread: LooperThread? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // start looper thread
        startLooperThread()

        // Send messages to Looper Thread
        sendMessage.setOnClickListener {

            // send random messages to looper thread
            val messageToSend = "" + Math.random()

            // post message
            looperThread!!.sendMessage(messageToSend)

        }
    }

    override fun onResume() {
        super.onResume()

        //Register to Server Service callback
        val filterServer = IntentFilter(ServerService.ACTION)
        LocalBroadcastManager.getInstance(this).registerReceiver(serverReceiver, filterServer)

    }

    override fun onPause() {
        super.onPause()

        //Stop Server service callbacks
     LocalBroadcastManager.getInstance(this).unregisterReceiver(serverReceiver)
    }

    // Define the callback for what to do when data is received
    private val serverReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val resultCode = intent.getIntExtra(ServerService.RESULT_CODE, Activity.RESULT_CANCELED)
            if (resultCode == Activity.RESULT_OK) {
                val resultValue = intent.getStringExtra(ServerService.RESULT_VALUE)
                Log.e(MainActivity.TAG, "Server result : $resultValue")

                serverOutput.text =
                        (serverOutput.text.toString()
                                + "\n"
                                + "Received : " + resultValue)

                serverScrollView.post( { serverScrollView.fullScroll(View.FOCUS_DOWN) })
            }
        }
    }

    private fun startLooperThread() {

        // create and start a new LooperThread
        looperThread = LooperThread()
        looperThread!!.name = "Main Looper Thread"
        looperThread!!.start()

    }

    companion object {
        val BUNDLE_KEY = "handlerMsgBundle"
        private val TAG = javaClass.simpleName
    }
}

Can we use Async task or Intent Services instead?

Async tasks are designed to perform a short operation in background and give progres & results on UI thread. Async tasks have limits like you cant create more than 128 Async tasks and ThreadPoolExecutor will allow only upto 5 Async tasks.
IntentServices are also designed to do background task for a little longer duration and you can use LocalBroadcast to communicate with Activity. But services get destroyed after task execution. If you want to keep it running for a long time than you need to do hecks like  while(true){...}.

Other meaningful use cases for Looper Thread:

Used for 2 way socket communication where server keep on listening to Client socket and write back acknowledgment
Bitmap processing in background. Pass the image url to Looper thread and it will apply filter effects and store it in tempe rory location and then  broadcast temp path of image.
Answer: A Looper has a synchronized MessageQueue that's used to process Messages placed on the queue.
It implements a Thread Specific Storage Pattern.
Only one Looper per Thread. Key methods include prepare(),loop() and quit().
prepare() initializes the current Thread as a Looper. prepare() is static method that uses the ThreadLocal class as shown below.
   public static void prepare(){
       ...
       sThreadLocal.set
       (new Looper());
   }

prepare() must be called explicitly before running the event loop.
loop() runs the event loop which waits for Messages to arrive on a specific Thread's messagequeue. Once the next Message is received,the loop() method dispatches the Message to its target handler
quit() shuts down the event loop. It doesn't terminate the loop,but instead it enqueues a special message

Looper can be programmed in a Thread via several steps

Extend Thread
Call Looper.prepare() to initialize Thread as a Looper
Create one or more Handler(s) to process the incoming messages
Call Looper.loop() to process messages until the loop is told to quit().
Answer: Life span of java Thread is over after completion of run() method. Same thread can't be started again.
Looper transforms normal Thread into a message loop. Key methods of Looper are :
void prepare ()

Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().

void loop ()

Run the message queue in this thread. Be sure to call quit() to end the loop.

void quit()

Quits the looper.
Causes the loop() method to terminate without processing any more messages in the message queue.

This mindorks article by Janishar explains the core concepts in nice way.

Looper is associated with a Thread. If you need Looper on UI thread, Looper.getMainLooper() will return associated thread.
You need Looper to be associated with a Handler.
Looper, Handler, and HandlerThread are the Android's way of solving the problems of asynchronous programming.
Once you have Handler, you can call below APIs.
post (Runnable r)

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

boolean sendMessage (Message msg)

Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.

HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes
In some scenarios, you can't run Runnable tasks on UI Thread.
e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream
In these cases, HandlerThread is useful. You can get Looper object from HandlerThread and create a Handler on HandlerThread instead of main thread.
The HandlerThread code will be like this:
@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

Refer to below post for example code:
Android: Toast in a thread
Answer: This answer has nothing to do with the question, but the use of looper and the way people created the handler and looper in ALL the answers here are plain bad practice (some explanations are correct though), I have to post this:
HandlerThread thread = new HandlerThread(threadName);
thread.start();
Looper looper = thread.getLooper();
Handler myHandler = new Handler(looper);

and for a full implementation
Answer:
What is Looper?

FROM DOCS
Looper
Looper Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

A Looper is a message handling loop:
An important character of Looper is that it's associated with the thread within which the Looper is created
The Looper class maintains a MessageQueue, which contains a list messages. An important character of Looper is that it's associated with the thread within which the Looper is created.
The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because someone could not invent a better name
Android Looper is a Java class within the Android user interface that together with the Handler class to process UI events such as button clicks, screen redraws and orientation switches.

How it works?

Creating Looper

A thread gets a Looper and MessageQueue by calling Looper.prepare() after its running. Looper.prepare() identifies the calling thread, creates a Looper and MessageQueue object and associate the thread
SAMPLE CODE
class MyLooperThread extends Thread {

      public Handler mHandler;

      public void run() {

          // preparing a looper on current thread
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                 // process incoming messages here
                 // this will run in non-ui/background thread
              }
          };

          Looper.loop();
      }
  }

For more information check below post

What is the relationship between Looper, Handler and MessageQueue in Android?
Android Guts: Intro to Loopers and Handlers
Understanding Android Core: Looper, Handler, and HandlerThread
Handler in Android
What Is Android Looper?
Android: Looper, Handler, HandlerThread. Part I.
MessageQueue and Looper in Android
Answer: Handling multiple down or upload items in a Service is a better example.
Handler and AsnycTask are often used to propagate Events/Messages between the UI (thread) and a worker thread or to delay actions. So they are more related  to UI.
A Looper handles tasks (Runnables, Futures) in a thread related queue in the background - even with no user interaction or a displayed UI (app downloads a file in the background during a call).
Answer: I will try to explain the purpose of looper class as simple as possible.
With a normal thread of Java when the run method completes the execution we say the thread has done it's job and thread lives no longer after that.
what if we want to execute more tasks throughout our program with that same thread which is not living anymore?
Oh there is a problem now right? Yes because we want to execute more tasks but the thread in not alive anymore. It is where the Looper comes in to rescue us.
Looper as the name suggests loops. Looper is nothing more than an infinite loop inside your thread. So, it keeps the thread alive for an infinite time until we explicitly calls quit() method. Calling quit() method on the infinitely alive thread will make the condition false in the infinite loop inside the thread thus, infinite loop will exit. so, the thread will die or will no longer be alive. And it's critical to call the quit() method on our Thread to which looper is attached otherwise they will be there in your system just like Zombies.
So, for example if we want to create a background thread to do some multiple tasks over it. we will create a simple Java's thread and will use Looper class to prepare a looper and attach the prepared looper with that thread so that our thread can live as longer as we want them because we can always call quit() anytime whenever we want to terminate our thread. So our the looper will keep our thread alive thus we will be able to execute multiple tasks with the same thread and when we are done we will call quit() to terminate the thread.
What if we want our Main thread or UI thread to display the results computed by the background thread or non-UI thread on some UI elements?
for that purpose there comes in the concept of Handlers;
via handlers we can do inter-process communication or say via handlers two threads can communicate with each other.
So, the main thread will have an associated Handler and Background thread will communicate with Main Thread via that handler to get the task done of displaying the results computed by it on some UI elements on Main thread.
I know I am explaining only theory here but try to understand the concept because understanding the concept in depth is very important. And I am posting a link below which will take you to a small video series about Looper, Handler and HandlerThread and I will highly recommend watching it and all these concepts will get cleared with examples there.
https://www.youtube.com/watch?v=rfLMwbOKLRk&list=PL6nth5sRD25hVezlyqlBO9dafKMc5fAU2&index=1
Answer: I try to give an example in Kotlin. Here is below the code example.
Firstly we need to instantiate variable handler from the Handler(the provided looper instead of the default one) which ask for mainthread (Looper.getMainLooper()).
The function getAllCourses() need to return LiveData so we use handler.postDelayed() to be added to the message queque and run after x amount of millisecond specified in constant SERVICE_LATENCY_IN_MILLIS.
Please feel free to elaborate more wording to my explanation to give more clarity.
class RemoteDataSource private constructor(private val jsonHelper: JsonHelper) {

    private val handler = Handler(Looper.getMainLooper())

    companion object {
        private const val SERVICE_LATENCY_IN_MILLIS: Long = 2000

        @Volatile
        private var instance: RemoteDataSource? = null

        fun getInstance(helper: JsonHelper): RemoteDataSource =
                instance ?: synchronized(this) {
                    RemoteDataSource(helper).apply { instance = this }
                }
    }

    fun getAllCourses(): LiveData<ApiResponse<List<CourseResponse>>> {
        EspressoIdlingResource.increment()
        val resultCourse = MutableLiveData<ApiResponse<List<CourseResponse>>>()
        handler.postDelayed({
            resultCourse.value = ApiResponse.success(jsonHelper.loadCourses())
            EspressoIdlingResource.decrement()
        }, SERVICE_LATENCY_IN_MILLIS)
        return resultCourse
    }

Answer: The official way to use the Looper is in the documentation and doesn't use the deprecated Handler CTOR that has no parameters :
https://developer.android.com/reference/android/os/Looper
  class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler(Looper.myLooper()) {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

Here's an improved version of it in Kotlin that I've made:
open class LooperThread : Thread() {
    @Volatile
    var handler: Handler? = null
        private set

    @WorkerThread
    override fun run() {
        Looper.prepare()
        handler = object : Handler(Looper.myLooper()!!) {
            fun handleMessage(msg: Message?) {
                email@example.com(msg!!)
            }

        }
        Looper.loop()
    }

    @WorkerThread
    open fun handleMessage(msg: Message) {
    }

    /**stops handling messages for the looper, so it can be released
     * @param quitSafely whether to use Looper.quitSafely (wait for normal messages) or Looper.quit (ditch all pending messages):
     * https://developer.android.com/reference/android/os/Looper#quitSafely()
     * https://developer.android.com/reference/android/os/Looper#quit()*/
    fun quit(quitSafely: Boolean) {
        handler?.let { handler ->
            if (quitSafely)
                handler.looper.quitSafely()
            else handler.looper.quit()
            email@example.com = null
        }
    }
}


Measuring segment using QGIS

Question: When I try to measure an element I get really big numbers,
I tried to measure by using in the attribute table -> open field calculator -> output field type (whole number (integer)) ->row_number - Geometry - area$
Answer: An important aspect to consider when measuring spatial data is what units the coordinate reference system being used is measured in, e.g. degrees (a geographic coordinate system), or metres (a projected coordinate system)?  Often when unexpected results come up, it is because your data is measured in degrees (it may be using a spatial reference like EPSG 4326) rather than metres of Easting and Northing (e.g. defined using a UTM grid zone like EPSG 32755, or EPSG 3857).
Also worth considering is, if you are measuring area and you are using a projected coordinate system with units of metres and were expecting a result in square kilometres or hectares, the result in square metres will be much larger (1 sqkm = 1,000,000 sqm; 1 hectare = 10,000 sqm).  So, you may have to scale your result to get the expected magnitude for your purpose.
A quick way of measuring in QGIS is using the measure line or area tool, described here.
I'm not sure if these considerations reflect the issues you are facing.

Measuring segment using QGIS


STFT zeropadding

Question: I am trying to implement the STFT by MATLAB, and I read somewhere that we must do zeropadding to the subsequence of the signal before windowing it with a Gaussian window. What happens if we don't do any windowing?
Comment: I think it's the same reason as why you'd want to Zero pad any signal before taking its FFT.
Answer: You don't HAVE to zero pad, ever, unless there are constraints on the length of data required by the FFT algorithm - often it's a case of speed.
Many FFT's (like the Numerical Recipes code) require a power-of-two length series, some (like Kiss-FFT) only require it to be an even number, but being a multiple of 2,3 and 5 makes it run much faster.
In Matlab's case the algorithm is optimized for dealing with power-of-two length data. It usually pads the data to achieve this for you, though you control how many powers-of-two you wish to pad up to.

STFT zeropadding


SearchKit: incorrect contact profile opening from (list) Display Name column

Question: When using SearchKit and there are multiple profiles in the same row of the result, when I click on a to open a contact profile, sometimes an incorrect contact profile will open.
This happens using the link in the (List) Display Name column, and the profile that opens does seem to be that of another contact in the row. However, for some of the contacts the correct profile does open. Is this happening for anyone else?
Steps to re-produce in demo site:

Create following search and click Search

Scroll to row where (Count) contact ID = 30, or you see multiple names in the (List) Display Name column

Click Alexia Müller to try to open their profile (contact ID 157)

It opens Kiara Jameson's profile (contact ID 42)

Repeat Steps 1-2 above search and try Mrs. Justina Jameson, it opens the correct profile.

Note that some contacts in Display Name list are correct like firstname.lastname@example.com (https://dmaster.demo.civicrm.org/civicrm/contact/view?reset=1&cid=109) but the next contact in the list, firstname.lastname@example.com, has the same link to the email@example.com contact .
Answer: It looks like the bug is triggered when you use "Distinct" mode for grouping. I'll take a look at what's going on there, but in the meantime you can disable "Distinct." When I did that, all the links pointed to the correct contact.
To disable it, open up "Field Transformations" and uncheck the box like this:


How to remove cloudy pixel from MODIS NDVI (MOD13Q1)

Question: I am using MODIS NDVI product (MOD13Q1) for the vegetation changes study. I want to remove cloudy or bad pixel from MODIS NDVI data. I am not getting any suitable method or software or any program to do this task.
Comment: Is there a reason that you don't use the Quality Layer provided along with the NDVI layer? The easiest way to access the information in that data is by using the LDOPE tools: https://lpdaac.usgs.gov/tools/ldope_tools
Answer: Although it requires signing up for an account, you can do this through Google Earth Engine's API quite easily. They give comprehensive tutorials and scripts for how to do so, as well as the data products you are asking for. You can remove the cloudy/bad pixels from the NDVI product by adjusting the script of this tutorial for the data layers you'd like to use: https://developers.google.com/earth-engine/ic_composite_mosaic
Comment: Thank you Sir . but i checked there. There is cloud mask code for LANDSAT "scored = ee.Algorithms.Landsat.simpleCloudScore(image)". And how i can use this code for MODIS NDVI . Kindly tell me
Answer: As I know, there is a QA band in MOD13Q1 product. you can check on this link
It indicate whether the pixel is covered by snow or cloud.
Answer: This group at the University of Colorado monitors storm surges and flooding globally using MODIS. You might look at their publications for some insight on their dealings with clouds... I know that they use multiple days worth of images from both Terra and Aqua to produce their products.
https://floodobservatory.colorado.edu/publications.htm


Does ATC expect 250 KIAS during vectors for an instrument or visual approach?

Question: During vectors to an instrument or visual approach does ATC expect the pilot to maintain 250 KIAS until cleared for the approach or instructed to slow to another speed?
Comment: Be aware too there are many airplanes in the sky that can't even come close to 250 KIAS. As I recall, the fastest plane I ever got checked out on had a Vne of 164 KIAS, cruise speed of about 130 KIAS, and I'd usually fly an instrument approach at 90 KIAS.
Comment: If there is no other traffic involved, regulatory airspeed limits (e.g. 250 below 10,000, etc.) apply and the pilot can fly the speed of his/her choice (no ATC expectation involved). As the aircraft gets closer to the airport it must be configured for landing and flap/gear speed limits require a reduction in speed. However, if there is other traffic involved (most often the case) ATC assigns the speed they want the aircraft to fly (for appropriate spacing/separation). ATC speed assignments is one of the primary tools used in the terminal area along with radar vectors.
Answer: Generally no, we do not expect pilots to stay at 250 until final. That would be very fast.
Of course I expect the pilot to slow to 250 indicated (which will show as 270-280 over the ground) when reaching 10,000 MSL. And then I will expect further speed reductions as the aircraft gets closer to the airport and the pilots run their checklists and begin configuring the aircraft for landing. Where I work now we very rarely have to use speed restrictions, and I would guess that most jet aircraft are doing around 180-220 on the base leg without any instruction from me.
Military fighters will sometimes stay quite fast on the base leg, sometimes 250+ knots over the ground. This is not normal for other aircraft.
When I was in radar training with the FAA, in the simulator sessions the general rule of thumb was to assign 210 knots on the downwind, 190 on base, and 170 on final. These were slower on downwind and base than the aircraft would otherwise fly, and faster on final. But that was only simulation.
At busy airports where there is a constant stream of arrivals it is very common for aircraft to be assigned specific speeds, whether over the frequency or via a published procedure.

The 7110.65 says this (paragraph 5–7–3):

When assigning airspeeds, use the following:
c. To arrival aircraft operating below 10,000 feet:

Turbojet aircraft:

Assign a speed not less than 210 knots, except for the aircraft as specified in subparagraph b above [operating below a Class B shelf], or
Assign a speed not less than 170 knots when the aircraft is within 20 flying miles of the runway threshold.

Reciprocating and turboprop aircraft:

Assign a speed not less than 200 knots, or
Assign a speed not less than 150 knots when the aircraft is within 20 flying miles of the runway threshold.


What does "square the base" mean?

Question: I was flying the other day and heard tower say to another aircraft, "square the base". What does it mean, and when might a controller say this?
Answer: The controller wants the base to have two distinct 90° turns, from downwind to base, and base to final. And not one continuous turn from downwind to final. And no shortcuts to be taken to shorten the downwind.
It means the base will be slightly longer, and the downwind more parallel to the runway.
The controller is buying time (delaying the arrival) to accommodate someone else.

Top image is square-the-base, as opposed to the tight circular pattern—which experienced pilots tend to prefer1. (Images above are a mere representation.)
Note: exact answer will depend on the plane's exact location in the pattern.
It's one of those terms you won't find in a manual, like "hold our code".
It's a shorter time extension than "extend downwind leg":

Further reading: studentpilot.com, AOPA, 1 humorous AVweb video.
Answer: " Squaring the base" or "squaring the base to final" is a non-standard instruction used by the controller asking the pilot to fly the base leg until the correct point where he can make a proper 90° turn onto final.

This being the correct normal procedure in the pattern, he is simply asking the pilot not to cut the corner. This is usually done for spacing to allow enough time for the traffic ahead to clear the runway.
If the controller needs the pilot to expedite his landing he may give the opposite instruction, something like, "proceed to the numbers" or "straight to the numbers." This indicates that the controller wants them to cut the corner and take the most direct route to the threshold making time for traffic following.

Since these instructions are non-standard the wording may vary between different controllers.
Answer: The other two answers correctly describe the situation where an aircraft is in the local pattern already. But there is another situation where controllers might tell an aircraft to "square your base to final:" when the aircraft is inbound to the airport and in a position to make a modified straight-in, and the controller does not want them to. Again, this is a delaying maneuver.

What does "square the base" mean?


How to check if a directory is empty in Java

Question: I'd like to check if directory is empty in Java. But there is a possibility that there are many files in that directory so I'd like to do it without querying its file list, if possible.
Comment: list() can be very slow on many files.
Comment: When scanning for empty directories I found that .list() was taking up well over 50% of the execution time. So finding an alternative could significantly speed things up if you don't actually need the list of files.
Comment: Over an excruciatingly slow network (via a UNC path), reading a directory list containing 10,000 subdirectories once took a program I was tasked to maintain somewhere around 30 minutes. The program then attempted to read the contents of each directory cross-indexed against a database, resulting in an 8-hour runtime. `list()` can be _very_ slow indeed. After flipping the logic (database query first), the runtime dropped to around 8 minutes.
Answer: With JDK7 you can use Files.newDirectoryStream to open the directory and then use the iterator's hasNext() method to test there are any files to iterator over (don't forgot to close the stream). This should work better for huge directories or where the directory is on a remote file system when compared to the java.io.File list methods.
Example:
private static boolean isDirEmpty(final Path directory) throws IOException {
    try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) {
        return !dirStream.iterator().hasNext();
    }
}

Comment: @jonr, he uses try-with-resources in the example so the stream is automatically closed when exiting the block.
Comment: @garyee, you could store the iterator in a local variable, then perform the `hasNext()` check as described in the answer and otherwise use a `while` loop over the iterator.
Comment: How would one go about if one would want to iterate over dirStream after the check? I tried:
for (Path artifact : dirStream ) {
But got a Iterator already obtained - Exception
Comment: You say `don't forget to close the stream` but in the example you don't close the stream? :)
Comment: The problem is that on Windows there is sometimes a desktop.ini file that is created by default. The method doesn't check for only that file. One could argue that this directory is not really empty, but it is empty of content user has created. Or am I missing something?
Comment: @tobidelbruck It looks like for that you could simply add `|| dirStream.iterator().next().endsWith(".ini")` to the returning statement. Of course assuming there is only ever one file in that case. Edit: oh wait thats a directory stream not files for the directory.
Answer: File parentDir =  file.getParentFile();
if(parentDir.isDirectory() && parentDir.list().length == 0) {
    LOGGER.info("Directory is empty");
} else {
    LOGGER.info("Directory is not empty");
}

Comment: "without querying its file list"
Answer: if(!Files.list(Paths.get(directory)).findAny().isPresent()){
    Files.delete(Paths.get(directory));
 }

As Files.list Return a lazily populated Stream it will solve your  execution time related issue.
Comment: The javadoc for Files.list() says to close the stream when finished and suggests try-with-resources (and btw, `!isPresent()` is the same as `isEmpty()`), so something like this:
`try (Stream entries = Files.list(path)) {
    return entries.findAny().isEmpty();
}`
Answer: Considering from java.io.File source code, list() method does:
    public java.lang.String[] list() {
    ...
        byte[][] implList = listImpl(bs);
        if (implList == null) {
           // empty list
           return new String[0];
        }
     ...
     }

     private synchronized static native byte[][] listImpl(byte[] path);

It calls a native method passing a byte array to get files from it. If a method returns null it means directory is empty.
Which means, they don't even have a native method, to check for directory emptiness without listing files, so there is no way they would have an implementation in java for checking if directory is empty.
Outcome: checking if directory is empty without listing files is not implemented in java, yet.
Answer: boolean isEmptyDirectory(Path dir) throws IOException {
    try (var entries = Files.list(dir)) {
        return entries.count() == 0;
    }
}

Similar to @Minnow's solution (but with less method calls), this solution has the benefit "As Files.list Return a lazily populated Stream it will solve your execution time related issue."
Comment: I guess count would load all the directory entries anyway. Wouldn't the `entries.findFirst().isPresent()` be a better solution?
Comment: Both Files.list and Files.newDirectoryStream will iterate the directory entries lazily. Therefore, they will work with huge directories very efficiently. However, your solutions will not work well. It's not a good choice for huge directories.
Answer: This is a dirty workaround, but you can try do delete it (with the delete method), and if the delete operation fails, then the directory is not empty, if it succeeds, then it is empty (but you have to re-create it, and that's not neat). I'll continue searching for a better solution.
EDIT: I've found walkFileTree from java.nio.file.Files class: http://download.java.net/jdk7/docs/api/java/nio/file/Files.html#walkFileTree(java.nio.file.Path, java.nio.file.FileVisitor)
Problem is that this is Java 7 only.
I've searched S.O. for other questions related to this very issue (listing files in a directory w/o using list() which allocates memory for a big array) and the answer is quite always "you can't, unless you use JNI", which is both platform dependent and ugly.
Comment: Directory deletion may fail due to other causes -- e.g., file permissions.
Comment: Well the problem is directory permissions - not just the wrong answer kind, but also the fact that you pretty much reset the permissions AND change metadata. Not much you can do about the second, but at least check permissions beforehand (that way you get rid of the false negative - just do a list() in that case) and set those permissions for the new dir. Still horrible, but a bit better.
Comment: In fact it's ugly. Hope there is a 100% java solution for doing this. Still searching.
Comment: I don't think even `/bin/ls` would work because it enumerates the whole directory in order to sort its output.
Comment: I'd like people downvoting understand that I'm perfectly aware this is an horrible hack and I've done comprehensive research on how it can be done better, w/o finding anything satisfactory (see EDIT)
Answer: If you can live with platform dependent code - you can try using actual native code by loading a system library and using its APIs.
In Windows for example you have a Win32 API named FindFirstFile() with the directory name (without a trailing backslash). If it returns something other than . and .. you know the directory isn't empty. It will not list all the files so it's much faster than file.list().
The equivalent on Unix is opendir. For your purposes the logic would be the same.
Of course - calling native methods has a price on usability and the initial library loading which should be negated by the time it will save on the FS queries.
Comment: Considering that there's absolutely nothing stopping people from creating files that don't contain a "." and nothing stopping people from creating directories that contain a "." - that solution won't do any good. And while I'm sure there's a more or less efficient way to do this with a native API, the overhead of calling it, will probably be worse. Depending on the FS implementation it's conceivable that the OS would have to enumerate all files in it to begin with anyways (no idea how NTFS is implemented?)
Comment: @Voo: The proper usage is to ignore the `.` and `..` entries. If a filesystem doesn't allow you to get the first directory entry without enumerating all the files, there would be no fast way to check if it's empty, but I doubt such a filesystem would ever exist.
Comment: @Gabe Yeah no idea how NTFS is implemented in detail. Your edited solution should be exactly what the OP wants, apart from the fact that it's native - and I'd assume the directory has to be quite large to offset the cost of the native call (but you mentioned that already and the question is about large dirs anyways so that's fine too). Though you should've created a new post (the edited one doesn't have much in common with the original ;) ), I'd love to upvote your post (or do you get a part of the credit because of your edit?)
Answer:      Path checkIfEmpty=Paths.get("Pathtofile");
     DirectoryStream<Path> ds = Files.newDirectoryStream(checkIfEmpty);
     Iterator files = ds.iterator();
     if(!files.hasNext())
         Files.deleteIfExists(Paths.get(checkIfEmpty.toString()));

Comment: Just be careful to close DirectoryStream when you are done (or use try-with-resources) otherwise you end up with a file handler leak.
Answer: You can check whether directory isDirectory() after all (and not a file) and then, call list() to get its content and finally, get the length value to see whether there is content, i.e., whether it's not empty.
directory.isDirectory() && directory.list().length > 0 // directory is a File obj

Comment: Welcome to stackoverflow. I'd recommend editing this to add how your answer is better or different from the many other answers already posted on this old question. Also note that the original question asks for a way to do this without calling `directory.list()` so if you still advise using it despite that, you should explain why.
Comment: See "[answer]" and [Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/128421)". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem.
Answer: I also had this Confusion for a Long time about how to check if the Directory was empty or not
But the Answer is Quite Simple
use
class isFileEmpty{
public static void main(String args[]){
File d = new File(//Path of the Directory you want to check or open);
String path = d.getAbsolutePath().toString();
File dir = new File(path);
File[] files = dir.listFiles();
if(!dir.exists()){
System.out.Println("Directory is Empty");
}
else{
for(int i =0;i<files.length;i++){
System.out.Println(files[i])
           }
       }
   }
}

Answer: I want to add to answer of Developer. Checking is it directory or not should not be in one If operator, because you will have mistake in logic. First of all you checking is it directory or not, and only after that you checking directory consistensy, becouse you will get wrong answer if the tranfered to method directory is not exist. Just check it. Should be like this:
if (file.isDirectory()) {
    if( file.list().length == 0) {
        logger.info("Directory is empty");
        return false;
    } else {
        logger.info("Directory is not empty");
        return true;
    }
} else {
    return false;
}


Locking focus and capture to a specific window

Question: I can call a setfocus and setcapture using a toggle mechanism and in OnLButtonDown make sure the message doesn't get passed on, but that seems to fail the moment you left click. Is there any way to ensure that the window which has capture and focus does not give it up?
Comment: In this particular case it's for a color sampler.
Answer: For a color picker, try reading this article on getting colors from anywhere on screen.
This one is a more complete utility, let's you do what you want. The difference is capturing stops on a key combination [Alt+Ctrl+P], where you want to stop on a click.
In the second link, the following function calls will be useful for you:
<code>SetWindowPos(&wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
RegisterHotKey(m_hWnd, 0x1FEB, MOD_CONTROL | MOD_ALT, 0x50);
</code>
The first one keeps the window active, and the second registers Alt+Ctrl+P (And when that is pressed the window will receive a WM_HOTKEY event, where upon you can stop capturing colors). Sadly you cannot use RegisterHotKey with mouse buttons. You will want to look into SetWindowsHookEx
With SetWindowsHookEx, you can make sure your application will receive events even without focus. Call SetWindowsHookEx with the hook "WH_MOUSE", along with a Mouse Procedure.
It is in this procedure you will get the mouse message, stop capturing where the mouse moves (lock the color), and use SetWindowPos to move your window to the top. Then unregister your hook with UnhookWindowsHookEx.
This is quite a bit of stuff you might need to learn, but all the MSDN pages I've linked you to have plenty of information that should help you out, not to mention if you're willing to settle with a key combination instead the second link is perfect for you.
Hope that helps.


Acess windows files with SeBackupPrivilege and SeRestorePrivilege

Question: I have a full drive to move to another partition.
The problem is that the design was poorly funded and now, we have to deal with lots and lots of different users accessing via SMB and applying their own permissions on their folders.
In order to backup, I see robocopy has a /b switch, which uses the backup mode.
AFAIK: Backup mode applies to those users who have the setting "enabled" when they run "whoami /priv" on the SeBackupPrivilege and SeRestorePrivilege settings.
I've been trying to modify my user's setting via GPO but it does not seem to sort any effect!
Can anyone shed some light on this issue?
Truth is that ever since I started using the /b switch, the backup seems to run better and does not give me so many access errors (it actually does not output any)
Comment: `Backup mode applies to those users who have the setting "enabled" when they run "whoami /priv" on the SeBackupPrivilege and SeRestorePrivilege settings.` No. Those privileges are always disabled by default. They are enabled by the applications that use them when needed (robocopy in this example).
Answer: In order to allow robocopy to use backup privilege, you must be an administrator (or see below) and you must run robocopy from an elevated command line window.
To open an elevated command line window, type cmd in the Start Menu and then press SHIFT-CONTROL-ENTER instead of just ENTER, or choose the "Run as administrator" option.  Depending on how Windows is configured, you may be prompted to confirm that you want to proceed, or you may need to re-enter your account details.
If you are an administrator, you automatically have backup and restore privileges, unless your system configuration has been changed in an unusual way.

It is possible to explicitly grant a user account just backup and restore privilege rather than full administrator privilege.  Traditionally, nobody bothers, because backup and restore privilege is "equivalent" to administrator privilege, in that a malicious user could easily leverage backup and restore privilege to obtain administrator access.  (There may be some marginal security benefit in that a virus might not be programmed to take advantage of this situation, but generally speaking it isn't worth it IMO.  Just have a separate admin account and use it when you need to perform this sort of operation.)
If you choose to do it this way, however, you must still open an elevated command window in order to take advantage of the privileges.  In this scenario, you will always be prompted for a username and password.
You can confirm that this has worked using the whoami /priv command as mentioned in the question, but you should ignore the State column.  If SeBackupPrivilege and SeRestorePrivilege appear in the list of privileges, then they are available to the robocopy command even if the State is shown as Disabled.  Robocopy will enable the privileges automatically when you use the /b option.  If you do not have the privileges, they will not appear on the list at all.
Comment: If it's not clear from the above, one of the things you have to watch out is user rights vs. whether the privilege is currently enabled within a process.  Some privileges can be available but not enabled by default during process creation.  Robocopy presumably adjusts the token as needed within available rights.  Other tools may omit this step and rely on something else to pre-enable.  This is also a worthwhile security auditing topic: attempting an operation and failing isn't enough to ensure you don't have the underlying right... (See also: impersonation and reverting to self...)


Two floor home cooling with one ductless heat pump split mini mounted on second floor

Question: I live in Seattle where we have a relatively small number of days where it gets hot enough to need AC. I live in a two story house where the two floors, each being 1200 sq ft in area, are connected by a large opening such that it's almost like having one large room with a high ceiling. I'm wondering if a single zone split mini heat pump system installed on the top floor will also keep the lower floor cool enough. I don't need it to be really cool, say 75 degrees, just cool enough to get through a few days of hot days each summer. I'm thinking of a system capable of providing 24000 to 36000 btu cooling. I don't need heat from the system so I don't really need a heat pump but almost all split mini systems seem to be based on heat pumps. I should add that I can use my gas furnace blower to help mix air via the existing ducts. Thanks!
Comment: Is the main bedroom on the 2nd floor?
Comment: What do you use for heat now? Heat pumps are *crazy efficient* compared to whatever you have now.  If you are hitting more than about 2 COP (which will be all the time in Seattle), it is actually less carbon footprint to burn gas at the power plant and power your heat pump than burn gas inside your home!
Comment: @Harper - Reinstate Monica: I have a high efficiency gas furnace, though for much of the winter I just use a small Jotul gas stove. I'd be interested in seeing the data that shows a comparison of burning gas in my furnace as compared to the cost of burning gas at a remote generation station and suffering the transmission line losses getting the electricity to my home. I'm not disputing your claim, I'd just like to see the data. I'm an engineer and we live on data.
Comment: Sure.  [Gas power plant efficiency](http://needtoknow.nas.edu/energy/energy-sources/fossil-fuels/natural-gas/) and the efficiency of a particular heat pump is stated by its COP ( which will differ at different temperatures).   However the bigger factor is that your gas heat will always be gas, but your electric heat will change makeup as grid sources change.
Comment: Thanks for the reference.
Answer: Certainly 36 kBTU/h from a single air handler would make a huge difference in a 2-story house (1200 ft² each story) in Seattle, but you can get minisplits with one condensing unit supplying more than one air handler, and the air handlers are individually controllable. If you get a minisplit, you would want at least one air handler on each floor.
Comment: Two air handlers are much better than using furnace blower to mix air +1
Comment: @Jim Stewart : Thank you!
Comment: Yeah, furnace blower is a total energy loss.  Easier to push freon around than air.
Comment: Don't forget that the indoor part of a heat pump system (the evaporation coil) also includes a blower - I.e., it's not just Freon being moved about.
Comment: Yes, but pushing air around inside a room is a great deal easier than shoving it through a ductopus. Look at the ampacities used by the various blowers.
Comment: True enough. In my case, I would envision running my furnace blower 3-4 times a day for about 15 minutes, so an hour max. The energy consumed doing so would be modest.  That plus the fact that I might only run the system 10 days per year…
Comment: If you get a capable and efficient minisplit, you will use it more than 10 days per year, even in Seattle.
Comment: Remember each evaporator coil/air handler of a mini-split produces condensate water which must be drained, either to the ground outside or to your sanitary sewer.  Do all modern mini-split air handlers have a pump to raise the condensate into an attic where it can flow by gravity to the outside? Can air handlers be mounted on inside walls?
Answer: Since hot air rises and cold air sinks, yes, one head unit upstairs will affect both levels of the home, to the extent that you describe wanting.
Hard to know sizing without knowing your needs (both climate [recently hellish in your area as I write this answer] and insulation level of the building.) I manage just fine with a 12K btu (nominal) head in a building slightly smaller (1060 sq ft/floor) but very well insulated - I do have one head per floor, as I do use them primarily for heating and only occasionally for cooling, but for cooling the single head upstairs is often plenty. The "apparent effective output" seems to be considerably better than a similarly-nominal-sized window unit, perhaps in part from not being installed in a leaky window and poorly insulated from the hot part of itself, perhaps also due to more efficient fan/coil design (also much quieter than a window unit, even a much smaller output one.)
I chose the one head per compressor configuration as it's more efficient than the multi-head form, and cost differential was quite small. But not all mini-splits are equal on that basis, so shop carefully if operating cost/efficiency is a concern, as it is for me.
With a "more typically insulated building" 36K might be needed, or even be not quite enough.
My own shopping experience was that number of heads strongly influenced the cost, and BTU capacity of the heads/compressors was a much smaller impact than I expected (larger cost more, but twice the capacity was less than 10% cost difference, IIRC - but oversizing also makes it inefficient, so bigger is only better up to a point.) I had intended to get more smaller heads before I understood the cost model I found, so I fully understand using a single head located upstairs if you are only looking for cooling. Adding a downstairs head might nearly double your cost, at least based on what I found in my market.
Comment: ...and for heating, a good one can compete with your gas heat much of the year, depending on your relative cost of electricity and gas.
Comment: Thanks very much for sharing your thoughts.


How do I delete material in 'Video' in the imovie app

Question: When I open imovie there are three choices Video Projects of Theater.  I want to delete what is in the video file but can't work out how to do this as when I enter this there are all the video clips but no menu to do anything but view them.  Can anybody help please.
Answer: The videos in the "Video" section can be deleted from the "Photos" application.  iMovie can include those videos when making a project, but, it cannot delete them directly.


how to avoid 14mm hex tool getting stuck in the fastening bolt when installing crank?

Question: As I am trying to install the eewings mountain crank as per the instructions, and fasten the bolt to 52nm, the 14mm hex tool gets stuck in the fastening bolt when I apply pressure.
I am afraid to further apply more pressure so it will not mess up the threads on the bolt, or I would not be able to take it out. I did apply a layer of supplied (along with the crank) ti-prep on the fastening bolt threads. Do you have any suggestions please? At the moment I pulled it out with my pliers, but have not gone all the way to 52nm.  I am using the parktool torque wrench along with adapter to 14mm hex tool, while the bike is on the bike stand. Thank you.
Comment: Yeah I had expected that, but unfortunately when I apply force on the opposite direction, it stays stuck in there.
Comment: Does the 14mm bit not free itself once enough force is applied in the opposite direction to unbind the bit. You'll lose a tiny amount of tightness but at 52Nm it's not going to matter.
Answer: If the hex bit is simply stuck in hex-shaped recess in the bolt after tightening, then I'd simply lightly tap it on the side back and forth with a hammer to loosen it and then pull it out, whilst wiggling it side-to-side, by hand. It is quite normal for these sorts of things to get jammed in the bolts such that it is hard to remove just pulling by hand.
However, it is an expensive bit of kit and a large amount of torque, so make sure you are confident that the assembly is correct before applying force. I'd suggest trying to get the first few turns of the bolt done by hand to confirm thread is fully engaged before getting your big wrench out.
Comment: @yuvalon Well, what happens is that the hex profile of the bolt or the screw bit gives in a little bit, so that the hex profiles of the bolt and the bit are no longer aligned. This puts a large squeezing force onto the hex bit, which clamps the bit into the bolt. You need to make the bit move despite the clamping force and without turning the bolt backwards. And that's what a bit of love from a hammer is good for.
Comment: Thank you, yes that is what I did at first, by hand. Felt like the thread was fully engaged. Hopefully it is just the case you mentioned where it is simply stuck inside and it is okay to "manipulate" its way out of it by tapping it/ etc. But weird that applying torque to the opposite direction did not do the job.


Etymology/origin of 'The argument principle'

Question: What is the origin - explanation - etymology of 'The argument principle'
It goes in French by "théorème de l'argument" or by "Principe de l'argument".
ANother question did not answer this.
Comment: The argument of a nonzero complex number is (any one of the choices of) angle that the position vector makes with the positive $x$-axis. The change in argument tells you how many times the curve winds around the origin.
Answer: The argument principle makes a statement about the following integral:
$$\frac{1}{2\pi\text{i}}\int_\Gamma \frac{f'}{f},$$
where $f$ is a meromorphic function in an open set $\Omega$ and $\Gamma$ is a closed contour in $\Omega$ such that $f$ doesn't have any poles or zeros in $\Gamma$.
Note that, under these conditions, if we denote $\gamma:=f\circ \Gamma$, then
$$\frac{1}{2\pi\text{i}}\int_\Gamma \frac{f'}{f} = \frac{1}{2\pi\text{i}}\int_\gamma \frac{1}{z}=\operatorname{Ind}(\gamma,0).$$
This is, the integral $\frac{1}{2\pi\text{i}}\int_\Gamma \frac{f'}{f}$ is the winding number around the origin of the image under $f$ of a point moving along $\Gamma$, or, in other words,
$$\int_\Gamma \frac{f'}{f},$$
yields the change in the (continuous) argument of the values that $f$ takes when moving along $\Gamma$. This justifies the name "argument principle".


How to avoid console window in Qt application, even after Including "testlib" package (for qWait()) in my .pro file?

Question: Hallo everyone,
I have gone through various threads on this topic but, nothing seems to solve my particular problem. Including testlib, makes the console window appear and there I didnot find any option to suppress this behaviour.
But my application still demands testlib to be present (because i badly wanted to use QTest::qWait() method), and no console window to appear. I tried a few options from the other threads but nothing is working. what should i do to suppress this console window even after using 'testlib"?
The options I tried are

adding CONFIG -= console to my .pro file.
    QT += gui \
        xml \
        core \
        testlib
    CONFIG += qt \
        windows \
        uitools \
        release
    CONFIG -= console
    LIBS += extern/ftd2xx.lib
    RC_FILE = res/AC-Core.rc
    QMAKE_CXXFLAGS += -Wall \

editing the qmake.conf file, the lines
QMAKE_LFLAGS_CONSOLE = -Wl,-subsystem,console, to
QMAKE_LFLAGS_CONSOLE = -Wl,-subsystem,windows

Any other ideas to suppress the appearing of console window are welcome?
Thanks!
Comment: Related: http://stackoverflow.com/q/760323/13767
Answer: You don't have to use QTest to get the functionality of QTest::qWait(). If you look at the source code for qWait() you can see how it works and implement this function yourself:
inline static void qWait(int ms)
{
    Q_ASSERT(QCoreApplication::instance());

    QTime timer;
    timer.start();
    do {
        QCoreApplication::processEvents(QEventLoop::AllEvents, ms);
        QTest::qSleep(10);
    } while (timer.elapsed() < ms);
}

Comment: Or, even better, use local QEventLoop and QTimer::singleShot on event loop's quit() slot.


What is the cause of the pink cast in my photos?

Question: When I've photographed my dogs lately, their fur comes out with spots of pink tint. It's in both the RAW file and the edited Lightroom file. Any suggestions? I use a Canon Rebel t6i and it's 6 months old. If you zoom in on this pic, you'll see what I mean.
Comment: I see some areas that have a slight red cast above the hind knee and behind the foreleg, but nothing that looks unnatural. It might help if you add arrows to indicate the areas you're concerned about.
Comment: It would also help if we could see 100% crops of the affected areas.
Comment: What, exactly, is the "RAW file" within the context of the way it looks? All raw data must be converted to be in a viewable format. Neither the lcd on the back of your camera nor your computer screen shows you a "raw file'. It shows one particular interpretation of the raw data converted to display on your screen.
Comment: What was used to convert the raw file to the jpeg you uploaded? How was color temperature/white balance set? What were the compression settings? What ISO was set? What aperture? Shutter time? What lens was used? The pink/purple tint is in all of the image, it is just a little more noticeable on the dog's fur.
Comment: The white balance has an overall magenta cast as well.
Comment: Is it possible that the problem is caused by shooting right againts the sun?  How does photose with sun behind you look? And, please, provide more details: ISO, shutter speed, apperture, lens, accessories (filters, caps,...)
Comment: @Michael Clark agreed, my guess is on high ISO and high compression.
Answer: This is a complement to @Caleb's answer. You mentioned pink spots, so that is an apropiate answer.
I must say that I do not see the distortion you are mentioning.
If you have an overall "pink" cast (which technically it would be magenta) could be due a white balance issue.
Either the camera is trying to compensate some other color like the blue of the reflection or you somehow you moved a special setting on your camera. (I'll try to post a screen capture later).
Answer:
If you zoom in on this pic, you'll see what I mean.

While there are some areas in the fur that do look a little more red than others, there's nothing that looks unnatural, at least at the resolution available to us. It would help if you'd post additional images, especially with some indication of where you think the problem spots are so that we can make sure that we're on the same page.

Any suggestions?

If there's a problem, it could be anything from lens flare to some kind of lens aberration to a damaged sensor. Try to diagnose the problem by finding reproducible cases and identifying the conditions that affect the problem.
I'd start by trying to reproduce the problem at various focal lengths. Assuming you have the 18-55mm kit lens, shoot at 18mm, at 55mm, and at several focal lengths in between. See if the tinting happens at all focal lengths or just some. You should also vary the aperture setting at each focal length. For most lenses, problems like chromatic aberration are most noticeable at the extremes – the shortest and longest focal lengths and the largest and smallest aperture settings. If stopping down a bit and/or using a middle-of-the-range focal length eliminates the tint, you're on the right track.
Try shooting with a lens hood. It doesn't have to be a proper hood -- you can tape a black construction paper collar around the lens. Lens flare is caused by light bouncing around inside the lens and eventually hitting the sensor. It can manifest in surprising ways, but blocking light entering the lens from extreme angles (as a lens hood does) can cut down on it. If this solves the problem, just buy a proper hood if you don't have one already and use it when there's strong light from the side. Aftermarket lens hoods are readily available and are frequently very affordable.
Assuming the spots remain in all photos, try to get the spots to appear in photos of things other than your dogs. Shoot an evenly lit white wall. Shoot the sky with the sun at your back. Shoot your dogs in other lighting conditions. If the tint pops up everywhere, no matter what you're shooting, then you'd start to suspect a problem with the sensor.
Next, try a different lens. If the pink tinting fails to happen with the second lens (make sure that you take similar images with both lenses), then you know that the original lens is the problem. If the tinting continues to happen, it's possible that both lenses suffer from the same issue. Ideally, you should try a different lens model, but one that has a similar focal length.
Answer:
If you zoom in on this pic, you'll see what I mean.

I zoomed in and looked at various areas of the picture. The magenta/purple spots are everywhere. They're just more noticeable on certain areas of the dog's fur where the color is a greatest difference to the color of the magenta color splotches. Here's the lower right corner of the image:

And the upper left corner:

Without knowing the specifics of the photo linked above in the question (i.e. ISO, WB setting, how it was processed and by what application(s) using what specific settings) it is difficult to say for sure what caused the magenta color splotches but based on the very little information provided in the question here is what appears to be going on to my eyes as someone who has been shooting Canon digital cameras for over a decade and color film for over 4 decades:

The color temperature and white balance are wrong. In the film days if one used a color film balanced to be used under fluorescent lighting (or processed a daylight film as if it had been shot under fluorescent light, or used a compensating filter for fluorescent lighting when shooting under daylight conditions) outside in daylight the color would look very similar to the color cast in this photo. With digital cameras, when a scene doesn't have very much true white for the camera to work with the AWB setting will often struggle and guess incorrectly. Sometimes by a significant margin. For a very extreme example, please see this answer to this question: Blown out blue/red light making photos look out of focus.
The color temperature in the photo is leaning heavily towards blue. It appears to have been shot with the sun fairly high in the sky when the sun is brightest and has a higher (bluer/whiter) color temperature than shortly after sunrise or just before sunset when it is lower (more golden/amber). The color temperature should be set in the raw conversion application to a higher value to compensate for the color of the light in the scene.
There's a very heavy magenta cast in the photo. The hue adjustment on a raw convertor should be used to change the bias towards the green end of the magenta <--> green axis. Again, this is to compensate for the color of the sun's light when it is high above the horizon.
Some types of chrominance noise will often manifest itself with color blotches such as what we can see in the example photo. Those color blotches are very often red, magenta, or purple if the color temperature is as described above. Increasing the chrominance component of the noise reduction tool in your raw conversion application can go a long way to reducing such color splotches. If the photo was taken at a relatively high ISO setting, the reduced shutter time/overall exposure will increase the chances of such types of chrominance noise.
There seems to be a lot of compression in the photo as posted in the question. Perhaps it came from the settings when the raw data was converted to jpeg, or perhaps it was added when the image was uploaded. Whatever its source, the compression seems to exacerbate the magenta splotches in the photo. Notice that the color cast seems to be worse in the blocks that seem to be more compressed than adjacent blocks that are not as compressed.

Even the white/grey pixels in the watermark in the lower left corner are affected. This is almost certainly an artifact from the jpeg compression.
Answer: I used to get the same aberrations on my Canon 20D, and would get the discoloration in images that had both high contrast and high detail (like your sample).
In Lightroom you can use the selective color adjustments to change the saturation and tonality of the pink/purp. (screenshot: https://i.stack.imgur.com/bmv6E.jpg).
Also look at the defringing and chromatic aberration checkbox under Lens corrections.   It isn't a normal CA, per se, but it will help minimize the pink/purp tones.
I would give Canon support a call.
Comment: Sorry, not convinced that there is a sensor issue here.
Comment: Not sure why she should give Canon support a call... What exactly are they going to do for her in this context?
Comment: Also, you don't actually explain in your answer _why_ she should call Canon. Your preceding paragraphs talks solution to the issue and then, without any context as to what is causing it, you tell her to call Canon. So, you haven't really addressed the question at all, except in a comment, and even then you don't explain _why_ it is a sensor issue. The question isn't how to fix it, it's what is causing it.
Comment: This appears to be more of a postprocessing/WB/chrominance noise issue. Without more info from the OP it is hard to pin down, though.
Comment: JoanneC: --this is a sensor issue.  12 years ago it would have been (barely) acceptable, but not today.
Comment: Or to put it this way: You haven't explained *what* to tell Canon when she calls them.
Comment: @opus13 For why proper postprocessing is so important please see this answer to a different question: http://photo.stackexchange.com/a/73479/15871   AWD doesn't always get it right. In fact it rarely gets it *exactly* right.


Defining potential of the ground

Question: In electronics, it is customary to define the potential of ground (thinking the Earth as a large conductor) as zero. Is this consistent with the fact that the Earth has a net electric charge that is not zero?
Answer: Yes it is, for the following reasons.
In any circuit, you can add an arbitrary voltage offset to the ground return ("lifting" the return above ground voltage) and upon doing the math you will find that the offset voltage drops out everywhere in the equations and leaves you with the same result as the zero offset case. This means that even though the surface of the earth may possess some net voltage offset because of a charging process that is driven by the sun, we can still designate the surface of the earth to be at "ground potential" and all our circuits will still function properly.
By the way, the fact that adding a voltage offset like this is found to have no effect on an electrical system is the result of a mathematical property called electromagnetic gauge invariance.

Defining potential of the ground


Scaling any document to A4 format

Question: I have got some pdf documents that need to be printed to A4 paper.
I know there are options in my pdf reader (evince) to scale the document to fit the exact paper size it's printed to, and that works fine with printing to a file, too.
So there must be a CLI-solution to get this job done, right?
Whenever I want a pdf to be 2 pages on one sheet, I use
pdfnup in.pdf --nup 2x1 --outfile out.pdf

But that doesn't work – in.pdf is not scaled to fit, instead it's too tiny compared to the output of evince printed to a file. So how can I scale it before (or while) using pdfnup? It would be great if that worked for any input format, not just for A5. Thanks in advance for any answer!
Regards, LDer
Answer: Oh boy, I just figured something out on my own. Sorry for bothering anyone!
gs -o out.pdf -sDEVICE=pdfwrite -sPAPERSIZE=a4 -dFIXEDMEDIA -dPDFFitPage -dCompatibilityLevel=1.4 in.pdf

Scaling any document to A4 format


How to make helm follow and show files as I type?

Question: My Emacs used to have the ability to display the help buffer of each function everytime I was scrolling through M-x function candidates. How to enable it again? Thanks!
Answer: It is called helm-follow-mode.
According to Helm documentation (C-h m from inside an Helm buffer):

When helm-follow-mode is on (C-c C-f
to toggle it), moving up and down Helm session or updating the
list of candidates will automatically execute the
persistent-action as specified for the current source.

If helm-follow-mode-persistent is non-nil, the state of the
mode will be restored for the following Helm sessions.

If you just want to follow candidates occasionally without
enabling helm-follow-mode, you can use
C-down or
C-up instead.  Conversely, when
helm-follow-mode is enabled, those commands go to previous/next
line without executing the persistent action.

So the easiest way is to navigate with C-down or C-up.
C-c C-f allows you to toggle this behaviour and variable helm-follow-mode-persistent to make it persistent.
Comment: Thanks. I actually can't find helm-follow-mode in my system. I installed helm, but it doesn't show for some reason. In my init I actually had helm-follow-mode-persistent turned on. How can I install helm-follow-mode?
Comment: I meant to say, "In my init I actually have helm-follow-mode-persistent turned o but when I do M-x helm-follow-mode, there are no candidates. Also, C-c C-f does not seem to be binded to it."
Comment: You need to be in a helm session to use `C-c C-f`. Do `C-down` and `C-up` work in helm M-x?
Comment: Oh my god! You nailed it! Now I was in the helm session, and did C-c C-f and it worked. I did not know this. Regarding C-down and C-up, That's another thing, in my MAC if I do C-down, it shows the desktop. It's inbuilt mac behaviour, so I can't do C-down in Emacs. Not sure how I could enable this in Emacs.


The Possibility Life Patents?

Question: Genetic engineering has come a long ways now form it's humble beginnings with Dolly to artificial organs, it's only a matter of time before we are making brand new animals to use for circuses, sports or pets. Of course companies would want to patent the design they put years into making but considering that animals are infinitely complex in design how could they? Ignoring all the problems with playing god, how would the genetic engineering companies patent a biological blueprint and have it hold up in court?
Comment: Copyright is the wrong concept. Ask about life patents.
Answer: Actually, it's already happening today.
Pharmaceutical companies often ask for people with certain conditions to participate in studies, etc. in order to help that company develop a drug or method of treatment. What the participants don't realize however is that they are unwittingly signing away the rights to their own DNA.
What some companies are doing now is identifying certain genes which cause an illness, or even a benefit and then patent them as the "discoverers".
What this means is that each of us are walking around with genes in our DNA which a company owns.
There have been trials over how a company can possibly own our DNA, and their argument was that they are the ones who put the effort into discovering that that particular gene causes an issue or benefit.
I'm sure this will become a much, much bigger deal in the near future.
Comment: "What the participants don't realize however is that they are unwittingly signing away the rights to their own DNA." Talk about signing away your soul!
Comment: Dunno about other nations, but in the US Constitution, the authority of Congress to grant copyright protection extends to inventors and authors.  When it comes to human DNA, no company can claim to be the author.
Comment: Yeah, that is true.
Comment: I do believe AndreiROM has it right.  This *is* a grey area between protecting inventors and having rights to things that may not actually be yours.  Our world is exploring how that grey are should be shaped every day.  One excellent case is the case of Monsano GMO corn.  Their corn had pesticides built into the DNA.  However, they flowered , crossbred with nearby fields, and it retained the change.  Monsano went out and sued farmers for patent infrignment beause their plants polinated with Monsano's patented plants.
Comment: @CortAmmon Just for the sake of trying to squelch internet misinformation, Monsanto has never sued farmers for mistakenly planting their patented plants, only when farmers have intentionally planted them. Sources: [NPR](http://www.npr.org/sections/thesalt/2012/10/18/163034053/top-five-myths-of-genetically-modified-seeds-busted), [Wikipedia](https://en.wikipedia.org/wiki/Monsanto_Canada_Inc_v_Schmeiser)

The Possibility Life Patents?


Comparing two models using Repeated K-fold Cross Validation

Question: I am creating two separate classification models. In order to estimate the performance, I have been using 10-fold cross validation repeated 5 times for each model, resulting in 50 different performance metrics for each model. If I wanted to say for sure that one model's performance was better than another, and that this result is statistically significant, can I calculate the mean of the 50 different runs for each model and then perform a t-test? Are there assumptions being violated if I do this?
Comment: Better do bootstrap estimation of the mean performance and its standard errors.
Answer: Update:
I've been doing some reading the past few days and found a few answers. According to Dietterich's paper "Approximate Statistical Tests for Comparing Supervised Classification Learning Algorithms", standard t-tests have a high type I error (a significant difference is found between the models even when there isn't actually one) when used on cross validated results. According to Nadeau and Bengio's paper "Inference for the Generalization Error", this is due to the underestimation of the variance the samples caused by them not being truly independent - the test data is re-used in other folds.
To get around this, I found another paper "Evaluating the replicability of significance tests for comparing learning algorithms" that recommends the use of a "corrected" version of the t-test for repeated k-fold cross validation (which was used in my original models). The corrected version is:
$$t= \frac{\frac{1}{kr}\sum_{i=1}^{k}\sum_{j=1}^{r} x_{ij}}{\sqrt{(\frac{1}{kr} + \frac{n_2}{n_1})\hat{\sigma}^2}}$$
Where $k$ is a given fold, $r$ is the number of repeats, $x_{ij}$ is the difference between models in a given run $j$ and fold $i$. The numerator is an estimate for the mean, while the variance can be estimated as $\hat{\sigma}^2=\frac{1}{kr-1}\sum_{i=1}^{k}\sum_{j=1}^{r}(x_{ij}-m).^2$
(EDIT by @Firebug: $n_1$ is the number of instances used for training, $n_2$ is the number of instances used for testing)
This version seems to be more consistent and replicable in experiments according to the author, so it seems like a safer solution than a naive t-test.
Comment: What are n1 and n2?
Comment: @HaneenSu $n_1$ is the number of instances used for training, $n_2$ is the number of instances used for testing
Comment: I've added this info to the answer, if someone disagrees feel free to revert it


Motion Tracking works in viewport, but not in Render

Question: Everything works fine on the viewport and on the Motion Tracking Menu tab. I have a solve error of 0.839 and 26 trackers. If I do a viewport render, there's no problem. However, when I do a normal render (either in eevee or cycles), the objects start moving around unpredictably as if not recognising the motion tracking. I would really appreciate it if someone could help :)
Comment: As noted on the answer below, it is very hard to diagnose what the problem is without seeing what you have. Can you upload a copy of your project and the video used somewhere and add a link as part of your question?
Answer: It is impossible to help with motion tracking without looking at the shot, and the nodes used on the compositor.
A few comments:
An error of .8 pixels is still too high, you should aim for an error of .3 or lower.
Use the graph and dopesheet to see if any trakers have a high error value.
The most common error in tracking happens if you try to use the default solver on a shot where the camera is not moving, or where the camera is stationary and just tilting and panning. Those shots can only be solves as "tripod". And will not give you any 3d information.
If you haven't already please read the detailed post on this site on motion tracking:
How can I get better results when doing camera motion tracking?


Relation between Young's modulus and density?

Question: Can I calculate Young's modulus from density?
Is there any mathematical relation between Young's modulus and density?
Comment: For an ideal gas, the bulk modulus is proportional to density (at constant temperature). That is the only mathematical connection. Nothing similar exists for solids.
Comment: For many solid materials, the ratio of $E$ to $\rho$ tends to be similar, but there is no "exact" mathematical relationship - unless you can calculate both of them accurately from the atomic structure of the solid, which is probably not what the OP had in mind!
Comment: For the free electron gas, one can derive this mathematical relation: https://ps.uci.edu/~cyu/p238A/LectureNotes/lecture2/lecture2_html/node5.html
Answer: There's no general mathematical relation between stiffness (as parameterized by an elastic modulus such as Young's modulus) and density for all materials, but a relationship can be defined for an ideal gas, and a general trend exists for condensed matter.
For fluids such as gases and liquids, Young's modulus is zero; you won't encounter any resistance if you slowly pull on these materials uniaxially. However, the bulk modulus (i.e., the resistance one encounters when trying to compress these materials using pressure) is not zero; for an ideal gas, it is exactly equal to the pressure. One can relate this relation to the density $m/V$ using the ideal gas law $PV=nRT$ and the molecular weight of the gas.
For condensed matter, the stiffness generally scales up with the density:

The reason is that both properties depend on the pair potential between atoms; if the atoms are strongly bonded, then their spacing is generally small; thus, the density is high. In addition, the curvature of the pair potential at the equilibrium position is large, which is exactly equivalent to saying that the material is stiff:

(A third implication to strong bonding is that the pair potential dips deep and that the material is refractory, i.e., it has a high melting temperature):

An active area of research is to precisely define the pair potential in condensed matter to theoretically predict both stiffness and density; this is something you might pursue in an academic or industry environment.
Comment: Those graphs are for the elements. I suspect that including salts, oxides, and other compounds would leave even less of a correlation.


Is there any restriction as to how states choose presidential electors?

Question: If I understand correctly, state legislatures are empowered to select electors, but all of them have chosen to allow a popular vote. How much discretion do they have in choosing methods for selecting electors? Would it be constitutional/legal for them to pass a law saying that three-year-olds can vote? Or that they choose electors by a random process similar to the process for selecting people for jury duty, then each elector flips a coin, and votes Democrat if it's heads, Republican if it's tails? Could they amend their state or constitution to say that their legislature must vote Libertarian in every future election?
Answer: No, not beyond what's in the Constitution

Each State shall appoint, in such Manner as the Legislature thereof may direct, a Number of Electors, equal to the whole Number of Senators and Representatives to which the State may be entitled in the Congress: but no Senator or Representative, or Person holding an Office of Trust or Profit under the United States, shall be appointed an Elector.

Originally, electors in all states were appointed by the state legislatures - that was legal then and there is no reason to believe it wouldn't be legal now. Between then and now, there have been several methods used - the current "short ballot" method dates only from the early 20th century.
Beyond the limit that no Federal employee or officer and no one who has been disqualified from holding Federal office by the Congress may be an elector, the discretion on how it happens rests with the state legislatures.
Comment: One big issue brewing before the U.S. Supreme Court right now is whether the language in bold simply means "according to state law just like any other state law" or whether it is special in some way and allows the legislature to disregard, for example, state court rulings and state constitutions.
Answer: Taking Washington state as an example, each political party or unaffiliated candidate for president files a list of their electors, and an alternative, with the Secretary of State (RCW 29A.56.082. No laws mandate how the electors for a party / candidate are selected – they are not actually elected except by party officials, and their names do not appear on any ballot.
When it has been determined that party X (or candidate Y, but let's face it) has won the popular vote, the list from party X thus constitutes the set of electors for Washington. They are also required to promise to vote for that party's candidate, following RCW 29A.56.084. The legislature could change these rules in whatever manner they would like.
A state can lower the voting age (the 26th Amendment sets the voting age at no more than 18 years, and HJR 4213 sought to lower the voting age to 16. The minimum voting age is written into the state constitution, in Art. VI, so a constitutional amendment plus enabling legislation would be required to allow 3 year olds to vote.