text:
Q: Is there a way to display a countdown or stopwatch timer in a terminal? How can I display a real-time countdown timer on the Linux terminal? Is there an existing app or, even better, a one liner to do this?

A: I was looking for the same thing and ended up writing something more elaborate in Python:
This will give you a simple 10-second countdown:
pip install termdown
termdown 10

Source: https://github.com/trehn/termdown

A: I use this small Go program:
package main

import (
   "fmt"
   "time"
)

func format(d time.Duration) string {
   mil := d.Milliseconds() % 1000
   sec := int(d.Seconds()) % 60
   min := int(d.Minutes())
   return fmt.Sprintf("%v m %02v s %03v ms", min, sec, mil)
}

func main() {
   t := time.Now()
   for {
      time.Sleep(10 * time.Millisecond)
      s := format(time.Since(t))
      fmt.Print("\r", s)
   }
}

https://github.com/89z/sienna/tree/master/cmd/stopwatch

A: Another approach
countdown=60 now=$(date +%s) watch -tpn1 echo '$((now-$(date +%s)+countdown))'

For Mac:
countdown=60 now=$(date +%s) watch -tn1 echo '$((now-$(date +%s)+countdown))'
#no p option on mac for watch

If one wants a signal when it hits zero, one could e.g. build it with a command that returned a non-zero exit status at zero and combine it with watch -b, or something, but if one wants to build a more elaborate script, this is probably not the way to go; it is more of a "quick and dirty one-liner" type solution.

I like the watch program in general. I first saw it after I had already written countless while sleep 5; do loops to different effects. watch was demonstrably nicer.

A: I have combined terdon's very good answer, into a function which at the same time displays the time since the start, and the time till the end. There are also three variants, so it's easier to call (you don't have to do Bash math), and it's also abstracted.
Example of use:
{ ~ }  » time_minutes 15
Counting to 15 minutes
Start at 11:55:34     Will finish at 12:10:34
     Since start: 00:00:08     Till end:  00:14:51

And something like a work timer:
{ ~ }  » time_hours 8
Counting to 8 hours
Start at 11:59:35   Will finish at 19:59:35
     Since start: 00:32:41     Till end:  07:27:19

And if you need some very specific time:
{ ~ }  » time_flexible 3:23:00
Counting to 3:23:00 hours
Start at 12:35:11   Will finish at 15:58:11
     Since start: 00:00:14     Till end:  03:22:46

Here's the code to put into your .bashrc
function time_func()
{
   date2=$((`date +%s` + $1));
   date1=`date +%s`;
   date_finish="$(date --date @$(($date2)) +%T )"

   echo "Start at `date +%T`   Will finish at $date_finish"

    while [ "$date2" -ne `date +%s` ]; do
     echo -ne "     Since start: $(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)     Till end:  $(date -u --date @$(($date2 - `date +%s`)) +%H:%M:%S)\r";
     sleep 1
    done

    printf "\nTimer finished!\n"
    play_sound ~/finished.wav
}

function time_seconds()
{
  echo "Counting to $1 seconds"
  time_func $1
}

function time_minutes()
{
  echo "Counting to $1 minutes"
  time_func $1*60
}

function time_hours()
{
  echo "Counting to $1 hours"
  time_func $1*60*60
}

function time_flexible()  # Accepts flexible input hh:mm:ss
{
    echo "Counting to $1"
    secs=$(time2seconds $1)
    time_func $secs
}

function play_sound()  # Adjust to your system
{
    cat $1 > /dev/dsp
}

function time2seconds() # Changes hh:mm:ss to seconds. Found in some other Stack Exchange answer
{
    a=( ${1//:/ })
    echo $((${a[0]}*3600+${a[1]}*60+${a[2]}))
}

Combine this with some way of playing sound in linux terminal (Play MP3 or WAV file via the Linux command line) or Cygwin (cat /path/foo.wav > /dev/dsp works for me in Babun/Windows 7) and you have a simple flexible timer with alarm!

A: sw is a simple stopwatch that will run forever.

Install
wget -q -O - http://git.io/sinister | sh -s -- -u https://raw.githubusercontent.com/coryfklein/sw/master/sw

Usage
sw
 - start a stopwatch from 0, save start time in ~/.sw
sw [-r|--resume]
 - start a stopwatch from the last saved start time (or current time if no last saved start time exists)
 - "-r" stands for --resume

A: I'm surprised that nobody used the sleepenh tool in their scripts. Instead, the proposed solutions either use a sleep 1 between subsequent timer outputs or a busy loop that outputs as fast as possible. The former is inadequate because due to the small time spent doing the printing, the output will not actually happen once per second but a bit less than that which is suboptimal. After enough time passed, the counter will skip a second. The latter is inadequate because it keeps the CPU busy for no good reason.
The tool that I have in my $PATH looks like this:
#!/bin/sh
if [ $# -eq 0 ]; then
    TIMESTAMP=$(sleepenh 0)
    before=$(date +%s)
    while true; do
        diff=$(($(date +%s) - before))
        printf "%02d:%02d:%02d\r" $((diff/3600)) $(((diff%3600)/60)) $((diff%60))
        TIMESTAMP=$(sleepenh $TIMESTAMP 1.0);
    done
    exit 1 # this should never be reached
fi
echo "counting up to $@"
"$0" &
counterpid=$!
trap "exit" INT TERM
trap "kill 0" EXIT
sleep "$@"
kill $counterpid

The script can either be used as a stop watch (counting up until interrupted) or as a timer that runs for the specified amount of time. Since the sleep command is used, this script allows to specify the duration for which to count in the same precision as your sleep allows. On Debian and derivatives, this includes sub-second sleeps and a nice human-readable way to specify the time. So for example you can say:
$ time countdown 2m 4.6s
countdown 2m 4.6s  0.00s user 0.00s system 0% cpu 2:04.60 total

And as you can see, the command ran exactly for 2 minutes and 4.6 seconds without much magic in the script itself.
EDIT:
The sleepenh tool comes from the package of the same name in Debian and its derivatives like Ubuntu. For distributions that don't have it, it comes from  https://github.com/nsc-deb/sleepenh
The advantage of sleepenh is, that it is able to take into account the small delay that accumulates over time from the processing of other things than the sleep during a loop. Even if one would just sleep 1 in a loop 10 times, the overall execution would take a bit more than 10 seconds because of the small overhead that comes from executing sleep and iterating the loop. This error slowly accumulates and would over time make our stopwatch timer more and more imprecise. To fix this problem, one must each loop iteration compute the precise time to sleep which is usually slightly less than a second (for one second interval timers). The sleepenh tool does this for you.

A: Use leave (it at least works on BSD descendants):
man leave

Set a timer for 15 minutes:
leave +0015
Alarm set for Thu Nov  3 14:19:31 CDT 2016. (pid 94317)

A: I ended up writing my own shell script: GitHub gist
#!/bin/sh
# script to create timer in terminal
# Jason Atwood
# 2013/6/22

# Start up
echo "starting timer script ..."
sleep 1 # seconds

# Get input from user
read -p "Timer for how many minutes?" -e DURATION
DURATION=$(( $DURATION*60 )) # convert minutes to seconds

# Get start time
START=$(date +%s)

# Infinite loop
while [ -1 ]; do
clear # Clear window

# Do math
NOW=$(date +%s)    # Get time now in seconds
DIF=$(( $NOW-$START ))    # Compute diff in seconds
ELAPSE=$(( $DURATION-$DIF ))    # Compute elapsed time in seconds
MINS=$(( $ELAPSE/60 ))    # Convert to minutes... (dumps remainder from division)
SECS=$(( $ELAPSE - ($MINS*60) )) # ... and seconds

# Conditional
if [ $MINS == 0 ] && [ $SECS == 0 ]    # if mins = 0 and secs = 0 (i.e. if time expired)
then # Blink screen
for i in `seq 1 180`; # for i = 1:180 (i.e. 180 seconds)
do
clear # Flash on
setterm -term linux -back red -fore white # use setterm to change background color
echo "00:00 " # extra tabs for visibility

sleep 0.5

clear # Flash off
setterm -term linux -default # Clear setterm changes from above
echo "00:00" # (I.e. go back to white text on black background)
sleep 0.5
done # End for loop
break    # End script

else # Else, time is not expired
echo "$MINS:$SECS"    # Display time
sleep 1 # Sleep 1 second
fi    # End if
done    # End while loop

A: Take a look at TermTime. It's a nice terminal based clock and stopwatch:
pip install termtime

A: I'm not sure why you need beep. If all you want is a stopwatch, you can do this:
while true; do printf '%s\r' "$(date)"; done

That will show you the seconds passing in realtime and you can stop it with Ctrl+C.
If you need greater precision, you can use this to give you nanoseconds:
while true; do printf '%s\r' "$(date +%H:%M:%S:%N)"; done

Finally, if you really, really want "stopwatch format", where everything starts at 0 and starts growing, you could do something like this:
start=$(date +%s)
while true; do
    time="$(($(date +%s) - $start))"
    printf '%s\r' "$(date -u -d "@$time" +%H:%M:%S)"
done

For a countdown timer (which is not what your original question asked for) you could do this (change seconds accordingly):
seconds=20
start="$(($(date +%s) + $seconds))"
while [ "$start" -ge `date +%s` ]; do
    time="$(( $start - `date +%s` ))"
    printf '%s\r' "$(date -u -d "@$time" +%H:%M:%S)"
done

You can combine these into simple commands by using bash (or whichever shell you prefer) functions.
In bash, add these lines to your ~/.bashrc (the sleep 0.1 will make the system wait for 1/10th of a second between each run so you don't spam your CPU):
countdown() {
    start="$(( $(date '+%s') + $1))"
    while [ $start -ge $(date +%s) ]; do
        time="$(( $start - $(date +%s) ))"
        printf '%s\r' "$(date -u -d "@$time" +%H:%M:%S)"
        sleep 0.1
    done
}

stopwatch() {
    start=$(date +%s)
    while true; do
        time="$(( $(date +%s) - $start))"
        printf '%s\r' "$(date -u -d "@$time" +%H:%M:%S)"
        sleep 0.1
    done
}

You can then start a countdown timer of one minute by running:
countdown 60

You can countdown two hours with:
countdown "$((2 * 60 * 60))"

or a whole day using:
countdown "$((24 * 60 * 60))"

And start the stopwatch by running:
stopwatch

If you need to be able to deal with days as well as hours, minutes and seconds, you could do something like this:
countdown() {
    start="$(( $(date +%s) + $1))"
    while [ "$start" -ge $(date +%s) ]; do
        ## Is this more than 24h away?
        days="$(($(($(( $start - $(date +%s) )) * 1 )) / 86400))"
        time="$(( $start - `date +%s` ))"
        printf '%s day(s) and %s\r' "$days" "$(date -u -d "@$time" +%H:%M:%S)"
        sleep 0.1
    done
}

stopwatch() {
    start=$(date +%s)
    while true; do
        days="$(($(( $(date +%s) - $start )) / 86400))"
        time="$(( $(date +%s) - $start ))"
        printf '%s day(s) and %s\r' "$days" "$(date -u -d "@$time" +%H:%M:%S)"
        sleep 0.1
    done
}

Note that the stopwatch function hasn't been tested for days since I didn't really want to wait 24 hours for it. It should work, but please let me know if it doesn't.

A: For future reference, there is a command line tool called µTimer with very straightforward command line options for a countdown/count-up timer.

A: Short answer:
for i in `seq 60 -1 1` ; do echo -ne "\r$i " ; sleep 1 ; done

Explanation:
I know there are a lot of answers, but I just want to post something very close to OP's question, that personally I would accept as indeed "oneliner countdown in terminal". My goals were:

*

*One liner.

*Countdown.

*Easy to remember and type in console (no functions and heavy logic, bash only).

*Does not require additional software to install (can be used on any server I go via ssh, even if I do not have root there).

How it works:

*

*seq prints numbers from 60 to 1.

*echo -ne "\r$i " returns caret to beginning of the string and prints current $i value. Space after it is required to overwrite previous value, if it was longer by characters than current $i (10 -> 9).

A: I've used this one:
countdown()
(
  IFS=:
  set -- $*
  secs=$(( ${1#0} * 3600 + ${2#0} * 60 + ${3#0} ))
  while [ $secs -gt 0 ]
  do
    sleep 1 &
    printf "\r%02d:%02d:%02d" $((secs/3600)) $(( (secs/60)%60)) $((secs%60))
    secs=$(( $secs - 1 ))
    wait
  done
  echo
)

Example:
 countdown "00:07:55"

Here's a source.

A: My favorite way is:
Start:
time cat

Stop:
ctrl+c

As @wjandrea commented below, another version is to run:
time read

and press Enter to stop

A: A Python example:
#!/usr/bin/python

def stopwatch ( atom = .01 ):
    import time, sys, math

    start = time.time()
    last = start
    sleep = atom/2
    fmt = "\r%%.%sfs" % (int(abs(round(math.log(atom,10))))  if atom<1 else "")
    while True:
        curr = time.time()
        subatom = (curr-last)
        if subatom>atom:
            # sys.stdout.write( "\r%.2fs" % (curr-start))
            sys.stdout.write( fmt % (curr-start))
            sys.stdout.flush()
            last = curr
        else:
            time.sleep(atom-subatom)

stopwatch()

A: Pretend you are a person on OS X looking for a command line stopwatch. Pretend that you don't want to install the gnu tools and just want to run with the Unix date.
In that case do as terdon says, but with this modification:
function stopwatch(){
    date1=`date +%s`;
    while true; do
        echo -ne "$(date -jf "%s" $((`date +%s` - $date1)) +%H:%M:%S)\r";
        sleep 0.1
    done
}

A: Simply use watch + date in UTC time.  You can also install some package for big display...
export now="`date +%s -u`";
watch -n 0,1 'date +%T -u -d @$((`date +%s` - $now ))'

#Big plain characters
watch -n 0,1 'date +%T -u -d @$((`date +%s` - $now )) | toilet -f mono12'

#Big empty charaters
watch -n 0,1 'date +%T -u -d @$((`date +%s` - $now )) | figlet -c -f big'

Try it!
See also http://www.cyberciti.biz/faq/create-large-colorful-text-banner-on-screen/

A: just a one liner
N=100; while [[ $((--N)) >  0 ]]; do  echo  $N |  figlet -c && sleep 1 ; done

screenhost

Also we can clear the screen ( Terminal ) using ANSI Escape sequences using 2J format.
N=100; while [[ $((--N)) >  0 ]]; do  echo -e "\033[2J\033[0m"; echo "$N" |  figlet -c && sleep 1 ; done

NOTE
installing figlet command is required if you need in BIG font, otherwise remove figlet part.
N=100; while [[ $((--N)) >  0 ]]; do  echo  $N  && sleep 1 ; done

and you can make to have a beautiful output using lolcat ...
N=100; while [[ $((--N)) >  0 ]]; do  echo "$N" |  figlet -c | lolcat &&  sleep 1 ; done

screenhsot

A: If your system already has Ruby, you can use:
#!/usr/bin/env ruby

n = ARGV[0].to_f
go_beginning_of_line = "\033[G"
clear_till_end_of_line = "\033[K"

time_end = Time.now + n
while Time.now < time_end
    more = time_end - Time.now
    print "#{go_beginning_of_line}Counting down #{more.round(1)} of #{n} seconds#{clear_till_end_of_line}"
    sleep [0.1, more].min
end
puts "#{go_beginning_of_line}Counting down #{n} seconds. \a\aDone.#{clear_till_end_of_line}"

A: This is a terminal based timer:
https://github.com/naa-7/terminal_work_timer

A: If you have pv installed, you can use the following one-liner to display a countdown timer and sleep for a minute (or any other amount of time, just change 60 to the desired number of seconds):
cat /dev/zero | pv -B 1 -L 1 -tpe -s 60 -S > /dev/null

You can also put it in a function:
sleep_with_progress() {
  cat /dev/zero | pv -B 1 -L 1 -tpe -s "$1" -S > /dev/null
}

# If you prefer a simpler output with just the countdown:
sleep_with_countdown() {
  cat /dev/zero | pv -B 1 -L 1 -e -s "$1" -S > /dev/null
}

Sample outputs taken at 5 seconds after starting:
user@host:~ $ sleep_with_progress 60
0:00:05 [===>                                                  ]  8% ETA 0:00:55

user@host:~ $ sleep_with_countdown 60
ETA 0:00:55

Explanation:
cat /dev/zero produces an infinite amount of ASCII zero (\0) characters. pv displays progress, rate limits the data flowing through it and terminates after 60 characters (details below). Finally, the redirection to /dev/null makes sure that the \0 characters are not sent to the terminal.
The parameters used for pv are:

*

*-B 1 sets the buffer size to 1.

*-L 1 rate limits the pipe to 1 character per second.

*-tpe turns on the display of the time, progress and ETA indicators (while -e only shows the latter).

*-s 60 specifies that pv should expect 60 bytes.

*-S tells pv to stop after reaching the specified size even though the input continues (it is infinite).

A: Simple one liner to do the countdown job:
cnt=10;until [ $cnt -eq 0 ]; do printf "\rYour Quiz will start in $cnt seconds.... ";sleep 1;cnt=$(expr $cnt - 1);done;echo;

This one liner is taken from my open source project called Automated_Quiz, which is hosted here : https://sourceforge.net/projects/automated-quiz/
For Stopwatch :
Paste the following three lines one by one on the terminal and press enter. Press Ctrl+c on the second line to exit the stopwatch, as required.
function stopwatch() {  cntd=$1; printf '%dd:%dh:%dm:%ds\n' $((cntd/86400)) $((cntd%86400/3600)) $((cntd%3600/60)) $((cntd%60)) ; };

cnt=0;while true; do printf "\rStopwatch : $cnt seconds";export var=$cnt;sleep 1;cnt=$(expr $cnt + 1);done;echo;

stopwatch $var

A: This is similar to the accepted answer, but terdon's countdown() gave me syntax errors. This one works great for me, though:
function timer() { case "$1" in -s) shift;; *) set $(($1 * 60));; esac; local S=" "; for i in $(seq "$1" -1 1); do echo -ne "$S\r $i\r"; sleep 1; done; echo -e "$S\rTime's up!"; }

You can put it in .bashrc and then execute with: timer t (where t is time in minutes).

A: Found this question earlier today, when looking for a term application to display a large countdown timer for a workshop. None of the suggestions was exactly what I needed, so I quickly put another one together in Go: https://github.com/bnaucler/cdown
As the question is already sufficiently answered, consider this to be for the sake of posterity.

A: $ sleep 1500 && xterm -fg yellow -g 240x80 &
When that big terminal with yellow text jumps up, time to get up and stretch!
Notes:
 - 1500 seconds = 25 minute pomodoro
 - 240x80 = terminal size with 240 character row, and 80 rows. Fills up a screen for me noticeably.
Credit: http://www.linuxquestions.org/questions/linux-newbie-8/countdown-timer-for-linux-949463/

A: A GUI version of the stopwatch
date1=`date +%s`
date1_f=`date +%H:%M:%S____%d/%m`
(
  while true; do
    date2=$(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)
    echo "# started at $date1_f \n$date2"
  done
) |
zenity --progress \
  --title="Stop Watch" \
  --text="Stop Watch..." \
  --percentage=0

A: Another option under the "existing app" category: peaclock. Displays a "large" stopwatch, timer, or clock in the terminal. Quite a few key bindings facilitate interactive use.

A: A slightly shorter Python (3) example:
import sys
import time
from datetime import datetime
from datetime import timedelta

start = time.time() * 1000
while True:
    try:
        now = time.time() * 1000
        elapsed = now - start
        out = str(timedelta(milliseconds=elapsed))
        print(out + "\033[?25l", end='\r')
    except KeyboardInterrupt:
        print(out + '\033[?25h', end='\n')
        sys.exit(0)

Hides / restores blinking cursor.
Control-c to quit.

A: I'd like to suggest "timer" for a large countdown clock. It's similar to termdown but it's written in Rust and provides a nice beep at the end.

Usage
timer 11:00

timer 25min

Install
cargo install timer_core

Source: https://github.com/pando85/timer

A: I added a progress bar to and unlied the variable names in terdon's answer:
countdown() {
  stop="$(( $(date '+%s') + $1))"
  term_width=$(tput cols)
  counter_width=10
  while [ $stop -ge $(date +%s) ]; do
    delta="$(( $stop - $(date +%s) ))"
    complete_percent=$(( 100 - ($delta * 100) / $1))
    bar_width=$(($complete_percent * ($term_width - $counter_width) / 100))
    printf '\r'
    printf '%s ' "$(date -u -d "@$delta" +%H:%M:%S)"
    printf '%0.s-' $(seq 1 $bar_width)
    sleep 0.5
  done
  printf '\n'
}

It outputs something like:

00:00:05 --------------------

A: If you would like a compilable program for whatever reason, the following would work:
#include <iostream>
#include <string>
#include <chrono>

int timer(seconds count) {
  auto t1 = high_resolution_clock::now();
  auto t2 = t1+count;
  while ( t2 > high_resolution_clock::now()) {
    std::cout << "Seconds Left:" <<
    std::endl <<
      duration_cast<duration<double>>(count-(high_resolution_clock::now()-t1)).count() <<
    std::endl << "\033[2A\033[K";
    std::this_thread::sleep_for(milliseconds(100));
  }
  std::cout << "Finished" << std::endl;
  return 0;
}

This can be used in other programs as well and easily ported, if a Bash environment isn't available or you just prefer using a compiled program.
GitHub


text:
Q: VIM/Python: visualmode/mode detection function! Delete() range
python3 << EOF
import vim

vim.command('let x = visualmode()')
mode = vim.eval('x')

EOF
endfunction

I'm not able to detect 'mode' properly in vim (xterm). It can't switch between 'visual' 'normal' - i get 'n' or '^V' always, regardless of what mode i'm actually in. I invoke the function like so:
 :map <kDel> :call Delete()<CR>
:imap <kDel> <Esc>l:call Delete()<CR>
:vmap <kDel> <Esc>:call Delete()<CR>

How exactly are these functions used?

A: This simplified version of your function (please use testable examples):
function! Delete() range
    python << EOF
    import vim

    print vim.eval('visualmode()')

    EOF
endfunction

does exactly what it is supposed to do:

*

*if the last visual mode was plain visual mode, it echoes v,

*if the last visual mode was visual-line mode, it echoes V,

*if the last visual mode was plain visual-block mode, it echoes ^V.

Of course, you would do the following in your real function:
mode = vim.eval('visualmode()')

What, exactly, do you expect and what, exactly, are you trying to achieve?
--- edit ---
From :help visualmode(), emphasis mine:

The result is a String, which describes the last Visual mode used in the current buffer.

So it is obvious that visualmode() can't be used to know the current mode. The right function is mode().
From :help mode(), emphasis mine:

This is useful in the 'statusline' option or when used
  with remote_expr() In most other places it always returns
  "c" or "n".

So using straight mode() in most contexts will be useless, as demonstrated by the mappings below that all put you in normal mode before calling mode() so you always get n.
function! Delete() range
    python << EOF
    import vim

    print vim.eval('mode()')

    EOF
endfunction

nmap <key> :call Delete()<CR>         --> n
imap <key> <Esc>:call Delete()<CR>    --> n
xmap <key> <Esc>:call Delete()<CR>    --> n

For mode() to return the value you want, you need to be in an expression context which allows you to evaluate stuff without leaving the current mode:
nmap <expr> <key> Delete()            --> n
imap <expr> <key> Delete()            --> i
xmap <expr> <key> Delete()            --> v, V or ^V

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to clear HttpAuthRequest credentials I'm doing an app that logs users into websites that have an authentication popup using webView.
The problem comes when logging in and then going back to log in with different credentials, causing to skip HttpAuthRequest and therefore being logged in with the first credentials
What should I do?

A: The below lines of code is enough for clearing the cookies of Web View
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
CookieSyncManager.getInstance().sync();

Happy Coding! Thanks.

A: I did the trick logging in like this:
// Prefix http:// or https://
String prefix = url.substring(0, url.indexOf("/") + 2);

// Prefix + username +: + password + @ + url without prefix
String finalUrl = prefix + username + ":" + password + "@" + url.substring(url.indexOf("/") + 2);

webView.loadUrl( finalUrl );

Instead of using onReceivedHttpAuthRequest


text:
Q: Extract matching groups from string python regex I am trying to extract matching groups from a Python string but facing issues.
The string looks like below.
1. TITLE ABC Contents of title ABC and some other text 2. TITLE BCD This would have contents on
title BCD and maybe something else 3. TITLE CDC Contents of title cdc

And i would need anything starting with a number and capital letters as the title and extract the contents in that title.
This is the output I am expecting.
1. TITLE ABC Contents of title ABC and some other text
2. TITLE BCD This would have contents on title BCD and maybe something else
3. TITLE CDC Contents of title cdc

I tried with the below regex
(\d\.\s[A-Z\s]*\s)

and get the below.
1. TITLE ABC
2. TITLE BCD
3. TITLE CDC

If i try adding .* at the end of the regex the matching groups are affected.
I think I am missing something simple here. Tried with whatever I knew but couldn't solve it.
Any help here is appreciated.

A: Use (\d+\.[\da-z]* [A-Z]+[\S\s]*?(?=\d+\.|$))
Below is the relevant code
import re
text = """1. TITLE ABC Contents of title ABC and some other text 2. TITLE BCD This would have contents on
title BCD and maybe something else 3. TITLE CDC Contents of title cdc"""

result = re.findall('('
                    '\d+\.'   # Match a number and a '.' character
                    '[\da-z]*' # If present include any additional numbers/letters
                    '(?:\.[\da-z])*' # Match additional subpoints.
                                     # Each of these subpoints must start with a '.'
                                     # And then have any combination of numbers/letters
                    ' '   # Match a space. This is how we know to stop looking for subpoints,
                          # and to start looking for capital letters
                    '[A-Z]+'  # Match at least one capital letter.
                              # Use [A-Z]{2,} to match 2 or more capital letters
                    '[\S\s]*?'  # Match everything including newlines.
                                # Use .*? if you don't care about matching newlines
                    '(?=\d+\.|$)'  # Stop matching at a number and a '.' character,
                                   # or stop matching at the end of the string,
                                   # and don't include this match in the results.
                    ')'
                    , text)

And here's a more detailed explanation of each regex character used

A: In your regex you're missing the lowercase letters in character group so it matches only the uppercase words
You can simply use this
(\d\.[\s\S]+?)(?=\d+\.|$)

Sample code
import re
text = """1. TITLE ABC Contents of 14 title ABC and some other text 2. TITLE BCD This would have contents on
title BCD and maybe something else 3. TITLE CDC Contents of title cdc"""
result = new_s = re.findall('(\d\.[\s\S]+?)(?=\d+\.|$)', text)
print(result)

output

['1. TITLE ABC Contents of 14 title ABC and some other text ', '2. TITLE BCD This would have contents on \ntitle BCD and maybe
something else ', '3. TITLE CDC Contents of title cdc']

Regex demo
Note:- You can even replace [\s\S]+? with .*? as if you're are using single line flag  so . will match newline characters too

A: You can use re.findall with re.split:
import re
s = "1. TITLE ABC Contents of title ABC and some other text 2. TITLE BCD This would have contents on title BCD and maybe something else 3. TITLE CDC Contents of title cdc"
t, c = re.findall('\d+\.\s[A-Z]+', s), list(filter(None, re.split('\d+\.\s[A-Z]+', s)))
result = [f'{a}{b}' for a, b in zip(t, c)]

Output:
['1. TITLE ABC Contents of title ABC and some other text ', '2. TITLE BCD This would have contents on title BCD and maybe something else ', '3. TITLE CDC Contents of title cdc']

A: import re
a=r'1. TITLE ABC Contents of 2title ABC and some other text 2. TITLE BCD This would have contents on title BCD and maybe something else 3. TITLE CDC Contents of title cdc'
res = re.findall('(\d\.\s[A-Za-z0-9\s]*\s)', a)
for e in map(str, res):
    print(e)

output
1. TITLE ABC Contents of 2title ABC and some other text
2. TITLE BCD This would have contents on title BCD and maybe something else
3. TITLE CDC Contents of title


text:
Q: Only some css being used I'm extremely puzzled and coming for help.  I'm editing a Wordpress theme and within 5 lines of the css it just stops "reading" it.
I cannot post an example in jsfiddle or cssdesk due to me using captions in Wordpress and that isn't supported.
Also, what bugs me, is that this was working earlier.  Went to dinner, now it's not.
http://continuum.theneocloud.com/echo-pedicure-chair/
Is the dev site.  It should be 3 rows of pictures on the bottom, with the headers in between.  Like I said, worked before.  The browser is seeing the css file, as I can go to inspect element, and see the stylesheet being loaded.
Example problem:  The headers aren't clearing floats, the bottom pictures aren't floating, even though the css is correct.

A: On line 1522 of this file, you have this declaration:
#content ol li, #content ul li, .content_full_width ol li, , .content_full_width ul li {margin-bottom: 5px;}

There's an extra comma there, creating a parse error.
Furthermore, on line 20 of this file, you're ending the rule with a right parenthesis, instead of a right brace.
#Echo_Plus_Upholstery_Options {float:left;margin-left:25%;)

A: One issue you are having is that you are not clearning your floats properly.
Add this to your CSS:
h4.picture_titles{
    clear: both;
}

Since every
 you have down there floats left (#CurvedBase, #echo_options and #Echo_Plus_Upholstery_Options), the following heading is off.

A: Add float:left to all the 3 image tags.
i.e inside the


text:
Q: Converting numbers to a string number function foo(num1,num2,num3){
    var result ="";
    var sum = 0;

    sum = (num1*num2*num3);

    for(var i =sum; i > 0; i--){
        var str = i.toString();
        console.log(str);

        for(var j=0; j<str.length;j++){
            result = str[j] + result;
        }

        if(result === str){
           return result;
        }
    }
}

I am trying to convert the number from the first for loop so i can use the same number in the second for loop as a string. because I want to access the index of the number. for instance,
var str = "1234";
str[0] = 1;
but, when the second loop runs, it will return unrelated output
does anyone know how to fix it ? please

A: var num = 123; // The value of num is 123 - this is a number
var sum = num.toString(); // The value of sum is "123" - this is a string

console.log(num) // This logs 123 - this is a number
console.log(sum) // This logs "123" - this is a string

sum.length // This logs 3


text:
Q: How to add newly updated dynamic values in state to old object in React.js? I am creating a CRUD app in Java + React.js. I want to update user information, I am populating a dynamic form based on the employeeDetails array. On a result I am getting dynamically updated values from user in state. But I am not sure how to add those new input values from the form to old object, and update it to and send it to backend. Thanks in advance your help is appreciated.
I tried doing this.setState() after submitting form, to update old object with new values.
State of react app:
state = {
    employeeDetails: ['Name', 'Gender', 'Education', 'Address', 'Mobile Number', 'Experience'],
    editEmployee: {
     Name: "Rohan",
     Gender: 23,
     Education: "Software Engineer",
     Mobile Number: 12345,
     Experience: "Fresher"
    }
  }

Dynamic form of update user:
<form onSubmit={props.updateEmployee}>
   {
     Object.keys(props.editEmployee).map(details => <Fragment key={details}>
         {details}

         <input type="text" name={details} onChange={props.handleChange} defaultValue={props.editEmployee[details]} />
 </Fragment>
)}

Update method:
updateEmployee = (e) => {
    e.preventDefault();
    this.setState({
    editEmployee: {...this.state.editEmployee, dynamic value}
    })
    axios.put("http://localhost:9450/updateEmployee", this.state.editEmployee)
      .then(res => console.log(res))
      .then(this.setState({
        editEmployee: ''
      }))
  }

I want the newly updated values in my editEmployee object which I will send to backend server to update the user information.

A: Looking at your code, assuming that your Form is another separate component.
const Form = (props) => (
  <form onSubmit={props.updateEmployee}>
    {Object.keys(props.editEmployee).map((details) => (
      <React.Fragment key={details}>
        {details}

        <input type="text" name={details} onChange={props.handleChange} defaultValue={props.editEmployee[details]} />
      </React.Fragment>
    ))}
  </form>
);

In your parent container you have state and methods
state = {
  employeeDetails: ['Name', 'Gender', 'Education', 'Address', 'Mobile Number', 'Experience'],
  editEmployee: {
    Name: "Rohan",
    Gender: 23,
    Education: "Software Engineer",
    'Mobile Number': 12345,
    Experience: "Fresher"
  }
}

handleChange = (e) => {
  this.setState({
    editEmployee: {
      ...this.state.editEmployee,
      [e.target.name]: e.target.value,
    },
  })
}

updateEmployee = (e) => {
  e.preventDefault();
  axios.put("http://localhost:9450/updateEmployee", this.state.editEmployee)
    .then(res => console.log(res))
}

Your handleChange should update the state values and you don't have to call setState during your form submission. You should already have the latest changes in your state when you call updateEmployee


text:
Q: "Bad_pool_caller" bluescreen. How to figure out what's causing it I bought my HP 15-r085no in September last year. After a while, I got a few bluescreens with the accompanying horrible sound. There was two (I think) different bluescreens, where one of them was with the message "Bad_pool_caller". I cant remember the other one.
I updated the graphic driver. I don't know if that was what fixed it, but at least it didn't happen again - until now.
One day at the endo of last week, I had two bluescreens with "bad_pool_caller". The day after I had none. I updated my graphics driver once more. Sunday and Monday passed with no bluescreens. During the last 30 minutes, I've gotten two more bluescreen of the same type, while typing a question on the LaTeX pages and typing this question.
What can be causing this bluescreen? Is it software or hardware related? How do I troubleshoot this? The bluescreens says something about collecting some error info. Can this information be helpful? Where do I find it?
Bluescreen pictures:

Screendump from BlueScreenView:

EDIT: Added log from BlueScreenView
EDIT 2: Can OneDrive for business be causing the trouble? I'm at least having a lot of trouble with it!


text:
Q: Why is my pointer being changed? Long story short, I am developing a simple game, and I have a Game object that keeps track of the current game state, as well as some additional things that are useful/required later on.  One of these is a reference to the UIViewController that loaded the game, which is simply declared as a property on the object:
@interface Game : NSObject {
    //ivars
}

@property (nonatomic, retain) myViewController* viewController;

The getters/setters for this property are generated using @synthesize viewController, and all seems well.
Now there are only two paths through which this property is accessed, when the game is won and when the game is lost.  The "game is lost" path works fine.  The "game is won" path is causing a bizarre error in which the value of the viewController pointer seems to get overwritten with garbage.
In order to figure out what is going on, I overrode the getters and setters as follows:
- (myViewController*) viewController {
    NSLog(@"Getting");
    return viewController;
}

- (void) setViewController:(myViewController*)controller {
    NSLog(@"Setting");
    viewController = controller;
}

...and set breakpoints inside (I know I'm not retaining the view controller is my setter, but that is not the issue; the view controller remains on the stack and does not actually need to be retained by Game).  Here is what I got in GDB:
//first call to setter
po controller
<myViewController: 0x9208130>

//call to getter on the "game is lost" path
(gdb) po viewController
<myViewController: 0x9208130>

//call to setter, starting a new game from the same view controller
(gdb) po controller
<myViewController: 0x9208130>

//call to getter on the "game is lost" path
(gdb) po viewController
0xbea2222c does not appear to point to a valid object.
(gdb) print viewController
$1 = (myViewController *) 0xbea2222c

So at some point, the value of the pointer was changed from 0x9208130 to 0xbea2222c, but I can't figure out where.  There is no code that assigns into the viewController property (or its backing ivar) apart from the call to the setter at the start of the game.  Yet clearly something is overwriting the value with garbage on the "game is won" path.
Is this possibly a buffer overrun issue?  If so what is a good approach for tracking it down?
Edit
I added a second pointer (as an ivar in another class) that I set to the value of game.viewController at the start of play, and using this pointer for the "game is won" path works.  So it appears to me that something is trashing the original pointer.  Still no idea what, however.

A: Your setter is wrong. It should read:
- (void) setViewController:(yeticonfettiViewController*)controller {
    NSLog(@"Setting");
    [viewController autorelease];
    viewController = [controller retain];
}

Otherwise you are never retaining the controller and it will likely be garbage collected.

A: It does not look like there is enough data to diagnose the problem from the information you have posted.
If you want to further debug this problem, I suggest setting a break point on the address in memory of the pointer ivar. That way you will be notified if it is somehow changed outside of your setter's use.
You can accomplish this by breaking at some point during your Game objects creation and selecting to "Watch Variable" on the Game object's controller ivar.
Alternatively, asksol has a good example of using gdb in a similar fashion external from Xcode in response to another question here.


text:
Q: Bounding the conditional expectation of a normally distributed random variable. The Question
We are given a random variable $X$ on a probability space $(\Omega, F, P)$. $X \sim N(0,\sigma^2)$. Given an event $H \in F$, what is the largest possible conditional expectation $E[X\vert H]$. This bound should be given in terms of $P(H)$.
What I've Done
I reason that, worst case, $H=\{X>\lambda\}$ for some $\lambda$. So I compute
\begin{align*}
E[X\vert H] &\leq \frac{1}{P(\{X>\lambda\})}\int_{\lambda}^\infty \frac{x}{\sqrt{2\pi\sigma^2}}e^{\frac{-x^2}{2\sigma^2}}dx \\
&=\frac{\frac{\sigma}{\sqrt{2\pi}}e^{\frac{-\lambda^2}{2\sigma^2}}}{\int_{\lambda}^\infty \frac{1}{\sqrt{2\pi\sigma^2}}e^{\frac{-x^2}{2\sigma^2}}dx} \\
&=\frac{\sigma^2e^{\frac{-\lambda^2}{2\sigma^2}}}{\int_{\lambda}^\infty e^{\frac{-x^2}{2\sigma^2}}dx}
\end{align*}
From here I'm thinking I could get this in to some manageable function of $\lambda$ or perhaps an approximation, and somehow convert that into a function $P(H)$.
I guess, ultimately it seems to come down to finding $\int_{\lambda}^\infty \frac{x}{\sqrt{2\pi\sigma^2}}e^{\frac{-x^2}{2\sigma^2}}dx$ as a function of $P(\{X>\lambda\})$. One observation I have is that the former appears to be the derivative of the latter (up to a constant). Not sure if that helps.
I'm not too knowledgeable about probability, so perhaps there is a much simpler or better approach altogether. Any help would be greatly appreciated.


text:
Q: Finding the basis for a subspace and relating it to the basis of the vector space Let's say we have a subspace $U$ defined by the set:
$U = span {((1, 2, 1, 2),(2, 1, 2, 1),(1, 1, 1, 0))}$,
which exists within a vector space $V$, where $V = \mathbb{R}^4$.
I've been asked to find the basis for $U$, which I found to be the set:
$((1,2,1,2),(0,1,0,0),(0,0,0,1))$, using row reduction of the matrix composed of the spanning set. But then the next part of the question asks me to 'complete the basis of $U$ to a basis of $V$'. I don't understand what the question means by 'completing'. Could anyone offer advice?

A: It means choosing a fourth vector so that your set spans $R^4$


text:
Q: Using function name as string to call a callable function from another class What I am trying to do is to call a function from the class called GeneralRules using the data I extracted. I use the rulename var to call the function. I tried to use call_user_func, but it returned a fatal error.
<?php
namespace Validat;
require_once '\..\vendor\autoload.php';
use Rules\GeneralRules;
class Validator
{
    private $RuleName,$GRules;
    private $_Fields=[];
    public function __construct(){
    $this->GRules = new GeneralRules;
    }
    public function ExtractData(array $Rule){
        foreach ($Rule as $key => $values){
            $this->RuleName = $key;
            $this->_Fields = $values;
        }
        if (is_callable($this->GRules->{$this->RuleName}(""))){
            echo "Callable";
        }
    }
}

EDIT 1: the code that triggers the error
    <?php
namespace Validat;
require_once '\..\vendor\autoload.php';
use Rules\GeneralRules;
use Errors\ErrorHandler;
use Errors\Errors;
class Validator
{
    private $RuleName,$GRules,$ErrorH;
    private $_Fields=[],$_Errors=[];
    public function __construct(){
    $this->GRules = new GeneralRules;
    $this->ErrorH = new ErrorHandler;
    }
    public function ExtractData(array $Rule){
        foreach ($Rule as $key => $values){
            $this->RuleName = $key;
            $this->_Fields = $values;
        }
        var_dump($this->_Fields);
        if (is_callable(array($this->GRules,$this->RuleName)))
           if( call_user_func($this->GRules->$this->RuleName,$this->_Fields[1])){
               echo "pass";
           }
           else
               $this->_Errors=$this->ErrorH->AddError($this->_Fields[0].' '.Errors::get('Errors/'.$this->RuleName));
    }
}

A: if (is_callable(array($this->GRules,$this->RuleName)))
   if( call_user_func($this->GRules->$this->RuleName,$this->_Fields[1])){

The problem is in front of your eyes: you check if a symbol is callable but you pass something else to call_user_func().
This is how you should do it:
if (is_callable(array($this->GRules, $this->RuleName)))
   if (call_user_func(array($this->GRules, $this->RuleName), $this->_Fields[1])){

Why the original code does not work?
It does not work as you tried because PHP interprets the expression $this->GRules->$this->RuleName from left to right:

*

*$this->GRules is an object of type GeneralRules;

*$this->GRules->$this: the second $this is converted to string (it's probably object if class Validator does not implement __toString()) and $this->GRules most probably does not have a property object; this makes $this->GRules->$this to evaluate to NULL;

*on the last step, NULL does not have the property RuleName and this triggers the fatal error.

You can hint PHP about how you want this expression to be evaluated by using curly braces around $this->RuleName:
if (call_user_func($this->GRules->{$this->RuleName}, $this->_Fields[1])){

This way PHP knows that $this->RuleName must be evaluated first; it produces a string out of it and then replaces it into the big expression to get what you need.
I recommend you use the first way exposed on top; it is more clear for the reader what you want to do: call method whose name is stored in $this->RuleName of the object stored in $this->GRules.


text:
Q: JSON Schema Restricting the Length of a Integer While restricting strings can be defined as
"last_name": {
            "type": "string",
            "maxLength": 30,
            "minLength": 1
          }

It does not work on integer as type, bec minimum and maximum is a range.
Is there a keyword we can use to specify length on integer using json-schema?

A: As described in the JSON schema found here: https://json-schema.org/understanding-json-schema/reference/numeric.html?highlight=integer

Ranges of numbers are specified using a combination of the
minimum and maximum keywords, (or exclusiveMinimum and
exclusiveMaximum for expressing exclusive range).
If x is the value being validated, the following must hold true:
x ≥ minimum x > exclusiveMinimum x ≤ maximum x < exclusiveMaximum
While you can specify both of minimum and exclusiveMinimum or both of
maximum and exclusiveMaximum, it doesn't really make sense to do so.
{   "type": "number",   "minimum": 0,   "exclusiveMaximum": 100 }

I think the keywords you are looking for are minimum and maximum or exclusiveMinimum and exclusiveMaximum.
Edit: After reading the question a bit more let me clarify what I mean.
I see you want to have the length of the integer and not the actual range, however if you want the length to be lets say 8 characters, you can pick the range between 0 and 99999999 to get the same effect.
Currently there are not a JSON specification available that specifies the exact length of a number.

A: The way I have solved this is using a regex pattern. Which works well.
"mobile_country_code": {
            "type": "string",
            "pattern": "^[0-9]{2,3}$",
          },


text:
Q: How to resolve - Added Library Loaded - Proposed Google way? I am getting this message from SCC but am unsure what to tell the dev team on how to resolve it. What is the way that Google has in mind for this?
And is there maybe a way to "whitelist" some libraries and binaries but monitor for others? Because in general, the message makes sense.
In SCC the message is the following:
Added library loaded
A library that was not part of the original container image was loaded. If an added library is loaded, this is a possible sign that an attacker has control of the workload and they are executing arbitrary code.


text:
Q: Are constexprs stored in .rodata section I read c++11 faq and find this sentence:

Typically we want the compile-time evaluation guarantee for global or namespace objects, often for objects we want to place in read-only storage.

I want to see how my compiler(gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1) ) does, so I write code below:
#include <iostream>
using namespace std;
constexpr int add5(int i){
        return i+5;
}
int main(int argc,char*argv[])
{
constexpr int read_only = add5(10);
cout << &read_only <<endl;
return 0;
}

I thought that read-only will appeared in .rodata section but it didn't show up. Apparently people may think that the compiler do optimization. In this view, I thought that almost every constant expression can be store in the table of compiler but not omitted into target code. If there exit some constant expression should exist in target code in read-only storage for better occasion.
~$: ./constexpr
0x7fff622addec
~$: cat /proc/3051/maps
7fff6228e000-7fff622af000 rw-p 00000000 00:00 0                          [stack]

UPDATE:
I don't understand well the sentence I quote specifically the bold part.
As the comment below,read_only is a local variable which will appear in stack as result above.
It's meaningless if we don't talk about the global data or in namespace:
#include <iostream>
using namespace std;
constexpr int add5(int i){
        return i+5;
}
constexpr int read_only = add5(10);
int global_int = add5(10);
int main(int argc,char*argv[])
{
cout << &read_only <<endl;
cout << &global_int <<endl;
getchar();
return 0;
}

~$: ./constexpr
0x4009b8
0x601068
~$: cat /proc/3157/maps
00400000-00401000 r-xp 00000000 08:09 1200603              /home/shia/constexpr
00600000-00601000 r--p 00000000 08:09 1200603              /home/shia/constexpr
00601000-00602000 rw-p 00001000 08:09 1200603              /home/shia/constexpr

It worked as I expected.And about the global variable declared with prefix const :

A variable or data member declared with constexpr behaves as if it was
  declared with const, except that it requires initialization before use
  and its initializer must be a constant-expression. Therefore a
  constexpr variable can always be used as part of a constant expression

So,it should also appear in .rodata section.

A: The way I read it, constexpr guarantees that it can be evaluated at compile-time, but it is not necessarily even evaluated at all.
It does not, however, guarantee that it will be evaluated at all if not needed (i.e. optimized away as in your case).
E.g. (from your link):

[...] they are basically values kept in the compiler's tables and only emitted into the generated code if needed

A: You've declared a local variable. If the function were recursive or the program were multithreaded, you could have two of them at the same time. Two different objects can't have the same address, because the definition of an object in C++ is a thing with a unique address.
As already noted, there is no guarantee that a constexpr variable initialization will not be evaluated at runtime. The compiler is allowed to use read-write memory and call add5 even for the global variable. In this case, though, that's irrelevant. It needs to place the local variable there to do a dance so it can have a proper address.
Moreover, you (the user) are not allowed to see the difference between a program which does initialization at runtime and one with compile-time-only evaluation, aside from performance. Any experiment to discern it is bound to default back to runtime evaluation behavior.
If you don't take its address, the requirement ceases to apply. It can then disappear from the stack, and from runtime operations entirely.


text:
Q: Notation for contracting vectors using metric tensors If we take a vector $A$, which has three components, my understanding is that we can write this using Einstein notation as $A_{u}$ where this is actually $A_1+A_2+A_3$. We can also write $g^{uv}A_v = A^u$.
If we take a concrete example where $A = \begin{pmatrix} 2 \\ 3 \\ 4 \end{pmatrix}$ and $g^{uv} = \begin{pmatrix} 1 & 0 & 0 \\ 0 & -1 & 0 \\ 0 & 0 & 1 \end{pmatrix}$, then if we expand $g^{uv}A_v$, we have $g^{u1}A_1 + g^{u2}A_2 + g^{u3}A_3$ which is equal to $\begin{pmatrix} 2 \\ -3 \\ 4 \end{pmatrix}$. My confusion is why these are both called $A$? They are two completely different vectors, so I am confused why when we contract $A_v$ with $g^{uv}$, we get another vector $A$? My understanding is that $A_u$ and $A_v$ are the same vector since they are both called $A$ and summed over $1-3$, so my intuition is that we should say $g^{uv}A_v = B^u$.

A:
If we take a vector $A$, which has three components, my understanding is that we can write this using Einstein notation as $A_{u}$ where this is actually $A_1+A_2+A_3$.

No.  $A_\mu$ is the $\mu^{th}$ component of the covector $A$.  Summation is only implied if an index is repeated, e.g. $A_\mu B^\mu=A_0B^0 + A_1B^1+\ldots$

We can also write $g^{\mu\nu}A_\nu = A^\mu$.

Yes. To each covector $A$ with components $A_\nu$ we can associate a vector "partner" $A^\sharp$ with components $(A^\sharp)^\mu := g^{\mu\nu} A_\nu$. It is conventional to drop the $\sharp$ and simply write $A^\mu$, where we distinguish between the components of $A$ and $A^\sharp$ by the placement of the index.  Similarly, to each vector $V$ with components $V^\mu$ we can associate a covector $V^\flat$ with components $(V^\flat)_\mu := g_{\mu\nu} V^\nu$.
This can be confusing, because $A$ and $A^\sharp$ are emphatically not the same thing (they aren't even the same type of thing - one is a covector and one is a vector). They are partners, whose partnership is in this case defined by the metric tensor (though any non-degenerate bilinear form would do).

Based on some previous questions you've asked, I believe the convention used by your source lumps vectors and covectors together, treating them as elements of a single vector space. In this convention, $A^\mu$ and $A_\mu$ are called the contravariant and covariant components of the vector $A$, corresponding to the expansion of $A$ in the basis $\{\hat e_\mu\}$ or the dual basis $\{\hat \epsilon^\mu\}$, which is defined such that $\hat\epsilon^\mu \cdot \hat e_\nu = \delta^\mu_\nu$.  In other words,
$$A = A^\mu \hat e_\mu = A_\nu \hat \epsilon^\nu$$
The components $A^\mu$ and $A_\mu$ are different because the bases $\{\hat e_\mu\}$ and $\{\hat \epsilon^\mu\}$ are generally different (though they coincide if $\{\hat e_\mu\}$ is an orthonormal basis).


text:
Q: How to avoid explicitly writing MySQL database password in your code I'm building some dynamic website that will query the MySQL database from Apache Tomcat interface. Although the database stores all the user information with encrypted password, it seems I still need to explicitly write the password (root or admin account) in the java code to authenticate the users. I feel this is not very safe. What's the correct way to do that?
Thank you!

A: Since you are working with an application server/servlet container like Tomcat, you can leverage the databsae connection details to the server and just fetch a connection from your application.
In Tomcat, you can configure JDBC connections in the context.xml file in which you set the connection's driver, URL, user and password. You also configure a reference name for this connection. Ej:
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/javatest"/>

Later, you add a reference to this server resource in your application's web.xml config file:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <description>MySQL Test App</description>
  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

Finally, you can now instantiate Connection objects refering to the resource's name as a JNDI context:
Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();

Code taken from this Apache Tomcat Howto.

A: You will have to have the password available somewhere in order to connect to the database and this is the case for almost any application. This is the reason you use other layers of security to prevent people from being able to use that password should they discover it somehow.
Usually a database server is secured to only allow connections from the local machine it resides on or perhaps a limited whitelist of other machines. If you are not using the same password for anything else then anyone who steals it won't have any more power to access your database than before as they would need to be on the server to use the password.
If someone has managed to get on your server and can edit files then the password is already irrelevant and with sufficient privileges they won't need it anyway.
As AmazingDreams says, you tend to read it from a config file which provides a single location that can be referenced when bootstrapping your application and setting up the database connection.

A: As other have said, it will have to be stored somewhere, and usually the best place for this is a configuration file. It is also possible to setup passwordless MySQL accounts (obviously this is not a good idea on a shared server, or if you allow remote access to mysql, or have tools like phpmyadmin publicly accessible).
You should also lock-down the privileges of the user account you are using for your website and use a different user for administration tasks. E.g. if your website only needs to read data from a few tables, grant only SELECT access to those tables. Generally a website user wont need access to DROP or EMPTY tables, or INSERT into event-log type tables.

A: When I have to share code I'am also concerned about this. In php i use a simple approach that is encode de password with any simple function (like base64), and in the code instead of the actual password, i write the encoded one and call the decoding function somewhere. The security is not high if somebody is actually trying to find out, but is good enough to avoid every casual observer to see your password. This is in php.
In Java you can do a further approach.

*

*Create custom encoding and decoding functions.

*The encoding function is not included in the project, you only use it once to encode your password.

*You can create a small library with just the custom decoding function, and include it compiled in your projects, so the decoding logic cannot be seen by anybody.

In your code your only write the encoded password, and make a call to the decoding function, something like this:
public static final String PASSWD = DecodingHelper.decode ("THE_ENCODED_STRING");


text:
Q: The events "get a heart" and "get a king" are dependent? Suppose a card is drawn from a standard deck of 52 cards. Is it true that the events "get a heart" and "get a king" are dependent?
My professor told me it is true. I am not sure because $P(\text{get a heart}) = 13/52 = 1/4$ and $P(\text{get a king}) = 4/52$. Hence,  $P(\text{Get a heart and get a king})= P(\text{get a heart})*P(\text{get a king}) =  1/4*4/52 = 1/52$. It is independent,right?

A: You're right. They're independent.
Another way to look at it: you have a $1/4$ chance of having a heart before or after knowing you got a a king. You also have the $1/13$ chance of having a king before and after you know you got a heart.
But as N.F Taussig mentioned, if you pull two cards, the events are dependent as no matter what card you get dealt first, it affects the chances of getting a specific second card.


text:
Q: drawing image on end point of arc in Canvas I was trying to put image icon on end tip of an arc in canvas.Both at beginning and end point of an arc. But not able to do that.
My js code:
var coord=getPoint(x, y, radius,  endAngle);
var img = new Image();
img.src = 'http://dailydropcap.com/images/D-6.jpg';
context.drawImage(img, coord.x, coord.y,'20px','20px');
context.stroke();

My js fiddle

A: You can get the XY at any angle on your arc like this:
function xyOnArc(cx,cy,radius,radianAngle){
    var x=cx+radius*Math.cos(radianAngle);
    var y=cy+radius*Math.sin(radianAngle);
    return({x:x,y:y});
}

Demo:  http://jsfiddle.net/m1erickson/C4Y3V/

Here's example code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var cx=100;
    var cy=100;
    var radius=40;
    var startAngle=Math.PI/2;
    var endAngle=Math.PI*2;

    ctx.beginPath();
    ctx.arc(cx,cy,radius,startAngle,endAngle);
    ctx.stroke();

    var start=xyOnArc(cx,cy,radius,startAngle);
    ctx.fillStyle="blue";
    ctx.fillRect(start.x,start.y,20,20);

    var end=xyOnArc(cx,cy,radius,endAngle);
    ctx.fillStyle="green";
    ctx.fillRect(end.x,end.y,20,20);

    function xyOnArc(cx,cy,radius,radianAngle){
        var x=cx+radius*Math.cos(radianAngle);
        var y=cy+radius*Math.sin(radianAngle);
        return({x:x,y:y});
    }

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

[ Addition: how to give image time to load ]
var img = new Image();
img.onload=function(){
    // img is now fully loaded
    // do your drawImage inside this onload function
    ctx.drawImage(img,x,y);
}
img.src = 'http://dailydropcap.com/images/D-6.jpg';


text:
Q: Looping to Collect Labels and Calculations Programming Goal:
1)    Loop and store individual stats:
a.    Scan for Serial Number, offset and collect the following for each:
   i.   PL#
ii.  Firmware version
iii. Capacity (whatever is in cell below)
iv.  Technology (whatever is in cell below)
v.   Battery #
For each individual PL, the following calculations...
vi.    Avg, Min, Max(* % State of Charge)
vii.   Avg, Min, Max(Temp)
viii.  Min, Max, Avg(I start  of charge (A))
ix.    Number of occurrences Equal. Time at "=0","(1,419)","(420,839)","=840"
x. Number of occurrences Low Level "yes" and "no"
xi.    Ratio of yes/(yes+no)
xii.   Sum(Disch.  Ah-)
xiii.  Sum(Ah+ Charge)
xiv.   Ratio of (Ah+ / Ah-)
2)  Output table to a new sheet:
a. Create table with headers respective i-xii
b. Each individual PL# with it's respective value for i-xii
c. Sum of Equal. Time in buckets for all data
3)  Output graphs to a new sheet:
a. All dates (y) and * % State of Charge (x) 2D line graph, y axis 0-100, with
a constant green line at 100 and a constant red line at 20
b. All dates and temps 2D line graph with a constant red line at 138
I am working on (1). This is how I will scan and collect each chunk...
Sub GetData()

Dim ArrPK() As String, SearchString As String
Dim SerialNo As Range, aCell As Range
Dim ws As Worksheet
Dim PkCounter As Long
Dim LstBox As msforms.ListBox

Set ws = ThisWorkbook.Sheets("Sheet1")
SearchString = "Serial#"
Set LstBox = UserForm1.ListBox1

PkCounter = 1

With ws
    Set SerialNo = .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)

    For Each aCell In SerialNo
        If aCell.Value2 = SearchString Then
            ReDim Preserve ArrPK(1 To 5, 1 To PkCounter)
            ArrPK(1, PkCounter) = aCell.Offset(0, 1) 'Serial#
            ArrPK(2, PkCounter) = aCell.Offset(1, 1) 'Firmware#
            ArrPK(3, PkCounter) = aCell.Offset(3, 1) 'Capacity
            ArrPK(4, PkCounter) = aCell.Offset(3, 3) 'Technology
            ArrPK(5, PkCounter) = aCell.Offset(3, 11) 'Battery#
       'Collected information labels, now run calculations...
            PkCounter = PkCounter + 1
        End If
    Next
End With

WHAT I WANT TO DO:. I'd like to output a table with the collected labels and corresponding calculations. The loop I have so far gets the labels.
Example file:
https://drive.google.com/open?id=1vDqnt2aHL06xB2Fg9k5MZ2WeCefqQZ1n1

A: this requires more coding, you can parametrize it a lot more, but also keeping it simple has benefits if you export excel file format will not change. I calculated the average temperature and inserted it in your array. Once you collected all of your data you need to transpose your array and paste it in a sheet:
Sub GetData()

    Dim ArrPK() As String, SearchString As String
    Dim SerialNo As Range, aCell As Range
    Dim ws As Worksheet
    Dim PkCounter As Long
    'Dim LstBox As msforms.ListBox
    Dim rng As Range

    Set ws = ThisWorkbook.Sheets("Sheet1")
    SearchString = "Serial#"
    'Set LstBox = UserForm1.ListBox1

    PkCounter = 1

    With ws
        Set SerialNo = .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)

        For Each aCell In SerialNo
            If aCell.Value2 = SearchString Then
                ReDim Preserve ArrPK(1 To 6, 1 To PkCounter)
                ArrPK(1, PkCounter) = aCell.Offset(0, 1) 'Serial#
                ArrPK(2, PkCounter) = aCell.Offset(1, 1) 'Firmware#
                ArrPK(3, PkCounter) = aCell.Offset(3, 1) 'Capacity
                ArrPK(4, PkCounter) = aCell.Offset(3, 3) 'Technology
                ArrPK(5, PkCounter) = aCell.Offset(3, 11) 'Battery#

                'define the data block for the battery
                Set rng = aCell.CurrentRegion 'data block for one battery
                Set rng = rng.Offset(6, 0)
                Set rng = rng.Resize(rng.Rows.Count - 6, rng.Columns.Count)

                'now range is defined, run the calculations using the worksheet functions, or use a loop over the range columns
                '### calculate avg, min and max temperature (8th column in block)
                ArrPK(6, PkCounter) = Application.WorksheetFunction.Average(rng.Columns(8)) 'average temperature

                PkCounter = PkCounter + 1
            End If
        Next
    End With
End Sub


text:
Q: How to Check List Contains with multiple values in Linq to sql In my application I have a problem with a query.
I am trying to run a query with multiple condition values.
IQueryable<DealsDetails> DD = (from D in DbContext.Deals
                                        where lst.Contains(D.DealCategory)
                                        select D);

I have this query and lst will contains these values like:
lst.Add("Other");
        lst.Add("Services");

And D.DealCategory contains value like this.
Other,Beauty,Services
Beauty,Services,
Services
Other,
Beauty
Other,Services

I need all those rows from table which contains Any item of that list. Means All rows which contains Other and Services.
Result is
Other,Beauty,Services
    Beauty,Services,
    Services
    Other
    Other,Services
Excluding beauty row.
Please suggest me how i write this query.
First Edit
I need all those rows which DealCategory Column contains any items from list.
Thanks

A: Do a join with your two lists, and return only elements from the first list :
IQueryable<DealsDetails> DD = from D in DbContext.Deals
                              join C in lst
                                on D.DealCategory equals C
                              select D;

Edit: As @Muhammad said, this won't work since the deals are in the Db and lst is in memory, but I'll let a modified answer there if you can filter the lst items directly on the server :
IQueryable<DealsDetails> DD = from D in DbContext.Deals
                              join C in DbContext.DealCategories
                                on D.DealCategory equals C
                              where [Clauses to filter Cs]
                              select D;


text:
Q: Visual Studio is missing reference to COM dll I have a project on C#. Furthemore I have a library that is developed on C++ and successfully built. I need to use that library in my C# project. So I registered C++ dll in COM and this is successfully registered and I can see it in registry in noe HKEY_CLASSES_ROOT/Wow6432Node/CLSID.
When I add reference to that COM dll in my project it is missing and I can't see anything from that library.
What the problem can be? Is it possible that if COM dll has any dependency and it require to reference it in my project?


text:
Q: MergeSort shows index out of bound I am creating a mergesort method in Java, but I can't seem to know what's wrong. I have tried .add and .set, but it doesn't seem to work. From what I can see in the debugger, the numbers are correct. Please help me!
mergesort(list, 0, list.size() - 1);

private void mergesort(ArrayList<Integer> list, int l, int h) {
    if (l < h) {
        int m = (l + h) / 2;
        mergesort(list, l, m);
        mergesort(list, m + 1, h);
        merge(list, l, m, h);
    }
}

Here is my merge method.
private void merge(ArrayList<Integer> list, int low, int middle, int high) {
    ArrayList<Integer> temp = new ArrayList<Integer>();

    int low_end = (middle - 1);
    int tmp_pos = low;
    int num_elements = (high - low + 1);

    while ((low <= low_end) && (middle <= high)) {
        if (list.get(low) <= list.get(middle)) {
            temp.add(tmp_pos++, list.get(low++));
        }
        else {
            temp.add(tmp_pos++, list.get(middle++));
        }
    }

    while (low <= low_end) {
        temp.add(tmp_pos++, list.get(low++));
    }

    while (middle <= high) {
        temp.add(tmp_pos++, list.get(middle++));
    }

    for (int i = 0; i < num_elements; i++) {
        list.set(high, temp.get(high));
        high--;
    }
}

Any help appreciated.


text:
Q: PHP SFTP/SSH transfer I posted a question a little while ago but I asked about FTP, which is the wrong question (doh!). I need to automatically transfer images (e.g. test.jpg) from one server to another using SFTP/SSH.
Could someone please explain how I would do this? I am completely new to this kind of thing so as much information as possible would be really appreciated.
Thanks for any help
<?php

$local_file = "http://localhost/ftptest/logo.png";
$remote_file = "/logo.png";

exec("scp $local_file username:pass@***.**.238.87:$remote_file");

?>

edit:
in the end I found that this works:
<?php

     include('Net/SFTP.php');

     $image = 'logo.jpg'; //image to be uploaded - needs to be in the same directory as this script e.g. just logo.jpg

     $image_contents = file_get_contents($image); // location of image to be uploaded

     $sftp = new Net_SFTP('***.**.**.**'); // server address to connect to
     if (!$sftp->login('***', '***')) { // server login details
         exit('Login Failed');
     }

     echo $sftp->pwd();
     $sftp->put($image, $image_contents); // upload a file $image with the image contents.

?>

Couldn't get the SSH working but hopefully this will help someone in the future :)

A: A simple way to handle this is to call PHP exec and execute a unix scp call.
exec("scp $local_file user1@somehost:$remote_file");

A: As is too often the case here, you've not provided much information about what you are trying to achieve nor the constraints.
Where does the image originate from? How quickly does it need to be replicated? Are the servers equivalent nodes in a cluster?
Since both servers are already talking HTTP, why use a different protocol for transferring content?
As Antonio suggests you could simply exec scp - but this is only going to work if you've got key pairs set up.
A more flexible solution (assuming ssh is a requirement) would be to use the ssh bindings in PHP

A: You can try ssh2_scp_send:
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);


text:
Q: Is there a function in tensorflow for doing transformations that a functions of the indices? I'm looking for (but have been completely unable to find) a function in tensorflow that will allow me to do a 'map' on a tensor.
map
Firstly, I'm not even sure if there is a 'map' function? By this a mean something that lets me apply a given f(x) to even entry in a tensor. e.g. I want something like this
def f(x):
  return x**2

Y = tf.Variable(np.array([[1.0, 2.0],
                          [3.0, 4.0]])

Y = tf.map_function(X, f)

producing (after suitably running in a session, obviously) a tensor with values
Y = [[1.0, 4.0],
     [9.0, 16.0]]

Does this exist (for general f - I realise that tf.nn.relu and tf.nn.sigmoid? On one hand, it seems like it should, sincemap` is a pretty fundamental operation. On the other hand, it would involve taking the supplied python function and somehow converting it to be executed on the GPU, and that sounds like something that might not be possible.
Am I asking for the moon on a stick here?
**mapi*
If such a function exists, is there a version that allows me to use an index-aware f? e.g.
def f(x, i):
  if (i != [0, 0]):
    k2 = np.sum([x**2 for x in i])
  else:
    k2 = 1.0 # To avoid division by zero
  return (x / k2)

Y = tf.Variable(np.ones(shape=(2,3)))

Y = tf.mapi_function(X, f)

producing
Y = [[1.0, 1.0, 0.25],
     [1.0, 0.5, 0.2]]

If such function don't exist, would it be possible (for fixed f) for me to add them by building tensorflow from (slightly modified) source?
Why I need such a function
The reason I'm asking this is that I'm trying to use tensorflow to numerically integrate a PDE. As part of that I need to compute the laplacian (d^2/dx^2 + d^2/dy^2 + d^2/dz^2) u(x,y,z). In a Fourier-transformed representation of the field u(k_X, k_y, k_z) this involves dividing by k_x^2 + k_y^2 + k_z^2.
I could precompute a tensor of inverse squared wavenumber values and dow an element-wise multiply. But this would use up a lot of memory. I suspect it would also be slower to load those values from memory.

A: In your specific example of wanting to map individually to each of the x,y,z coordinates, you can accomplish this readily with tf.split() and tf.stack().  That is, I presume you have an input tensor (call it K) that is of size [n,m,...,3]; that is, where the last dimension indexes the x,y,z coordinates.  If so, then use tf.split() to break up K into Kx,Ky,Kz.  Then apply your map operation (I use tf.map_fn() for this purpose typically), and then finally stack things back together with tf.stack().
If I understand the setup correctly that should do it.  If not, please provide a minimal working example that will make the problem concrete; otherwise we are at best guessing at a solution.


text:
Q: Can't read NFC tags properly every time I try to read a NFC tag I always got false from:
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action))

I've tried with differents tags and Mifare cards but I always got the same problem.
Any idea of what i'm doing wrong?
Thanks.
Edit: Add this to your manifest.xml and It will work perfectly. The app will open everytime you read a NFC tag and It will take your Tag's ID and Tech List.
<intent-filter> <action
android:name="android.nfc.action.NDEF_DISCOVERED" /> <category
android:name="android.intent.category.DEFAULT" /> <data
android:mimeType="text/plain" /> </intent-filter> <intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" /> <category
android:name="android.intent.category.DEFAULT" /> </intent-filter>

Full Code:
 public class MainActivity extends AppCompatActivity {

 private NfcAdapter nfcAdapter;
 TextView textViewInfo;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     textViewInfo = (TextView)findViewById(R.id.info);

     nfcAdapter = NfcAdapter.getDefaultAdapter(this);
     if(nfcAdapter == null){
         Toast.makeText(this,
                 "NFC NOT supported on this devices!",
                 Toast.LENGTH_LONG).show();
         finish();
     }else if(!nfcAdapter.isEnabled()){
         Toast.makeText(this,
                 "NFC NOT Enabled!",
                 Toast.LENGTH_LONG).show();
         finish();
     }
 }

 @Override
 protected void onResume() {
     super.onResume();

     Intent intent = getIntent();
    String action = intent.getAction();

     if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
         Toast.makeText(this,
                 "onResume() - ACTION_TAG_DISCOVERED",
                 Toast.LENGTH_SHORT).show();

         Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
         if(tag == null){
             textViewInfo.setText("tag == null");
         }else{
             String tagInfo = tag.toString() + "\n";

             tagInfo += "\nTag Id: \n";
             byte[] tagId = tag.getId();
             tagInfo += "length = " + tagId.length +"\n";
             for(int i=0; i<tagId.length; i++){
                 tagInfo += Integer.toHexString(tagId[i] & 0xFF) + " ";
             }
             tagInfo += "\n";

             String[] techList = tag.getTechList();
             tagInfo += "\nTech List\n";
             tagInfo += "length = " + techList.length +"\n";
             for(int i=0; i<techList.length; i++){
                 tagInfo += techList[i] + "\n ";
             }

             textViewInfo.setText(tagInfo);
         }
     }else{
         Toast.makeText(this,
                 "onResume() : " + action,
                 Toast.LENGTH_SHORT).show();
     }

 } }


text:
Q: Energies of bodies travelling on different geodesics If two bodies of equal mass are released at rest from point $A$ and travel on different geodesics in a curved spacetime to point $B$ will they have the same total energy at point $B$?
Is the same true of two lightbeams travelling on different null geodesics from point $A$ to point $B$?

A: It depends on the metric, and what you mean by "total energy."
If the metric is stationary, that is the metric components are independent of time  $\partial_t g_{\mu\nu} = 0$, then the answer is yes.  One way to see this is from the geodesic equation itself.  Normally the geodesic equation is written for the contravariant 4-velocity $u^\mu$ as:
$$
\frac{d}{d\lambda} u^\mu = - \Gamma^\mu_{\alpha \beta} u^\alpha u^\beta \ .
$$
You can also write this in terms of the covariant 4-velocity $u_\mu$ as:
$$
\frac{d}{d\lambda} u_\mu = \frac{1}{2}u^\alpha u^\beta \partial_\mu \ g_{\alpha \beta} \ .
$$
This is a useful form of the geodesic equation because it explicitly tells you about conserved quantities.  For example, if the metric is independent of $t = x^0$ then $\partial_t g_{\alpha \beta} = 0$ and the equation becomes:
$$
\frac{d}{d\lambda}u_0 = 0 \ .
$$
Or, $u_0$ is conserved along the geodesic! If geodesic is that of a massive particle, then $u_0$ is the energy per unit mass.  So, if you release two particles from $A$ with the same mass and $u_0$ in a stationary metric, then at point $B$ they will still have the same $u_0$ and hence the same energy.
It turns out, we can generalize this a bit.  What is important is not exactly that $\partial_t g_{\mu\nu} = 0$, but that the metric (ie. spacetime) has a time symmetry.  Symmetries of metrics are described by Killing Vectors, vector fields which point in the direction of the symmetry.  If $K^\mu$ is a Killing vector of your spacetime, then $K^\mu u_\mu$ will be a conserved quantity along geodesics.  Stationary spacetimes have a Killing vector $(1,0,0,0)$, so $K^\mu u_\mu = u_0$ is conserved.  In general, we say energy is conserved along geodesics if the spacetime has a time-like Killing vector.
Last point: we assumed here your particles were sufficiently light they themselves did not curve spacetime.  Of course that is just an approximation.  If they did curve spacetime, then the metric would be extremely time-dependent, not admit a time-like Killing vector, and energy (ie. $u_0$) would not be conserved along geodesics.  In particular, it would probably be lost to gravitational radiation.

A: If two bodies of equal mass are released at rest from point A and travel on different geodesics in a curved spacetime to point B will they have the same total energy at point B?
Yes. Because gravity is a conservative force. Moreover gravity isn't a force in the Newtonian sense. When two massive bodies fall towards one another, gravity converts potential energy in those bodies into kinetic energy. It doesn't add any energy, conservation of energy applies. So not only do your two minor bodies have the same total energy at point B, their total energy at point B is the same as their total energy at point A.
Is the same true of two lightbeams travelling on different null geodesics from point A  to point B?
Yes. Gravity doesn't add any energy to a lightbeam. We talk of blueshift, but a descending photon doesn't actually gain any energy. What happens is that when you descend some of your gravitational potential energy is converted into kinetic energy, which you typically radiate away. Then you're left with a mass deficit. Your mass is reduced, your total energy is reduced. So the photon appears to have gained energy when in truth, it hasn't. (It's similar for SR when you accelerate towards a light source and see a blue-shift. The photons haven't changed, you have). Alternatively you can look at this in terms of gravitational time dilation. You and your clocks go slower when you're lower, so the photon frequency looks higher, and since E=hf the energy looks higher too.
Some people might challenge this, but note that when you send a 511keV photon into a black hole, the black hole mass increases by 511ke/c², not by any other amount. Conservation of energy applies, the books always balance. What isn't conserved is mass. "Invariant" mass varies, see Wikipedia. That's why we have a mass deficit.

A: The answer is no.
Firstly you talk about points but you should talk about events. An event has a place and a time. It is actually not that easy to come up with events A and B where you can take different geodesics between them, but sometimes it can be done. And your question wouldn't make sense otherwise since if one took longer to get there things could change a lot during the meanwhile.
Secondly you talk about having the same energy. Since they followed different geodesics they started out with different momentum, but let's assume they started out with the same energy.
The answer is no. Firstly GR reduces to Newtonian mechanics in some limits so if we find a Newtonian mechanics problem in the regime where GR and Newtonian gravity agree very well and compute with Newtonian gravity that the energies are very very off then the GR case will have them be different.
So imagine your two very tiny particles take off one going in the y direction at 1mm per billion years and the other one takes off in the x direction at 1mm per billion years then wait until they are 100 trillion light years apart. Then send a sun sized star heading in the y direction with a Jupiter sized gas planet orbiting the sun sized star. We know that it is possible to increase your speed with a slingshot maneuver with a three body problem in Newtonian physics. So have the solar system be heading towards the x moving particle set up just right so that the x moving particle does a slingshot that heads it towards the y moving particle at very high speed and oriented so they intersect at the same time and place.
That's it. You can look at how that sun and planet system curved spacetime and that is an example curved spacetime that had them arrive with radically different energies.
However, there is a sense where you could turn your question into something meaningless and then within that meaninglessness pretend the answer was yes even though it was no. For instance in this set up the y moving particle basically just moved in a straight line for an incredible long time through a region were spacetime wasn't curved much at all (there was about one solar mass about 100 trillion light years away that never came anywhere close to it) and in the natural frame that originally had them moving slowly that's the frame where the x moving one came back with an insane speed.  But energy is totally frame dependant and no frame is better than another. So we could pick a silly frame instead.
So if our particles have the same mass then at event A when they are together we could choose a frame that right near there is the center of momentum frame so they originally had equal and opposite momentum so had equal energy. And then over near event B when they come together again we could again choose a frame that right near there is the center of momentum frame so they end up with equal and opposite momentum so end up with equal energy.  And in GR we can use any frame we want, so we can pick one that near A is that first frame and that near B is that second frame. So regardless of how they move we can measure the frame dependant energy in a way where they are equal.
But that's silly because we can do that no matter how they moved. We could do that if one of the particles found a rocket ship and used that to turn around and come back at high speed and was ejected out of the rocket by the emergency crash system of the rocket. Or if it met a giant cue stick that slammed into it.


text:
Q: StreamWriter throws IOException Logon failure: unknown user name or bad password I'm trying to have my web service write to a shared drive on our intranet. I'm getting an IOException on my StreamWriter
 string fullpath = path + "\\" + fileName;
 using (System.IO.StreamWriter file = new System.IO.StreamWriter(fullpath, append))
 {
     file.WriteLine(contents);
     file.Close();
 }

And  the exception I'm seeing,
IOException - Logon failure: unknown user name or bad password

If I'm understanding correctly, the user of the IIS web server needs to have access to write to the shared drive. I'm wondering if there's a way I can hard-code credentials for now, to write to the shared drive for debugging purposes. How can I provide credentials to a StreamWriter, or is there another mechanism I should be using?
I looked into Impersonation (using StreamWriter on server in C#) and would like to use that as a last resort if possible.

A: Whenever you write to a network drive programmatically, you use the username and password that you used to start the program with. Unless you are using a domain, this will generate an error because the network drive does not recognize your username and password.
So to fix this, all you need to do is run the same code you have as a different user. This is basically the impersonation stuff you wanted to avoid, but I found a useful Stack Overflow Thread that explains this and has links to wrapper classes you can use in your code to make things simpler.
As Simple as this (from thread):
using (Impersonation.LogonUser(domain, username, password, logonType))
{
        // do whatever you want as this user.
}

This should resolve your issue


text:
Q: jquery dialog in IE not showing I cannot get a modal dialog to render in IE. The screen goes dark (as in disabled) but the dialog itself is nowhere to be found. Behavior in Chrome is as expected; screen goes dark AND dialog appears. I have repeatedly cleared cache in IE and Chrome to confirm that this is not some sort of stale reference problem.
I also played games with .hide().show() and  $("#waiting1").dialog('open') but with the same results.

    <link rel="stylesheet" type="text/css" href="/css/themes/base/jquery.ui.all.css" >

A: Your reference to jquery.ui.all.css has no closing.
If it is running in Chrome and other browsers, it should also be running properly in IE(maybe little differences in the UI).

A: I'm guessing that you have an issue with your theme or CSS that overrides it. This fiddle approximates your scenario, and it works in IE8 and 10: http://jsfiddle.net/yrFWJ/2/
Click

  Nice!

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css" type="text/css" media="all" />

$('.click').click(function() {
  $("#waiting1").dialog();
});

A: I had similar problems and noticed that stylesheets included after jquery.ui.all seemed to be ignored. Explanation: IE limits the number of stylesheets and imports into the stylesheets (see http://support.microsoft.com/kb/262161).

A: Your example code does not seem to match your description. For example, I do not see you defining the dialog as a modal. Anyway, in the example that you gave you have set the display of your div to be hidden in the style attribute. You should not need to do that.  Let the jQuery UI handle the display formatting for you.
You have this:

Try changing it to this:


text:
Q: Numpy array dimension conversion I have a 2 dimension array which sub-array has different size, it is expected to operate as 2 dimension array but turns out 1, is there anything wrong?
import numpy as np
sample_list = [['Section 1','Section 2','Section 3'],['Section 4','Section 5'],['Section 6']]
nd_array = np.array(sample_list, dtype=object)
print(nd_array.ndim)

the output is 1
however, when it change to
import numpy as np
sample_list = [['Section 1','Section 2','Section 3'],['Section 4','Section 5','Section 6'],['Section 7','Section 7','Section 7']]
nd_array = np.array(sample_list, dtype=object)
print(nd_array.ndim)

the output is as expected is 2.

A: There's nothing wrong, except that your first array is not a 2-dimensional array.  It's a one-dimensional array with 3 entries, each of which happens to be a different-sized list.
Numpy 2D arrays are always square.  You'll have to pad the lists in your first example if you want to make it a 2D array.


text:
Q: notification button not working i m creating custoom notification in my app.the notification shows up,but when i click on button,the button doesnt work.i dont know what to do.i looked in all the answer on stackoverflow but didnt get the idea.so,please help me.
this is code for notification
private void customNotification() {

    Intent closeButton = new Intent("Download_Cancelled");
    closeButton.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(getContext(), 0, closeButton, 0);

    RemoteViews notificationView = new RemoteViews(getContext().getPackageName(), R.layout.notification);

    NotificationManager notificationManager = (NotificationManager)getContext().getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext())
            .setSmallIcon(R.drawable.music)
            .setContent(notificationView)
            .setChannelId(ID);
    notificationView.setOnClickPendingIntent(R.id.next, pendingSwitchIntent);

    notificationManager.notify(0, builder.build());

}

this is broadcast activity
public class NotificationBroadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context,"thanks",Toast.LENGTH_LONG).show();

    }
}

this is manifest
<receiver android:name=".BlankFragment2$NotificationBroadcast">
    <intent-filter>
        <action android:name="Download_Cancelled" />
    </intent-filter>
</receiver>


text:
Q: What are the best practices for appium framework using page opject model I am developing an automation framework for a mobile application using Appium (in java). I started with creating a class per view, in each class, I find and initialize elements of that class. Now after a while I understand my configuration for the framework is not correct and I'm not able to expand it. It would be great if anyone can introduce me an implemented framework on Github.
here is my config class, I use setdriver() to set a driver wherever I need.
public class Config {

public AndroidDriver<AndroidElement> driver;

public static AndroidDriver<AndroidElement> SetDriver() throws MalformedURLException {

    File appPath= new File("src");
    File app = new File(appPath,"My-debug.apk");

    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setCapability(MobileCapabilityType.DEVICE_NAME, "myDevice");
    cap.setCapability(MobileCapabilityType.APP,app.getAbsolutePath());
    cap.setCapability("autoGrantPermissions",true);
    cap.setCapability("appWaitActivity","com.xxxx.xxxx.ui.launch.LaunchActivity");
    AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"),cap);

    return driver;
}

Thank you in advance.

A: First you have to create base class which load the driver.
Note: If you are using thread local, we can achieve the parallel execution without any issues
package com.vg.ui.utils.mobile;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class Mobile {

    public static ThreadLocal<AppiumDriver> driverThread = new ThreadLocal<AppiumDriver>();

    public void setDriver(String deviceName, String platformVersion)
            throws MalformedURLException, InterruptedException {
        // TODO Auto-generated method stub

        File classpathRoot = new File(System.getProperty("user.dir"));
        File appDir = new File(classpathRoot, "Apps");
        File app = new File(appDir, "android-debug.apk");
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
        capabilities.setCapability("deviceName", deviceName);
        capabilities.setCapability("platformVersion", platformVersion);
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("app", app.getAbsolutePath());
        if (deviceName.equals("Nexus6")) {
            driverThread.set(new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities));
        } else if (deviceName.equals("Nexus7")) {
            driverThread.set(new AndroidDriver(new URL(
                    "http://127.0.0.1:4724/wd/hub"), capabilities));
        } else if (deviceName.equals("Lenovo")) {
            driverThread.set(new AndroidDriver(new URL(
                    "http://127.0.0.1:4723/wd/hub"), capabilities));
        } else {
            System.out.println("Check the device name and platformversion");
        }

    }

    public static AppiumDriver getDriver() {
        return driverThread.get();
    }

    public static void closeDriver() {
        if (!getDriver().equals(null)) {
             getDriver().quit();
        }
    }
}

Second: Create a object class for the particular page using PageFactory methodology.
package com.vg.ui.pageobjects;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class LandingPageObject {

    @FindBy(xpath = "//*[@text='Account Create']")
    WebElement btn_accountCreate;

    public void click_AccountCreate(){
        /*driverUtil.clickandWait(btn_accountCreate);*/
        btn_accountCreate.click();
    }

}

Third: Then in your step definition class extend the Mobile driver class like below with the PageFactory of respective screens.
package com.vg.ui.stepdefinitions;

import org.openqa.selenium.support.PageFactory;

import com.vg.ui.pageobjects.LandingPageObject;
import com.vg.ui.utils.mobile.Mobile;

import cucumber.api.java.en.When;

public class LandingPage extends Mobile{

    LandingPageObject lp        = PageFactory.initElements(getDriver(), LandingPageObject.class);

    @When("^click on the button account create\\.$")
    public void click_on_the_button_account_create() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        lp.click_AccountCreate();
    }

}

A: First define your page as follow:
public class WelcomeScreen{
    @AndroidFindBy(accessibility = "") //you can use id, accessibility-id or xpath
    @iOSFindBy(accessibility = "")
    private MobileElement element1;

    @AndroidFindBy(accessibility = "")
    @iOSFindBy(accessibility = "")
    private MobileElement element2;

    AppiumDriver<MoblieElement> driver;
    public WelcomeScreen(AppiumDriver<MobileElement> driver) {
        this.driver=driver;
        PageFactory.initElements(new AppiumFieldDecorator(driver), this);
    }

    public void clickElement2(){
        element2.click()
    }
}

Then setup the DesiredCapabilities and AppiumDriver.
After that use page object model in other class.
WelcomeScreen screen=new WelcomeScreen(driver);
screen.clickElement2();

Make sure your driver is global.


text:
Q: Find the last record for a particular ID in a mysql table I have a MYSQL table which looks like this :
+-----+-------------+----------------------------+
| id  | prev_status | date_modified              |
+-----+-------------+----------------------------+
| 236 | INIT        | 2015-11-13 08:00:53.128730 |
| 236 | REMS        | 2015-11-13 08:00:53.139382 |
| 236 | RET         | 2015-11-13 08:00:53.146587 |
| 236 | PA          | 2015-11-13 08:00:53.150409 |
| 236 | CORR        | 2015-11-13 08:00:53.157473 |
| 236 | PA          | 2015-11-13 08:00:53.165941 |
| 236 | SUB         | 2015-11-13 08:00:53.174236 |
| 236 | FILL        | 2015-11-13 08:00:53.181169 |
| 236 | SHIP        | 2015-11-13 08:00:53.183954 |
| 570 | INIT        | 2015-11-13 08:01:13.320310 |
| 570 | REMS        | 2015-11-13 08:01:13.333153 |
| 570 | RET         | 2015-11-13 08:01:13.340783 |
| 570 | PA          | 2015-11-13 08:01:13.351363 |
| 570 | SUB         | 2015-11-13 08:01:13.360626 |
| 570 | FILL        | 2015-11-13 08:01:13.368099 |
| 570 | SHIP        | 2015-11-13 08:01:13.371222 |
+-----+-------------+----------------------------+

As is evident,the data is already ordered by ID.I know limit 1 will give the last record in the table.However,what i need is the last record for each id.In this particular case, i need:
 +-----+-------------+----------------------------+
 | id  | prev_status | date_modified              |
 +-----+-------------+----------------------------+
 | 236 | SHIP        | 2015-11-13 08:00:53.183954 |
 | 570 | SHIP        | 2015-11-13 08:01:13.371222 |
 +-----+-------------+----------------------------+

How would i go about doing that ?

A: After the date_modified field is added, The query will be as below
select s.id, s.prev_status, s.date_modified from (select * from tab1 order by date_modified desc) as s group by s.id;

A: You can use your query with self join . In that you don't need to create temp. table.You can use following to get data..
**SELECT id,prev_status,MAX(date_modified) FROM  tabelName GROUP BY id;**

For more detail you can check here
Thanks


text:
Q: YouTubePlayerView stops on screen rotate I am using YouTubePlayerView to load the video.The video plays successfully, but when the screen is rotated, the it stops playing.How do I overcome this problem?It may be a simple thing.I googled but didn't get help but your help is needed...
Below is my code.
Code:
youTubePlayerView=findViewById(R.id.youtube_view);
        onInitializedListener=new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
                youTubePlayers=youTubePlayer;
                youTubePlayers.loadVideo("9ZaEPeaucIU");
                youTubePlayers.setFullscreenControlFlags(FULLSCREEN_FLAG_CONTROL_ORIENTATION);
                youTubePlayers.setOnFullscreenListener(onFullscreenListener);
            }
            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
                }
        };
        onFullscreenListener=new YouTubePlayer.OnFullscreenListener() {
            @Override
            public void onFullscreen(boolean b) {
                if (b){
                    time=youTubePlayers.getCurrentTimeMillis();

                }

            }
        };
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                youTubePlayerView.initialize("AI&*$^$^$3634HxbhVM@#$%%^%&%$",onInitializedListener);

                }
        });

Layout:
<com.google.android.youtube.player.YouTubePlayerView
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:id="@+id/youtube_view"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</com.google.android.youtube.player.YouTubePlayerView>

A: Add this on your activity declaration in AndroidManifext.xml so that, the activtiy doesn't recreate on orientation change.
<activity
        android:name=".NameOfYourActivitiy"
        android:configChanges="orientation|screenSize">

</activity>

A: Added the configChanges in the AndroidManifest file and it worked.
Eg
<activity android:label=Activity Name"
  android:configChanges="keyboardHidden|orientation|screenSize"
  android:name="com.example.blahblah">