text:
Q: How to take a break during a CSS animation to pause at the center point of the transition? I made a sort of header with an animated information banner (on 3 lines)
starting at each end. (ex: for the 1st and 3rd line, from left to right and for the 2nd line from right to left). What I would like is to take a break of a few seconds when the 3 bands are
all aligned (in the center) then continue the animation.
I would prefer a solution without using javascript but unfortunately I think it seems impossible?
Problem: The 1st and 3rd banner always start to appear before the 2nd and therefore when they are aligned, they are never in the center.

<!DOCTYPE html>

  <title> VIDEO LIBRARY </title>
      <meta charset="utf-8"/>

MANAGEMENT

OF MY

VIDEO LIBRARY

A: Instead of using from and to in your keyframes, you can set steps using percentages.
In the code below, from 0% to 45% of animation, the animation moves from 0 to 500px. Then from 45 - 55% it stays at 500px (i.e. pauses). Then from 55 - 100% it moves from 500 - 1000px:
@keyframes defilement {
    0% {left: 0;}
    45% {left: 500px;}
    55% {left: 500px;}
    100% {left: 1000px;}
}

Responsive solution: blocks will stop in the centre an any size screen.
If you do not have fixed width and would like a more responsive way to calculate the midpoint, you can use percentages: Start at 0%, end at 100%, then 50% for the centre.
However if you position the left of the block at the very centre, it will be a bit too far right. The correct position for the left of the block is actually 50% - 125px (half of the width of the div). And we can actually use using the CSS calc function to do this!
Also to make all blocks appear at the same time, we need to change the starting point for -250px so the 3 blocks all start off the screen and then slide in together.
@keyframes defilement {
    0%   { left: -250px;}
    45%  { left: calc(50% - 125px); }
    55%  { left: calc(50% - 125px); }
    100% { left: 100%;}
}

Working example:

.bandeau {
  height: 120px;
  width: 100%;
  padding-top: 5px;
  border-radius: 25px;
  background: rgb(26, 133, 230);
}

@keyframes defilement {
    0%   { left: -250px; }
    45%  { left: calc(50% - 125px); }
    55%  { left: calc(50% - 125px); }
    100% { left: 100%; }
}

.defil {
  margin: 10px;
  position: relative;
  height: 20px;
  background-color: black;
  border: 1px solid black;
  overflow: hidden;
  text-align: center;
}

.defil div {
  position: absolute;
  top: 0;

  width: 250px;
  height: 20px;
  background-color: blue;
  opacity: 1;
}

.ex1 div {
  animation: defilement 20s linear infinite;
}

.ex2 div {
  top: 0;
  right: 0;
  background-color: white;
  animation: defilement 20s linear infinite reverse;
}

.ex3 div {
  background-color: red;
  animation: defilement 20s linear infinite;
}

MANAGEMENT

OF MY

VIDEO LIBRARY

For more information on keyframes, take a look at Mozilla MDN Docs for CSS3 Keyframes


text:
Q: What is an alternative method to the WordPress private _doing_it_wrong() function I've noticed plugins using a singleton pattern that will use WordPress's _doing_it_wrong() function in their clone() methods, like so:
<?php
public function __clone() {
    _doing_it_wrong( __FUNCTION__, __( 'Cheatin’ huh?', 'divlibrary' ), $this->version );
}
?>

But I also noticed this warning/notice on WordPress's official documentation:

It really doesn't matter when, how a developer is using it, WordPress is advocating that it shouldn't be used, so I'm wondering what is the correct way to do this within custom plugins? The method is used for deprecating code but in this instance the developer is just wanting to send a warning/alert out.
Reference: https://developer.wordpress.org/reference/functions/_doing_it_wrong/

A:
What is an alternative method to the WordPress private _doing_it_wrong() function?

There's no way that WordPress is ever going to get rid of the _doing_it_wrong() function, so it's perfectly safe to use it. But if for some reason you don't want to use it because it's marked private, then you could create a plugin that has a function called doing_it_wrong() that is copy and pasted from _doing_it_wrong().
Another way would be to not copy code and instead use a class that handles deprecated code. Here's some sample code that basically does the same thing as _doing_it_wrong().
class deprecated {
  protected $method;
  protected $message;
  protected $version;

  public function method( $method ) {
    $this->method = $method;
    return $this;
  }

  public function message( $message ) {
    $this->message = $message;
    return $this;
  }

  public function version( $version ) {
    $this->version = sprintf(
      __( 'This message was added in version %1$s.' ),
      $version
    );
    return $this;
  }

  public function trigger_error() {
    do_action( 'doing_it_wrong_run', $this->method, $this->message, $this->version );
    if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
      trigger_error( sprintf(
        __( '%1$s was called incorrectly. %2$s %3$s' ),
        isset( $this->method ) ? $this->method : '',
        isset( $this->message ) ? $this->message : '',
        isset( $this->version ) ? $this->version : ''
      ) );
    }
  }
}

Usage
class wpse_238672 {
  public function some_deprecated_method() {
    ( new deprecated() )
      ->method( __METHOD__ )
      ->message( __(
        'Deprecated Method: Use non_deprecated_method() instead.', 'wpse-238672'
       ) )
      ->version( '2.3.4' )
      ->trigger_error();

    $this->non_deprecated_method();
  }

  public function non_deprecated_method() {
  }
}

A: As of WordPress 5.4 _doing_it_wrong() is no longer marked private, so it looks like we can just use it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to use tables in .asm file that are already declared and initialised in .h file i declared a table(array) in .h file.
Now i want to use that file in .asm but i am unable to include .h into .asm
Help me out

A: Assuming a C declaration something like:
char array[] = { 1, 2, 3, 4, 5 };

You can use it in your assembly file like this:
    .globl _array

lea  _array(%rip), %rbx
movb (%rbx), %al

The lea instruction puts the base address of array into rbx, and then the movb instruction grabs the first byte out.  You could use 1(%rbx) to get array[1], and so forth.
NB - my example is from a Mac OS X test app I just made.  If you're on a different system, you might have to do something different.


text:
Q: Django orm - how to get distinct items of field within query of distinct dates I have the following models:
class Event(models.Model):
    date = models.DateTimeField()
    event_type = models.ForeignKey('EventType')

class EventType(models.Model):
    name = models.CharField(unique=True)

I am trying to get a list of all dates, and what event types are available on that date.
Each item in the list would be a dictionary with two fields: date and event_types which would be a list of distinct event types available on that date.
Currently I have come up with a query to get me a list of all distinct dates, but this is only half of what I want to do:
query = Event.objects.all().select_related('event_type')
results = query.distinct('date').order_by('date').values_list('date', flat=True)

Now I can change this slightly to get me a list of all distinct date + event_type combinations:
query = Event.objects.all().select_related('event_type')
results = query.order_by('date').distinct('date', 'event_type').values_list('date', 'event_type__name')

But this will have an entry for each event type within a given date. I need to aggregate a list within each date.
Is there a way I can construct a queryset to do this? If not, how would I do this some other way to get to the same result?

A: You can perform such aggregate with the groupby function of itertools. It is a requirement that the elements appearch in "chunks" with respect to the "grouper criteria". But this is the case here, since you use order_by.
We can thus write it like:
from itertools import groupby
from operator import itemgetter

query = (Event.objects.all.select_related('event_type')
                         .order_by('date', 'event_type')
                         .distinct('date', 'event_type')
                         .values_list('date', 'event_type__name'))
result = [
    { 'date': k, 'datetypes': [v[1] for v in vs]}
    for k, vs in groupby(query, itemgetter(0))
]
You also better use 'event_type' in the order by criterion.
This will result in something like:
[{'date': datetime.date(2018, 5, 19), 'datetypes': ['Famous person died',
                                                    'Royal wedding']},
 {'date': datetime.date(2018, 5, 24), 'datetypes': ['Famous person died']},
 {'date': datetime.date(2011, 5, 25), 'datetypes': ['Important law enforced',
                                                    'Referendum']}]

(based on quick Wikipedia scan of the last days in May).
The groupby works in linear time with the number of rows returned.


text:
Q: Functions and Fractals - Recursive Trees - Bash! Logic Issue I am trying to build a fractal tree based on requirement to build it.
Something is wrong. Please assist. I am trying to build fractal tree based on the level requested. Here the levels are getting skipped. Need to understand how to fix the issue.
    #!/bin/bash
declare -A matrix
for ((i=1;i<=63;i++)) do
    for ((j=1;j<=100;j++)) do
        matrix[$i,$j]='_'
    done
done
function update_matrix {
p1=$1
p2=$(echo $2-1|bc)
p1=$(echo $p1-1|bc)
p3=$(echo 2^$p2|bc)
p4=$(echo 2*$p3|bc)
p5=$(echo $p3/2|bc)
p6=$3
for ((q1=$p3;q1<$p4;q1++)) do
        if [ "$(echo $q1-$p3|bc)" -lt "$p5" ]
            then
            q2=$(echo $p6-$(echo $p5-$(echo $q1-$p3|bc)|bc)|bc)
            q3=$(echo $p6+$(echo $p5-$(echo $q1-$p3|bc)|bc)|bc)
            matrix[$q1,$q2]=1
            matrix[$q1,$q3]=1
            #printf '%s' "$q1 $q2 -- $q1 $q3"
            #echo ""
            else
            matrix[$q1,$p6]=1
            #echo $q1 $p6
        fi
done

if [ $p1 -ge 1 ]
then
update_matrix $p1 $p2 $(echo $p6+$p5|bc)
update_matrix $p1 $p2 $(echo $p6-$p5|bc)
else
return
fi
}
read iteration
if [ $iteration -ge 1 ]
then
    update_matrix $iteration 6 32
fi
for ((i=1;i<=63;i++)) do
    for ((j=1;j<=100;j++)) do
        printf '%s' "${matrix[$i,$j]}"
    done
    echo ""
done

Output is:
[encoded data, 6300 characters]

Need to understand why left node created right one is not created.

A: What I was missing is to declare variables as local. Due to which global variables were getting updated and thus my program was not working properly.
I fixed the issue and used local variables and it worked like a charm.
Code for the solution is
Its for Hackerrank Functions and Fractals - Recursive Trees - Bash! Program.
Took me 3hr to nail it down. Really refreshing to finally solve it.
    #!/bin/bash
declare -A matrix
for ((i=1;i<=63;i++)) do
    for ((j=1;j<=100;j++)) do
        matrix[$i,$j]='_'
    done
done
i=0
declare -A arr
function update_matrix {
local p1 p2 p3 p4 p5 p6 q1 q2 q3 p11 p12 p13 p14 p15 p16
p1=$1
p2=$(echo $2-1|bc)
p1=$(echo $p1-1|bc)
p3=$(echo 2^$p2|bc)
p4=$(echo 2*$p3|bc)
p5=$(echo $p3/2|bc)
p6=$3
for ((q1=$p3;q1<$p4;q1++)) do
        if [ "$(echo $q1-$p3|bc)" -lt "$p5" ]
            then
            q2=$(echo 18+$p6-$(echo $p5-$(echo $q1-$p3|bc)|bc)|bc)
            q3=$(echo 18+$p6+$(echo $p5-$(echo $q1-$p3|bc)|bc)|bc)
            matrix[$q1,$q2]=1
            matrix[$q1,$q3]=1
            #printf '%s' "$q1 $q2 -- $q1 $q3"
            #echo ""
            else
            matrix[$q1,$(echo 18+$p6|bc)]=1
            #echo $q1 $p6
        fi
done

if [ $p1 -ge 1 ]
then
p11=$p1
p12=$p2
p13=$(echo $p6-$p5|bc)
p14=$(echo $p6+$p5|bc)
p15=$p1
p16=$p2

#echo $p11 $p12 $p6 $p5 $p13
update_matrix $p11 $p12 $p13
#echo $p15 $p16 $p6 $p5 $p14

update_matrix $p15 $p16 $p14
t=4
else
s=2
fi
}
read iteration
if [ $iteration -ge 1 ]
then
    #echo $iteration 6 32
    update_matrix $iteration 6 32
fi
for ((i=1;i<=63;i++)) do
    for ((j=1;j<=100;j++)) do
        printf '%s' "${matrix[$i,$j]}"
    done
    echo ""
done

A: The question asked by HackerRank requires you to make the code recursive. To be recursive the code must call itself at some point. Below I've made a create_y function that is recursive. This function will continually call itself until it meets its stop condition. The stop condition is the if statement that checks if the iteration variable is greater than 0.
The function itself naturally wants to build a Y, and at the end of the Y branches, make new Y's that are half the size of the original. When it is done it will print to standard out.
#!/bin/bash
declare -A SCREEN
SCREENR=63
SCREENW=100
DEPTH=0
MAX=16

function create_y {
    local originR=$1
    local originC=$2
    local iteration=$3
    local size=$4
    local originVR=0
    local originVC=0
    local originNYLR=0
    local originNYLC=0
    local originNYRR=0
    local originNYRC=0

    if [[ iteration -gt 0 ]]; then
        for ((i=0;i<$size;i++))
        do
            SCREEN[$(($originR-$i)),$originC]=1
            let originVR="$(($originR-$i))"
        done

        for ((i=1;i<=$size;i++))
        do
             SCREEN[$(($originVR-$i)),$(($originC - $i))]=1
             let originNYLR="$(($originVR-$i))"
             let originNYLC="$(($originC - $i))"
             SCREEN[$(($originVR-$i)),$(($originC + $i))]=1
             let originNYRR="$(($originVR-$i))"
             let originNYRC="$(($originC + $i))"
        done

        create_y $(($originNYLR-1)) $originNYLC $(($iteration-1)) $(echo "$size/2" | bc)
        create_y $(($originNYRR-1)) $originNYRC $(($iteration-1)) $(echo "$size/2" | bc)
    fi
}

for ((i=1;i<=$SCREENR;i++))
do
    for ((j=1;j<=$SCREENW;j++))
    do
        SCREEN[$i,$j]='_'
    done
done

read DEPTH

create_y $SCREENR $(echo "$SCREENW/2" | bc) $DEPTH $MAX

for ((i=1;i<=$SCREENR;i++)) do
    for ((j=1;j<=$SCREENW;j++)) do
         printf '%s' "${SCREEN[$i,$j]}"
    done
    echo ""
done

exit 0

A: Attempting to explain why this is optimal below. Idea of creating the grid and solving the problem is pretty straight-forward in terms of logic.
Algorithm:

*

*Create a grid.

*Create a solving function.

*Create a column (vertical line) of 1's, with length of l (interval, initially 16) starting from the middle.

*Mark left, right diagonals from the end of the line with 1's.

*You now have a Y!

*Recurse left and right from the top corners of Y, to create "sub-Y's".

*When recursing be sure your data are correct (interval should be divided by 2 etc.).

PS: Ladies and Gentlemen when sharing code, please give it a proper try when it comes on commenting, even for the smallest snippet. It will change your lives!
 #!/bin/bash

 declare -A grid

 #Solves the fractal problem.
 #Variables:
 #  d: depth of recursion.
 #  l: length of gaps/interval.
 #  r: row
 #  c: column.
 solve(){
  local d=$1
  local l=$2
  local r=$3
  local c=$4

  #base case, return.
  if [ $d -eq 0 ]; then
      return
  fi

# iterate backwards.
# create a column/vertical. line of 1's.
# sizeof(line) = l (length of interval) [initially 16].
# See graph below:
: '
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
'
for (( i = l; i > 0; i-- )); do
    grid[$((r-i)).$c]=1
done

((r -= l))

# iterate backwards.
# create the V-shaped tree/fractal.
# sizeof(tree) = l (length of interval) [initially 16].
# should fill all diagonal cells with 1's .
#       {[r-1, c-1] (left), [r-1, c+1] (right)} --> 1st.
#       {[r-2, c-2] (left), [r-2, c+2] (right)} --> 2nd.                                        for(i in [1,l]) {                       //remember l is dynamic. (16, 8, 4, 2, 1, ..)
#           ...                                                                         ---->       {[r-i, c-l] (left), [r-i, c+l] (right)} = 1
#           ...                                                                                }
#       {[r-l, c-l] (left), [r-l, c+l] (right)} --> 16th (or l-th).

for (( i = l; i > 0; i--)); do
    grid[$((r-i)).$((c-i))]=1
    grid[$((r-i)).$((c+i))]=1
done

: '
    This for n = 1 creates the following pattern:

    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ---------------------------------1-------------------------------1----------------------------------
    ----------------------------------1-----------------------------1-----------------------------------
    -----------------------------------1---------------------------1------------------------------------
    ------------------------------------1-------------------------1-------------------------------------
    -------------------------------------1-----------------------1--------------------------------------
    --------------------------------------1---------------------1---------------------------------------
    ---------------------------------------1-------------------1----------------------------------------
    ----------------------------------------1-----------------1-----------------------------------------
    -----------------------------------------1---------------1------------------------------------------
    ------------------------------------------1-------------1-------------------------------------------
    -------------------------------------------1-----------1--------------------------------------------
    --------------------------------------------1---------1---------------------------------------------
    ---------------------------------------------1-------1----------------------------------------------
    ----------------------------------------------1-----1-----------------------------------------------
    -----------------------------------------------1---1------------------------------------------------
    ------------------------------------------------1-1-------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------

'

#   Now comes the fun part, we should recurse.
#   For a complete analysis about why recursion is optimal u could read CLRS
#   or any other Algorithms book of ur choice (be extra carefull on big-O notation, Master Theorem and recursion trees).

# Idea:
#   - We will subrtact 1 from the depth for each complete fractal we create, so we will eventually terminate.
#   - Interval gets reduced by half for any fractal, thus l' = l/2.
#   - r-l: Executed 2 times (see line 48) will bring us to the left/right topmost part of the newly created Y (left/right corner), on the proper row [---------].
#   - c-l/c+l: Will result us beeing on either left or right corner of the Y [See below figure for more].

: '

    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ---------------------------------O-------------------------------O----------------------------------        After performing 2 recursive calls (left/right), the execution on the new copy
    ----------------------------------1-----------------------------1-----------------------------------        will start from points marked with "O".
    -----------------------------------1---------------------------1------------------------------------
    ------------------------------------1-------------------------1-------------------------------------
    -------------------------------------1-----------------------1--------------------------------------
    --------------------------------------1---------------------1---------------------------------------
    ---------------------------------------1-------------------1----------------------------------------
    ----------------------------------------1-----------------1-----------------------------------------
    -----------------------------------------1---------------1------------------------------------------
    ------------------------------------------1-------------1-------------------------------------------
    -------------------------------------------1-----------1--------------------------------------------
    --------------------------------------------1---------1---------------------------------------------
    ---------------------------------------------1-------1----------------------------------------------
    ----------------------------------------------1-----1-----------------------------------------------
    -----------------------------------------------1---1------------------------------------------------
    ------------------------------------------------1-1-------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------

'

# This will work recursivelly so only thing we need to do, is wait and pray that our exit case will work.
# This can also be seen as "Divide and Conquer" algorithm.

solve $((d-1)) $((l/2)) $((r-l)) $((c-l))
solve $((d-1)) $((l/2)) $((r-l)) $((c+l))

}

 # Just visualize the grid under given assumptions
 print_grid(){
    for ((i=0; i<63; i++)); do
        for ((j=0; j<100; j++)); do
              if [[ ${grid[$i.$j]} ]]; then
              printf 1
              else
                printf -
              fi
        done
        echo
    done
 }

 read n
 solve $n 16 63 49
 print_grid


text:
Q: Find string beetwen first occurence of word and before first occurence of special character I have following log string and I need to get from them only MedSoftware part, which means

*

*after .com\

*before first occurence of \

SERVERNAME2018-03-08 18:40:28 File: "x:_default\app.address.com\MedSoftware.data\BackEnd.Technical.Dictionaries.Service-180308182311\Web.config", Name: "dictionaries_data_product", CS: "###connectionStrings.dictionariesdataproduct.connectionString" info: Format of the initialization string does not conform to specification starting at index 0. 6069

Now my regex looks like this:
((?<=.com\\).*(?=\\))

and catches all after .com but goes to LAST occurence of \

A: You can use ((?<=.com\\)[^\\]*(?=\\))
I basically replaced .* by [^\\]* so that it stops at the first occurence of \.
Demo

A: \.com\\([^\\]+)\\.*

Imho you don't need something to capture the first com specifically, because that's what RE's normally do anyhow. And if you capture anything but backslashes, that doesn't need greedy-specifiers either. Only the backslashes which need masking, as well as the literal dot, are a bit tricky.
The capturing group \1 or $1 or whatever it is on powershell, contains MedSoftware now.
Demo


text:
Q: Add another role to a user when they click a button? On my site, there are roles "user, authors, etc.".
Default role for user is "User" which I want to keep it for all users.
How to add another role to a user when they click a button?
I tried with my code below but it doesn't work.
I have a page "Create a Post" that I want to restrict it to authors only.
So, when a normal logged-in user tries to access the "Create a Post" page,
they will be present with a form to apply as Author which they only need to click the button.
After they click "Apply" button, they will immediately get the Author role and immediately have access to the frontend post editor in the "Create a Post" page.
Here's my code:
/// APPLY AS AUTHOR BUTTTON
add_shortcode( 'apply_as_author', 'apply_as_author_button_shortcode' );

function apply_as_author_button_shortcode() {
if(is_user_logged_in()) {
$user = wp_get_current_user();
?>
<form method="POST">

Apply to be an author?

    <input checked="checked" type="hidden" class="input-checkbox" name="author_checkbox" id="author_checkbox" value="<?php echo esc_attr( $user->author_checkbox ); ?>" />

    Your application to be an author will be approved immediately right after you click the apply button.

    As an author, share your best stories and new ideas, and get discovered by many!

    <input type="submit" class="apply-author-button" name="submit" value="<?php esc_attr_e( 'Apply', 'wordpress' ); ?>" />
    <input type="hidden" name="action" value="submit" />

</form>
<?php
}}

// ADD AUTHOR ROLE
add_action('profile_update', 'role_option_update_user_meta');
function role_option_update_user_meta( $user_id ) {
if ( isset($_POST['author_checkbox']) ) {
    $user_id = wp_update_user( array( 'ID' => $user_id, 'role' => $_POST['role'] ) );
    if( $user_id > 0 ){
        $user = new WP_User($user_id);
        $user->add_role('author');
    }
}
}


text:
Q: Self-Hosting TFS PackageManagement (nuget server) I was interested in exploring the new PackageManagement service for TFS/Team Services -- though at a glance, it doesn't look like there's a self-hosted option for on-prem TFS server.
Can anyone confirm?
Thanks.

A: There's no on-prem/private Package Management option for VSTS (i.e. no hybrid approach where you use hosted VSTS and private Package Management)
Also for on-prem, it's available for TFS2017+ only...
Package Management is generally available: NuGet, npm, and more

"Today, I'm proud to announce that Package Management is generally
  available for Team Services and TFS 2017! If you haven't already,
  install it from the Visual Studio Marketplace...."


text:
Q: Laplacian of a submanifold in an Euclidean space let $M^n$ be a smooth an $n$-dimensional sub-manifold of a $\mathbb{R}^{m}$ ($n<m$). Denote by $\nabla^{M}$ and $\nabla^{\mathbb{R}^{m}}$ be the gradient of $M$ and $\mathbb{R}^{m}$ respectively. Similarly for $\Delta^{M}$ and $\Delta^{\mathbb{R}^{m}}$.
Please can you explain for me the relation between $\nabla^{M}$ and $\nabla^{\mathbb{R}^{m}}$ and that between $\Delta^{M}$ and $\Delta^{\mathbb{R}^{m}}$?
For example if I have  $f$ a smooth function defined on $\mathbb{R}^{m}$.
then    $$\nabla^{M}(f\mid_{M})=??(\nabla^{\mathbb{R}^{m}}f)^{T}$$
$(\,)^T$ represents the tangential part.
Is that true? What about Laplacian?

A: The gradient $\nabla^M f$ is the unique vector tangent to $M$ such that  $$\langle \nabla^M f, V \rangle = df(V) = V(f)$$ for all vector fields $V$ tangent to the manifold $M$ in question. Since $\langle (\nabla f)^T, V \rangle = \langle\nabla f,V\rangle$ when $V$ is tangent to $M$, we conclude that your formula for the submanifold gradient is correct.
For the Laplacian, there's no direct relationship, even in the flat case $\mathbb R^n \subset \mathbb R^m$: the issue is that $\Delta^M$ cannot capture second derivatives in the normal directions. However, we can get a useful formula in terms of the ambient derivatives. We have $$\Delta^M f = \mathrm{tr}_{TM} \nabla^M df$$ (where $\mathrm{tr}_{TM}$ means tracing over an orthonormal frame of the subspace $T_xM \subset \mathbb R^m$); and we know the extrinsic and intrinsic covariant derivatives are related by $\nabla^{\mathbb R^m}_X Y = \nabla^M_XY+A(X,Y)$ where $A$ is the second fundamental form. Thus the intrinsic second derivative is $$\nabla^M d f(X,Y) =X(Yf) - df(\nabla^M_X Y) = X(Yf)-df(\nabla^{\mathbb R^m}_XY) + df(A(X,Y)),$$ which we recognise as $\nabla^{\mathbb R^m}df(X,Y) + df(A(X,Y)),$ and so taking the trace we find $$\Delta^M f = \mathrm{tr}_{TM}\nabla^{\mathbb R^m}df+df(H),$$ where $H = \mathrm{tr} A$ is the mean curvature vector of $M$. If we evaluate at a point $x$, the first term can be written as $\Delta (f|_{T_x M}),$ where we are thinking of the tangent space $T_x M$ in the sense of analytic geometry, i.e. as a genuine subset of $\mathbb R^m$ touching $M$ at $x$.

A: I don't think that for Laplacian we might have a relationship like the gradients. Consider $\mathbb{R}^2$ and the unit circle $S^1$. Suppose $f(x,y) = x $. Then $ \nabla_{R^2}f= 0 $ however on the circle with induced metric $\nabla_{S^1}f = -\cos(\theta) \neq 0$.
In general we know that, Laplacian of $f$ on $M$ is the sum of second derivatives of $f\restriction _M$ along the geodesics. On $\mathbb{R}^m$ geodesics are just lines. On the other hand, on a Riemannian submanifold of $\mathbb{R}^m$ geodesics might be very different then lines. In that sense, I think we can always create a function which has zero Laplacian on $\mathbb{R}^m$ but non-zero Laplacian on $M$.


text:
Q: Siema carousel won't work I have added the file in my wp-includes I am trying to get this work on my WP page but it won't work. I have downloaded the stable release from here and added siema.min.js file in wp-includes/js/slider/siema.min.js and I first tried calling the file on the page by adding a script tab src and path. But it didn't work and than I added through Insert Header footer plugin. But it still doesn't work, rather is shows an image below the other.
HTML

const mySiema = new Siema();
const prev = document.querySelector('.prev');
const next = document.querySelector('.next');

prev.addEventListener('click', () => mySiema.prev());
next.addEventListener('click', () => mySiema.next());
body {
  width: 100%;
  max-width: 30rem;
  margin: 0 auto;
}

img {
  width: 100%;
}

.siema {
  margin: 1rem 0;
}

<button class="prev">Prev</button>
<button class="next">Next</button>

Webpage in quesiton.

A: You need to at least provide a selector to initialize Siema
const mySiema = new Siema({
  selector: '.siema',
});

Here you'll find other options available.
Note: when you visit your website, there is an error in the browser console saying this. Also, don't forget to put your scripts inside a $(document).ready(function(){});
Snippet:

$(document).ready(function() {
  const mySiema = new Siema({
    selector: '.siema'
  });
  const prev = document.querySelector('.prev');
  const next = document.querySelector('.next');

  prev.addEventListener('click', () => mySiema.prev());
  next.addEventListener('click', () => mySiema.next());
});
body {
  width: 100%;
  max-width: 30rem;
  margin: 0 auto;
}

img {
  width: 100%;
}

.siema {
  margin: 1rem 0;
}

<button class="prev">Prev</button>
<button class="next">Next</button>

Update from comments
Your page has a few errors and and a lot of warnings about non unique id
For now, it's hard to find the later errors, but the first one is causing your siema carousel not to work.
Your error says:

Uncaught SyntaxError: Unexpected token <

And your code is:

That error means you have html tags in your script and a < is not expected at that position. Remove those
 tags from the siema initialisation script. and it should work.


text:
Q: No provider for Http! - Angular 4 + Rails 5 API I have followed this tutorial, and am having trouble getting it going.
I am using Angular 4.2.4.
[Error] ERROR
Error: No provider for Http!
injectionError — core.es5.js:1169
...
  View_AppComponent_Host_0 (AppComponent_Host.ngfactory.js:4)
  ...

As I understand it, a few things have changed with Angular since this tutorial was written, including the replacement of this:
import { Http } from '@angular/http';

with this:
import { HttpModule } from '@angular/http';

I have tried this and added HttpModule to the imports array in `app.module.ts.
app.component.ts
import { Component } from '@angular/core';
import { HttpModule } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  books;

  constructor(private http: Http) {
    http.get('http://localhost:3000/books.json')
      .subscribe(res => this.books = res.json());
  }
}

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Any suggestions would be much appreciated.
Thanks!

A: You should import the Http provider from @angular/http inside your AppComponent, and add the HttpModule to the imports array of your AppModule:
AppComponent
import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  books;

  constructor(private http: Http) {
    http.get('http://localhost:3000/books.json')
      .subscribe(res => this.books = res.json());
  }
}

AppModule
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
Q: Low latency collection for edits Here is the situation  - I need to maintain a collection(unbounded/single writer) of ids(string) in Java 7.
As new records come in with a particular flag set (immaterial)- I attempt to insert.
If I find a pre-existing record in the collection - I alert and over-write anyways.
If new records come in with the flag unset - I attempt to remove the record,if one exists.
All lookups(2-step) to be avoided for performance.
Insert/update/remove to be as close to O(1) as possible.
Would HashSet be the most apt collection for this?

A: If your code is single-threaded, HashSet should be a good match. Sample implementation:
Set<String> ids = new HashSet<>();

void processRecord(Record record) {
    if (record.hasFlag()) {
        if (!ids.add(record.getId())) {
            alertDuplicate(record);
        }
    } else {
        ids.remove(record.getId());
    }
}


text:
Q: Don't understand how to use GridLayout.spec() This GridLayout is going in my app that has a lot of levels.  Each level has a different number of rows and columns.  I assume that this GridLayout would be my best bet to use to satisfy my needs.  Also, all need to be done at runtime prorammatically.
I am having trouble understanding how to use GridLayout.spec().  I am trying to follow this excellent example but just cannot grasp it fully.  Let's say, for example, I want a GridLayout with 3 columns and 4 rows.
GridLayout.LayoutParms params1 = new GridLayout.Layout(rowSpec, columnSpec);  //what's parameters?

gameplayGridLayout.setColumnCount(3);
gameplayGridLayout.setRowCount(4);

puzzle.addView(gameplayGridLayout, params1);

In my linked example above, he used code like below to set the "specs".
Spec row1 = GridLayout.spec(0, 2);
Spec row2 = GridLayout.spec(2);
Spec row3 = GridLayout.spec(3);
Spec row4 = GridLayout.spec(4, 2);

Spec col0 = GridLayout.spec(0);
Spec col1 = GridLayout.spec(1);
Spec colspan2 = GridLayout.spec(0, 2);

I don't understand the parameters of those variables either.  I've tried reading the documentation but it didn't give me any clarity.  Can someone help me with my example code of the 3x4 GridLayout which also helps explain what the Specs are?

A: I didn't exactly understand your question, but here are some examples that explain the syntax:
Spec row1 = GridLayout.spec(0, 2); //here you set row to be first row and it takes 2 cells in height.

Spec row2  = GridLayout.spec(2); //this row goes under row1 and it takes 1 cell(default size = 1)

and etc.
Spec col0 = GridLayout.spec(0); //same here - first column, width = 1 cell.

Spec colspan2 = GridLayout.spec(0, 2);

so you can do like this:
Spec row1 = GridLayout.spec(0);
Spec row2 = GridLayout.spec(1);
Spec row3 = GridLayout.spec(2);
Spec row4 = GridLayout.spec(3);

Spec col0 = GridLayout.spec(0);
Spec col1 = GridLayout.spec(1);
Spec col2 = GridLayout.spec(2);

GridLayout gridLayout = new GridLayout(this);
GridLayout.LayoutParams first = new GridLayout.LayoutParams(row1, col0);
/*Here you can set options for first cell which is in first row and first column.*/
first.width = screenWidth;
first.height = quarterScreenWidth * 2;
twoByTwo1.setLayoutParams(first);
twoByTwo1.setGravity(Gravity.CENTER);
twoByTwo1.setBackgroundColor(Color.RED);
twoByTwo1.setText("TOP");
twoByTwo1.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByTwo1, first)
//You can set all cells like above.

I hope this helps. :)


text:
Q: Silverlight Programmatical Drawing (converting from Windows Forms to Silverlight) I have a World ( a PictureBox and a Bitmap with is size ( rows * columns ) and create Graphics from  Bitmap in Windows Forms ) the following is the code,
    bmp = new Bitmap(columns*32, rows*32);
    graphics = Graphics.FromImage(bmp);
    pictureBox1.Size = new Size(columns * 32, rows * 32);
    pictureBox1.Image = bmp;

this i use to populate the Graphics in Windows form,
    private void drawImageInBox(Image src, int boxX, int boxY, int Offset = 0)
    {
        graphics.DrawImage(src, new Point((boxY * 32) + Offset, (boxX * 32) + Offset));
    }

and when all operations are done i just refresh the PictureBox,
    pictureBox1.Refresh();

how do i achieve this in Silverlight xaml?

A: You'll want something like this:
In your XAML:
<Grid x:Name="world_grid" Width="100" Height="100">
  <Grid.RowDefinitions>
    <RowDefinition Height="*" />   <!--Repeat this for however many rows you need -->
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" /> <!--Same here, for columns-->
  </Grid.ColumnDefinitions>
</Grid>

In your codebehind:
for each image you need to add:
  Image img = new Image();
  img.Source = new Uri("some/dir/img.png"); // coding in-place, can't remember syntax
  world_grid.Children.Add(img);
  Grid.SetRow(img, 0); // places this image in row 0
  Grid.SetColumn(img, 5); // places this image in column 5

A very important note: every time you "refresh" your "world", make sure you remove the appropriate images before re-adding them! Better yet, you can just keep track of these images in some array, and change their rows/columns. And if you need to, you can set the visibility on images to hidden/collapsed.


text:
Q: list only has one element I'm using hibernate to read data from a database. I have 3 entities, sensor, zone and a N to N relationship between those two entities, that is the entity SensorZone.
For each entity I created a class, which are the examples that follow, they don't include a constructor, getters and setters:
@Entity
@Table(name = "Sensor")
public class Sensor {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "zone")
    private List<SensorZone> zones = new ArrayList<>();
}

@Entity
@Table(name = "Zone")
public class Zone {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "max_count")
    private int maxCount;

    @Column(name = "current_count")
    private int currentCount;

    @Column(name = "created")
    private Timestamp created;

    @Column(name = "modified")
    private Timestamp modified;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sensor")
    private List<SensorZone> sensors = new ArrayList<>();
}

@Entity
@Table(name = "Sensor_Zone")
public class SensorZone {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "zone_id")
    private Zone zone;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "sensor_id")
    private Sensor sensor;

    @Column(name = "enter_exit")
    private boolean enterExit;
}

I'm using PostgreSQL as a database engine, and the tables are as follow:
CREATE TABLE Sensor (
    id SERIAL,
    name TEXT NOT NULL UNIQUE,

    CONSTRAINT PK_Sensor PRIMARY KEY (id)
);

CREATE TABLE Zone (
    id SERIAL,
    name TEXT NOT NULL UNIQUE,
    max_count INT NOT NULL,
    current_count INT NOT NULL,
    created TIMESTAMP NOT NULL,
    modified TIMESTAMP NOT NULL,

    CONSTRAINT PK_Zone PRIMARY KEY (id)
);

CREATE TABLE Sensor_Zone (
    id SERIAL,
    zone_id INT NOT NULL,
    sensor_id INT NOT NULL,
    enter_exit BOOLEAN NOT NULL,

    CONSTRAINT PK_Zone_Sensor PRIMARY KEY (id, sensor_id, zone_id),
    CONSTRAINT FK_Zone_Sensor_Zone FOREIGN KEY (zone_id) REFERENCES Zone (id),
    CONSTRAINT FK_Zone_Sensor_Sensor FOREIGN KEY (sensor_id) REFERENCES Sensor (id)
);

And here's the values on the table Sensor_Zone:

The problem is that the field zones from Sensor only has one element in the list, even there are multiple elements in the database.
I've tried to put FecthType.EAGER, but it didn't change anything.

A: Not the exact solution (a.k.a. Could your model be re-modeled?)
I know it's easier said than done, but if you could avoid managing extra column(s) on the joining table, you could resolve it using standard example of many-to-many with joining table.
Perhaps there is a way of thinking about your extra column so that it could become owned by either Zone or Sensor entities? Maybe it's complementary as in on one side of many-to-many if it is set to TRUE it means one thing, but when it's missing it is equivalent to being FALSE.
@Entity
@Table(name = "Sensor")
public class Sensor {
  // ...
  @OneToMany
  @JoinTable(
    name = "Sensor_Zone",
    joinColumns = { @JoinColumn(name = "sensor_id") },
    inverseJoinColumns = { @JoinColumn(name = "zone_id") }
  )
  private List<Zone> zones = new ArrayList<>();
}

@Entity
@Table(name = "Zone")
public class Zone {
  // ...
  @OneToMany
  @JoinTable(
    name = "Sensor_Zone",
    joinColumns = { @JoinColumn(name = "zone_id") },
    inverseJoinColumns = { @JoinColumn(name = "sensor_id") }
  )
  private List<Sensor> sensors = new ArrayList<>();
}

And then your joining table does not need to be an entity simplifying things.

The Solution (Here be dragons)
Escape hatch: for solution please check Mykong's blog

You have to look into using @AssociationOverrides on the entity created from joining table. Please also note a separate class annotated with @Embeddable created to deal with the composite key in the joining table.


text:
Q: Django - Fiter the latest objects based on DateTimeField I have a model class with two DateTimeField:
class Map(Models.Model):
    date_created = models.DateTimeField('date created', auto_now_add=True)
    date_updated = models.DateTimeField('date updated', auto_now=True)

I would like to have a query that returns the latest Map created and another query that returns the latest updated.

A: You can use latest():

latest(field_name=None)
Returns the latest object in the table, by date, using the field_name
  provided as the date field.

Map.objects.latest('date_created')
Map.objects.latest('date_updated')

A: Check the docs
Map.objects.order_by('date_created').first(10)


text: Q: iPhone compass woefully inaccurate Not sure when this started, but heading/compass on 2 iPhones (6 and X) is way off for some reason. Magnetic north  is off by 10-40°, depending on how much moving around I do. True north mostly works, but is also off. There is a difference between the two devices of 5-30°  No electromagnetic interference that I can trace nearby.    What could possibly cause this? The GPS signal on the X is also quite bad and takes very long to lock. I did the sim eject-reboot routine, to no effect


text:
Q: Soil Total Nitrogen Index - GEE I am new to GIS and I need some clarification.
There are vegetable indices available in Google Earth Engine like NDVI, EVI, SAVI etc. I need to know, is there any index available to map Soil Total Nitrogen Content? Or is there any way to calculate such index?


text:
Q: CSS Button color only change word's background color no whole button when hover I want make the button when hover change the background color but my css button  only change the word's background color, not the whole button color when hover. Is something wrong in my css?
snippet added

.popup1_btn {
    width: 210px;
    height: 45px;
    font-size: 20px;
    text-transform: uppercase;
    background-color: #d3db2c;
    color: black;
    cursor: pointer;
    margin: 30px auto 0;
    line-height: 45px;
    font-family:"Avant Garde Demi BT";}

    .popup1_btn :hover{
         background-color: black;
         color: #d3db2c;}

I'm Interested

image link: https://i.stack.imgur.com/z5XoU.png

A: Seems the space before the :hover in your CSS caused this problem.
After changing popup1_btn :hover to popup1_btn:hover, it works.
Here's a working snippet im which the entire button paints black on hover:

.popup1_btn {
    width: 210px;
    height: 45px;
    font-size: 20px;
    text-transform: uppercase;
    background-color: #d3db2c;
    color: black;
    cursor: pointer;
    margin: 30px auto 0;
    line-height: 45px;
    font-family:"Avant Garde Demi BT";}

.popup1_btn:hover{
    background-color: black;
    color: #d3db2c;
 }

I'm Interested


text:
Q: Flutter Navigator - push to Another page I have a problem when i use Navigator.of(context).push, at ElevatedButton it doesn't work.
I have two pages Home_Screen And The another one is Body from another file
body: Container(

     padding: EdgeInsets.symmetric(vertical: 10,horizontal: 5),
        child: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
              Text('PROMOTION',style: TextStyle(color:Colors.orange, fontSize: 20 ),),
              FloatingActionButton(
                onPressed: (){
                  Navigator.of(context).push( MaterialPageRoute(builder: (context) => Body(),
                ),);
                },
                child: Text('Starter',style: TextStyle(color: Colors.grey),),),

A: Change your following code:
Navigator.of(context).push( MaterialPageRoute(builder: (context) => Body()),);

to
Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => const Body()),
  );

You need to pass a context and route to push method.
For more information about navigator, please go through the following link:
https://docs.flutter.dev/cookbook/navigation/navigation-basics

A: @vaidarbhi: the form is correct in both cases...
@yassir outisket: Body should be a PAGE with scaffold or wont work.
Try next code for make a test with your function:
Navigator.of(context).push( MaterialPageRoute(builder: (context) => TestPage(), ),);

And test page
import 'package:flutter/material.dart';

class TestPage extends StatefulWidget {

  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Test'),
        ),
        body: Text("This is a test")
    );
  }
}


text:
Q: How to access jQuery serialized data? How can I access the data that has been 'serialized' using the jQuery function?
var test = $("form").serialize();

I have this data...
url=hello+1&title=hello+1&content=abc

How can I get the value of 'url'? - I tried this...
console.log(test.url);

But I get undefined - I want to get the result as "hello+1"

A: serialize() function returns a string so you can't use it like an object.
To deserialize a string you can use the jQuery BBQ $.deparam() function:
You can find example and documentation here
Source code here

A: The serialize method only creates a URL encoded string from a form, but this is a string, i.e you can not get the value of url or any other value. To do so you need to parse back the string into an object. You can check library out: https://github.com/kflorence/jquery-deserialize
However it would be best if you simply select the field containing that value and get it from there, i.e.
jQuery('input[name="url"]').val();

or if you have an id or class on that field, you can use it as a selector.
P.S. The value of url is "hello 1" the + is just how spaces are encoded in query strings.

A: The serialize() method is designed to create a URL encoded string, usually used for AJAX requests to the server. This means you can't access the string like an object or array in the traditional sense, instead you have two options for achieving the result you want...
(This question might be old but the original answers don't really answer the initial question and nor do they give much explanation...)
Method 1 : Serialize Array
The first method and my preferred one, is to use the serializeArray() method, this can be a useful method if you have several values and want to get the value of each, rather than having to explicitly select each element to get there value.
A solution, like below, using this method will serialize the selected form or element into an array of objects which can then be put into a single object and accessed easily using a function to get the values when and where you need them in your script...
//Serialize the Form
var values = {};
$.each($("form").serializeArray(), function (i, field) {
    values[field.name] = field.value;
});

//Value Retrieval Function
var getValue = function (valueName) {
    return values[valueName];
};

//Retrieve the Values
var url = getValue("url");

Here's a JSFiddle Code Snippet...

$(document).ready(function () {
    var values = {};

    $.each($("form").serializeArray(), function (i, field) {
        values[field.name] = field.value;
    });

    var getValue = function (valueName) {
        return values[valueName];
    };

    var first = getValue("FirstName");
    var last = getValue("LastName");

    $("#results").append(first + " & ");
    $("#results").append(last);
});

<form action="">
    First name:
    <input type="text" name="FirstName" value="Foo" />

Last name:
    <input type="text" name="LastName" value="Bar" />

</form>

Method 2 : Element Value
The second method, as already mentioned is to simply get the value directly from the form element that you are trying to collect, rather than serialising the value. This can simply be achieve using the jQuery val() method - this will get the entered value of the selector.
While this method is simple for selecting a single element, it can quickly become messy when trying to select and retrieve the value of several elements from a form...
$("input").val();

A: So I found a solution to this. Even though you can get the value of Input directly through Jquery with the selector or through pure javascript. But what if we are sending all this data at once and we have no way to set it? So, as it was answered, The serialize method only creates a URL encoded string from a form, from this we can work with URL, we can create a false URL then.
My solution:
var $form = $('#example_form');
var data = $form.serialize();

console.log(data);

var fakeURL = "http://www.example.com/t.html?" +  data;
var createURL = new URL(fakeURL);

From this you can get values from the URL you created:
createURL.searchParams.get('my_parameter_url')

Also, you can take, set, and among other things. Here is the link to the documentation:
https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
There is even a new way to work with URL in javascript, if you want, do a search and you will find.


text:
Q: Showing Large String in TextView in android I need to show a Large text view in android,if the string length is small i want to show the whole text if the String length is high I want to show the texts in first the letters of the String followed by dots and then followed by the last part of the String.
Like if the String is 'Google' i want to show "Google" If the String is 'Google Play Developer Console' I want to show the String something like "Google P...Console" how can I achieve this?

A: Use ellipsize to abbreviate the text:
<TextView android:layout_width="50dp"
          android:layout_height="match_parent"
          android:singleLine="true"
          android:ellipsize="middle"/>

A: This will solve your problem
android:ellipsize="middle"

A: if(string.length() <= 5)
            {
                tvAdd.setText(yourstring);
            }

            else
            {
                tvAdd.setText(yourstring.substring(0, 5) + "..");
            }


text:
Q: F# OleDb Syntax Error in INSERT INTO Statement Pulling Data from Access to Linked SQL Server I'm running an F# application to pull data from an Access table to a linked SQL Server table. Here is the resulting query:
INSERT INTO dbo_TempTerm (UnitID, PolicyTermYear, InsuredName, PolicyNumber, RenewalDate, CovATotal, CovBTotal, CovLTotal, DwellExtn, AllOtherPerilDeductible, MedPay, TotalPremium, HurricaneDeductible, Zone, Subzone, PercentCRC, PercentCRD, YearBuilt, RenYrs, PercentCFD, PercentHA, PercentMLD, GRP1, PercentNH, QCLM, RateV, CRI, AgentCode, AgentName, AFOCode, PolicyType, PolicyForm, OC, DateCreated)
SELECT [UNIT ID], [POLICY TERM YEAR], [INSURED NAME], [POLICY #], [RENEWAL DT], [COV A TOTAL], [COV B TOTAL], [COV L TOTAL], [DWELL EXTN], [ALL/OTHER PERIL DEDUCTIBLE], [MED PAY], [TOT PREMIUM], [HURR DED], ZONE, SUBZONE, [%CRC], [%CRD], [YR BLT], RENYRS, [%CFD], [%HA], [%MLD], GRP1, [%NH], QCLM, [RATE V], CRI, [AGENT CODE], [AGENT NAME], [AFO CODE], [POLICY TYPE], [POLICY FORM], OC, DateCreated
FROM tblPrior

The query parses and runs fine in Access. But from within my application, it raises an error: Syntax error in INSERT INTO statement.
Here is my F#, though I don't think it's relevant.
module Data

open System.Data
open System.Data.OleDb

type Period = Prior | Current

let Upload (p:Period) db =
    use conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + db + ";Persist Security Info=False;")

    let execNonQuery s =
        let comm = new OleDbCommand(s, conn) in
        comm.ExecuteNonQuery() |> ignore

    let (table,proc) = match p with
                       | Prior   -> ("tblPrior"  ,"InitPriorTable")
                       | Current -> ("tblCurrent","InitCurrentTable")

    do conn.Open()

    let u = sprintf "INSERT INTO dbo_TempTerm (UnitID, PolicyTermYear, InsuredName, PolicyNumber, RenewalDate, CovATotal, CovBTotal, CovLTotal, DwellExtn, AllOtherPerilDeductible, MedPay, TotalPremium, HurricaneDeductible, Zone, Subzone, PercentCRC, PercentCRD, YearBuilt, RenYrs, PercentCFD, PercentHA, PercentMLD, GRP1, PercentNH, QCLM, RateV, CRI, AgentCode, AgentName, AFOCode, PolicyType, PolicyForm, OC, DateCreated) SELECT [UNIT ID], [POLICY TERM YEAR], [INSURED NAME], [POLICY #], [RENEWAL DT], [COV A TOTAL], [COV B TOTAL], [COV L TOTAL], [DWELL EXTN], [ALL/OTHER PERIL DEDUCTIBLE], [MED PAY], [TOT PREMIUM], [HURR DED], ZONE, SUBZONE, [%%CRC], [%%CRD], [YR BLT], RENYRS, [%%CFD], [%%HA], [%%MLD], GRP1, [%%NH], QCLM, [RATE V], CRI, [AGENT CODE], [AGENT NAME], [AFO CODE], [POLICY TYPE], [POLICY FORM], OC, DateCreated FROM %s" table
    // DEBUG.
    printfn "%s" u
    // DEBUG.
    execNonQuery u
    execNonQuery proc

A: Zone and DateCreated are both reserved words.  It's difficult to predict when reserved words will cause trouble for SQL statements, but it seems to me that OleDb may be less forgiving, ie more likely to fail with reserved words.  See if bracketing all occurrences of those names will allow the INSERT to succeed.
let u = sprintf "INSERT INTO dbo_TempTerm (UnitID, PolicyTermYear, InsuredName, PolicyNumber, RenewalDate, CovATotal, CovBTotal, CovLTotal, DwellExtn, AllOtherPerilDeductible, MedPay, TotalPremium, HurricaneDeductible, [Zone], Subzone, PercentCRC, PercentCRD, YearBuilt, RenYrs, PercentCFD, PercentHA, PercentMLD, GRP1, PercentNH, QCLM, RateV, CRI, AgentCode, AgentName, AFOCode, PolicyType, PolicyForm, OC, [DateCreated]) SELECT [UNIT ID], [POLICY TERM YEAR], [INSURED NAME], [POLICY #], [RENEWAL DT], [COV A TOTAL], [COV B TOTAL], [COV L TOTAL], [DWELL EXTN], [ALL/OTHER PERIL DEDUCTIBLE], [MED PAY], [TOT PREMIUM], [HURR DED], [ZONE], SUBZONE, [%%CRC], [%%CRD], [YR BLT], RENYRS, [%%CFD], [%%HA], [%%MLD], GRP1, [%%NH], QCLM, [RATE V], CRI, [AGENT CODE], [AGENT NAME], [AFO CODE], [POLICY TYPE], [POLICY FORM], OC, [DateCreated] FROM %s" table


text:
Q: Mysql - Can I use the 'having' clause after 'order by' clause? For an application I make, I need to get the last week (monday to friday) and the details for every day for each user I have in the database.
For now, my query gets every day of the month starting to today (So if we're the 18th, it'll get 18-17-16... and so on) and the month before (in case we're the first...)
But I want to limit the select to the first 8 days. I read this:
http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
The last example is what I'm trying to do. But the problem is that I need to do an order by before. I need to order by months (DESC), than by days (DESC) and than I need to do the having to get what I want. I tried it without ordering, it works well, but it gets the wrong days. Because by default it's ordered ASC.
Just for the example, here's a query that represent my problem, here's what I have:
SELECT
    day, id
FROM
    myTable
WHERE
    (month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 1 OR
         month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 2) AND
    year = EXTRACT(YEAR FROM CURRENT_TIMESTAMP) AND
    day <= EXTRACT(DAY FROM CURRENT_TIMESTAMP)
ORDER BY
    month DESC,
    day DESC;

Here's what I want:
set @day := 0, @id:= '';

SELECT
    day, id, @day := if(@id= id, @day + 1, 1) as day_number,
    @id := id as dummy
FROM
    myTable
WHERE
    (month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 1 OR
         month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 2) AND
    year = EXTRACT(YEAR FROM CURRENT_TIMESTAMP) AND
    day <= EXTRACT(DAY FROM CURRENT_TIMESTAMP)
ORDER BY
    month DESC,
    day DESC
HAVING
    day_number <= 8;

But I can't put a HAVING after an ORDER BY. If I remove the ORDER BY clause, I'll get all days for every id between 1st and 8th. But I need between 18th and 10th. (18th being the current date)
With the code I have in the app, it will stop after a week, so it doesn't matter if the select returns sunday to saturday, I just want to have at least monday to friday. Which is why I took the number '8', because the app will execute this only mondays.
Thanks for any help/suggestion!

A: You can wrap your query in a subquery and perform filtering in the outer query:
SET @day := 0, @id:= '';

SELECT day, id, day_number
FROM (
  SELECT
      day, id,
      @day := IF(@id = id, @day + 1,
                  IF(@id := id, 1, 1)) as day_number
  FROM
      myTable
  WHERE
      month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 1 OR
      month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 2) AND
      year = EXTRACT(YEAR FROM CURRENT_TIMESTAMP) AND
      day <= EXTRACT(DAY FROM CURRENT_TIMESTAMP)
  ORDER BY
    month DESC,
    day DESC ) as t
WHERE  day_number <= 8;

The outer query uses a WHERE clause to perform filtering. HAVING is used in conjunction with GROUP BY and operator on group level.
Note: The above query uses nested conditionals in order to properly read/write @id variable.


text:
Q: doxygen file customTag I want to include a custom doxygen tag refering a license.md file in my workspace root folder. I am using Visual Studio Code Editor and the doxygen extension.
I know that I can write in the options something like:
"doxdocgen.file.customTag": [
        "@license License /* {licensePath} */"
    ]

I want just to link the licensePath to my file, or more generally, how can I refer any file into those templates?
Any suggestion? Thanks in advice


text:
Q: Could not determine IPv4/IPv6 protocol I am having this problem all of a sudden.  Open VPN worked brilliantly until December 2021- then it stopped connecting with the following reason:
RESOLVE: Cannot resolve host address: xxxx.xxxx.com:xxxx (No such host is known. )
Could not determine IPv4/IPv6 protocol.
I have hidden the host address and port designations- but hopefully you get the idea.  Any help would be greatly appreciated as this service is no longer reliable.

A: This message is printed when no IPv4/v6 preference is given in the config (i.e. proto udp/tcp is used) and OpenVPN is running as a server. Just change in server.conf on what you need udp4/upd6:
;proto udp
proto udp4

Updated: For tcp protocol (not udp) just change in server.conf on what you need tcp4/tcp6:

;proto tcp
proto tcp4

Original Source


text:
Q: Using a texture atlas in Xcode WITHOUT cocos2d Following on from this question:
How should I go about animating over 200 images in iOS?
i'd like to know how to use a texture atlas in Xcode, but not with cocos2d. Too much of the project is already completed for me to port it over to cocos2d now. This will also be the only animation with this number of images.
The only tutorials out there seem to involve cocos2d or corona. I've downloaded Zwoptex and have packed all my sprites but, even then, i'm not sure if i should be trimming them, allowing rotation, giving them padding or even how i handle my retina images.
I've been looking at this link: http://mysterycoconut.com/blog/2011/01/cag1/ as recommended to me from my last question but it seems to gloss over many parts that i'm struggling with.
I'd really appreciate any help with this.

A: The texture atlas is designed to run with Cocos2D, there is a lot of dependencies with the other components. So I don't think that's a good choice for you.
The tutorial you posted is good otherwise. It could be most easy to use, but it gives a very good entry point. The main parts of this code are the - display and the - (void)displayLayer: methods:
The display method is call when the layer needs to its content. The animation will call (indirectly) the display method and here we call the displayLayer which will change the image to display (I hope I've been clear :!).
Here how you can refactor the display method if you want use a zwooptex file (or other) with non fixed size:
// Implement displayLayer: on the delegate to override how sample rectangles are calculated; remember to use currentSampleIndex, ignore sampleIndex == 0, and set the layer's bounds
- (void)display;
{
   static const CGRect sampleRects[11] = {
      { 0, 0, 38, 47 },       // run
      { 0, 47, 46, 47 },
      { 82, 0, 40, 47 },
      { 122, 0, 30, 47 },
      { 152, 0, 36, 47 },
      { 38, 0, 44, 47 },
      { 188, 0, 42, 47 },
      { 230, 0, 26, 47 },
      { 46, 47, 28, 47 },
      { 74, 47, 28, 47 },
      { 102, 47, 28, 47 },
   };

   unsigned int idx = [self currentSampleIndex];
   if (idx == 0)
      return;

   self.bounds = CGRectMake(0, 0, sampleRects[idx-1].size.width, sampleRects[idx-1].size.height);
   self.contentsRect = CGRectMake(sampleRects[idx-1].origin.x/256.0f, sampleRects[idx-1].origin.y/128.0f, sampleRects[idx-1].size.width/256.0f, sampleRects[idx-1].size.height/128.0f);
}

@end

If you have any question, don't hesitate. ;)


text:
Q: Cannot get existing images/resources from server and how to get them Sometimes ,may be when connection slow, browser cannot get image that already exist in server. I try to copy image src url that browser fail to get and open in new tab image can load properly just as you see in the picture. Chrome can load image and display it in console.I wonder why this happen and how to solve this.

I try to reload images by add some parameter to prevent cache with this code
images[instance].onerror = function(){
        repeatPreload(this, 5);
}
function repeatPreload(Image, timeout){
    if(timeout > 0){
        setTimeout(function(){
            Image.src = Image.src.replace(/\?d=*[0-9]{6,}/g,"") + "?d=" + new Date().getTime();
            console.log("Fail to load image : " + Image.src + " , timeout : " + timeout);
            Image.onerror = repeatPreload(Image, timeout - 1);
        },2000);
    }else{
        Image["error"] = 1;
    }
}

I have already try to duplicate image folder and get image from duplicate folder when error happen but always fail.


text:
Q: virtual keyboard in JS but with images I want to make a virtual keyboard in HTML, CSS, and JavaScript. However, there is a twist. Instead of the letters on the keyboard, I would like to replace them with images of my own choice. So lets say,
instead of letter "a", i have an image of APPLE
instead of letter "s", I have an image of SNAKE

Was able to do it.

A: You can use HTML AND CSS Grid to do that, you just need the images and a file you can take them out of, unless there is an interactiveness to your website you won't be needing javascript

A: is this what you had in mind?

var elements = document.getElementsByClassName("key");

var myFunction = function(event) {
let text = document.getElementById('text')
text.innerText = text.innerText + event.target.id

};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', myFunction, false);
}
.keyboard{
display:flex;
justify-content:center;
}

img{
border:solid 2px green;
}


text:
Q: I want to convert a HTML table into a jSON array in angular 2 I have tried few methods but unable to get the desired output.
Here is my table like
<table>
   <tr>
    <th> Name </th>
    <th> Age </th>
   </tr>
   <tr>
     <td> foo </td>
     <td> 20 </td>
   </tr>
   <tr>
      <td> Boo </td>
      <td> 24 </td>
   </tr>
</table>

I want the desired jSON output as follows
[{
  Name: 'Foo',
  Age: 20
},{
  Name: 'Boo',
  Age: 24
}]

Can somebody please help?

A: Hello you can do like this :
const html = `<tr>
<th> Name </th>
<th> Age </th>
</tr>
<tr>
 <td> foo </td>
 <td> 20 </td>
</tr>
<tr>
  <td> Boo </td>
  <td> 24 </td>
</tr>`;
// For plug and play sample, i just create dummy table.
const tableEl = document.createElement('table');
tableEl.innerHTML = html;

const output = [];
// Little trick to make querySelectorAll as iterable by foreach.
[].forEach.call(
    tableEl.querySelectorAll('tr'),
    //Uncomment for TypeScript strong type : (lineElement: HTMLElement) => {
    (lineElement) => {
        const rows = lineElement.querySelectorAll('td');
        if(rows.length >= 2) {
            output.push(
                {
                    name : rows[0].innerText,
                    age : rows[1].innerText,
                }
            );
        }
    });

console.log(output);

__ UPDATE 1 : Dynamic attribute detection from th ___
const html = `<tr>
<th> Name </th>
<th> Age </th>
</tr>
<tr>
 <td> foo </td>
 <td> 20 </td>
</tr>
<tr>
  <td> Boo </td>
  <td> 24 </td>
</tr>`;
// For plug and play sample, i just create dummy table by programming way
const tableEl = document.createElement('table');
tableEl.innerHTML = html;

const output:any[] = [];
const keys: string[] = [];
// Little trick to make querySelectorAll as iterable by foreach.
[].forEach.call(
    tableEl.querySelectorAll('tr'),
    (lineElement: HTMLElement) => {
        const rows = lineElement.querySelectorAll('td,th');
        /**
         * If is th tag, we store all items to keys array.
         */
        if(rows[0].nodeName === 'TH') {
          //We replace remove all whitespace char from key.
          rows.forEach((e:HTMLElement) => keys.push(e.innerText.replace(/\s*/g,'')));
        }
        else {
          // We craft dynamically item object.
          let item: any = {};
          keys.forEach((key, index) => {
              // We use keys array to populate it.
              item[key] = rows[index].innerHTML;
          });
          //We Store it
          output.push(item);
        }
    });

console.log(output);

disclaimer :
This script assume you have only one tr with th inside AND is the first tr of your table. up to you to change this code to feet on another behaviour
Online sample


text:
Q: IllegalAccessError in springApplication in maven simple project I'm trying to run a simple application in maven after adding the Spring Jars 3.2.5.RELEASE, my Eclipse is 3.8.3.RELEASE, and I'm getting this error:
Exception in thread "main" java.lang.IllegalAccessError: tried to access method org.springframework.core.io.support.SpringFactoriesLoader.loadFactoryNames(Ljava/lang/Class;Ljava/lang/ClassLoader;)Ljava/util/List; from class org.springframework.boot.SpringApplication
at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:402)
at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:394)
at org.springframework.boot.SpringApplication.initialize(SpringApplication.java:261)
at org.springframework.boot.SpringApplication.<init>(SpringApplication.java:237)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175)
at Main.main(Main.java:8)

My main:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {

   public static void main(String[] args) {
      SpringApplication.run(Main.class, args);

   }

}

My pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0     http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>io.javabrains.springbootquickstart</groupId>
  <artifactId>course-api</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>TrySpring</name>

<parent>

  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.2.RELEASE</version>

</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>

</project>

I've also tried using STS but I get the same error.

A: Why are you using such an old version of Spring with the newest version of spring boot?  I would suspect the issue is a class path collision where the 3.2.5 release is getting referenced instead of the appropriate 4.x.x jar for a newer spring boot application.
When you use the starter poms like you are, all the required jars (a ton of excess actually) get included for your use, you shouldn't need to specifically include any spring jars on your path.


text:
Q: How to calculate the aspect ratio by a given factor? How do I calculate the aspect ratio (formatted as integer:integer) by a given factor?
For example, aspect ratio 16:9 has a factor of 1.778, because 16 / 9 = 1.778. But how can I find the ratio by that factor? So
Dimension getAspectRatio(double factor) {
    ...
}

public static void main(String[] arguments) {
    Dimension d = getAspectRatio(16d / 9d);
    System.out.println(d.width + ":" + d.height);
}

should return
16:9

A: This is not possible in general, since a double may not represent the actual (exact) fraction. You'll have to rely on heuristics or brute force as suggested in the other answers.
If you had the exact decimal expansion and period you could solve it though.
Here's the pen and paper way:

*

*Suppose you start with 1.77777... (which is 16/9 but let's assume that we didn't know that)

*You note that the period is 7 (one digit) so you multiply by 10 (i.e. move the decimal point one step to the right):
10n = 17.77777...

*You can now cancel out the repeating part by computing 10n - n:
10n - n = 17.77777... - 1.77777... = 16

*Solving for n yields n = 16/9
Translating this to code would require you to figure out the start and length of the period of the decimal expansion which will itself be a nasty problem, as the number could typically look something like 0.16666667.

A: Here is an implementation in Scala which finds the Best rational approximation based on the Farey sequence. This algorithm was suggested by @AakashM and it's translated from John D. Cook's Python implementation and David Weber's C++ modification.
/**
 * Calculates the `Best rational approximation` based on the Farey sequence.
 *
 * Translated from John D. Cook's Python implementation and David
 * Weber's C++ modification.
 *
 * @param x A value to be approximated by two integers.
 * @param eps The required precision such that abs(x-a/b) < eps. Eps > 0.
 * @param n The maximum size of the numerator allowed.
 * @return The best rational approximation for x.
 */
def farey(x: Double, eps: Double, n: Int): (Int, Int) = {

  @tailrec
  def iterate(a: Int, b: Int, c: Int, d: Int): (Int, Int) = {
    if (b <= n && d <= n) {
      val mediant = (a + c).toDouble / (b + d).toDouble
      if (Math.abs(x - mediant) < eps) {
        if (b + d <= n) {
          (a + c) -> (b + d)
        } else if (d > b) {
          c -> d
        } else {
          a -> b
        }
      } else if (x > mediant) {
        iterate(a + c, b + d, c, d)
      } else {
        iterate(a, b, a + c, b + d)
      }
    }
    else if (b > n) c -> d
    else a -> b
  }

  iterate(0, 1, 1, 0)
}

I've created a gist which contains also some tests.

A: This is an extremely late reply, but I have solved this using a much easier way and I know other's would appreciate it.
I'm assuming that you already know the screen resolution since you know the aspect ratio (decimal equivalent). You can find the aspect ratio (integer:integer) by solving for the greatest common factor between the screen width and height.
public int greatestCommonFactor(int width, int height) {
    return (height == 0) ? width : greatestCommonFactor(height, width % height);
}

This will return the greatest common factor between the screen width and height. To find the actual aspect ratio, you just divide the screen width and height by the greatest common factor. So...
int screenWidth = 1920;
int screenHeight = 1080;

int factor = greatestCommonFactor(screenWidth, screenHeight);

int widthRatio = screenWidth / factor;
int heightRatio = screenHeight / factor;

System.out.println("Resolution: " + screenWidth + "x" + screenHeight;
System.out.println("Aspect Ratio: " + widthRatio + ":" + heightRatio;
System.out.println("Decimal Equivalent: " + widthRatio / heightRatio;

This outputs:
Resolution: 1920x1080
Aspect Ratio: 16:9
Decimal Equivalent: 1.7777779

Hope this helps.
Note: This won't work for some resolutions. Comments contain more info.

A: Disclaimer: These algorithms are silly and inefficient. I'm sure there's a better one...
A silly, straightforward (not very efficient) algorithm to find an approximation is this:
double ratio = 1.778;
double bestDelta = Double.MAX_VALUE;
int bestI = 0;
int bestJ = 0;

for (int i = 1; i < 100; i++) {
  for (int j = 1; j < 100; j++) {
    double newDelta = Math.abs((double) i / (double) j - ratio);
    if (newDelta < bestDelta) {
      bestDelta = newDelta;
      bestI = i;
      bestJ = j;
    }
  }
}

System.out.println("Closest ratio: " + bestI + "/" + bestJ);
System.out.println("Ratio        : " + ((double) bestI / (double) bestJ));
System.out.println("Inaccurate by: " + bestDelta);

Output.
Closest ratio: 16/9
Ratio        : 1.7777777777777777
Inaccurate by: 2.2222222222234578E-4

Update: Alternative algorithm
I've just thought of an alternative algorithm, which tries to close in on the approximation. Of course, it's still not very efficient...
double bestDelta = Double.MAX_VALUE;
int i = 1;
int j = 1;
int bestI = 0;
int bestJ = 0;

for (int iterations = 0; iterations < 100; iterations++) {
  double delta = (double) i / (double) j - ratio;

  // Optionally, quit here if delta is "close enough" to zero
  if (delta < 0) i++;
  else j++;

  double newDelta = Math.abs((double) i / (double) j - ratio);
  if (newDelta < bestDelta) {
    bestDelta = newDelta;
    bestI = i;
    bestJ = j;
  }
}

System.out.println("Closest ratio: " + bestI + "/" + bestJ);
System.out.println("Ratio        : " + ((double) bestI / (double) bestJ));
System.out.println("Inaccurate by: " + bestDelta);

The output is the same
Should I stumble upon an efficient algorithm, I'll post it here :-)

A: This is a linear equation. In general you can't have two unknowns in a linear equation.

A: Actually, all the factors of form a/b are presented as finite ratios or infinite but periodic ratios (provided a and b are integers). Period can be pretty big, though. You could try to detect it and find exact ratio if period is, at least, half less than double precision. Or you could try to make best guess.

A: Aspect ratio can be be real number (1.85:1 for example), so I'm afraid its impossible to "guess" aspect ration from factor.
But there are maybe 10 common used aspect ratios. You could easy make factor-aspect ratio table.

A: If someone wants to calculate the tv height and width based on aspect ratio and diagonal use the below code.
public void printTvHeightAndWidth(){
            int widhtRatio = 16;
            int heightRatio = 9;
            int diagonal = 88;

            double tvHeight = (heightRatio * diagonal) / Math.sqrt(widhtRatio * widhtRatio + heightRatio * heightRatio);
            double tvWidth = (widhtRatio * diagonal) / Math.sqrt(widhtRatio * widhtRatio + heightRatio * heightRatio);
            DecimalFormat df = new DecimalFormat("#.##");
            System.out.println("W = " + df.format(tvWidth) + " H = " + df.format(tvHeight));

        }


text:
Q: Can we fire an event when ever there is Incoming and Outgoing call in iphone? Can I fire an event when ever there is Incoming and Outgoing call ends on iphone? Axample of an event is calling a webservice .

A: Yes you can, but not necessarily immediately.
There is a framework, called the CoreTelephony framework, which has a CTCallCenter class.  One of the properties on this class is the callEventHandler property.  This is a block that gets fired when then state of a phone call changes.  For example:
CTCallCenter *callCenter = ...; // get a CallCenter somehow; most likely as a global object or something similar?

[callCenter setCallEventHandler:^(CTCall *call) {
  if ([[call callState] isEqual:CTCallStateConnected]) {
    //this call has just connected
  } else if ([[call callState] isEqual:CTCallStateDisconnected]) {
    //this call has just ended (dropped/hung up/etc)
  }
}];

That's really about all you can do with this.  You don't get access to any phone numbers.  The only other useful tidbit of information is an identifier property on CTCall so you uniquely identify a CTCall object.
CAUTION:
This event handler is not invoked unless your app is in the foreground!  If you make and receive calls while the app is backgrounded, the event handler will not fire until your app becomes active again, at which point (according to the documentation linked to above) the event handler will get invoked once for each call that has changed state while the app was in the background.

A: No but you do get callbacks into the app when those events happen.
    -(void)applicationWillResignActive:(UIApplication *)application{
        //our app is going to loose focus since thier is an incoming call
        [self pauseApp];
    }

    -(void)applicationDidBecomeActive:(UIApplication *)application{
            //the user declined the call and is returning to our app
            [self resumeApp];
    }

A: No. As of the current SDK, this is not possible. Apple does not allow apps to have such hooks.


text:
Q: Sort with a button for a google spreadsheet I want a button in my spreadsheet which sorts based on 3 criteria.
I tried about 20 different ways of writing the syntax, but none of those worked.
I'd be glad if someone could tell me what is wrong.
function sort1() {
   sort({C3:K12;9;FALSE;3;TRUE;8;FALSE})
}

A: If strict adherence to your predefined sorting criteria is not important, and you are happy to let users adjust the sort by themselves, you can achieve this result quite simply by selecting the region of data of interest, and then creating a "filter" on it.

A Google Sheets "filter" is really a rich sorting and filtering mechanism. Implemented this way, the end user can achieve the exact sort you mentioned by selecting the 3rd sort criterion (column 8 in your example), the 2nd (column 3), and then the 1st (column 9).
Example of a filter applied to a region of a sheet:

A: function sort1() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var rg=sh.getRange(3,3,10,9);
  rg.sort([{column:11,ascending:false},{column:5,ascending:true},{column:10,ascending:false}]);//The sort options is an array of objects but the array can be left for just one.
}

Reference

A: You can't run a Sheets function from an Apps Script like that. If you are writing the script yourself, you will need to get a range object and sort that. You may want to start by recording a macro, which will write the script for you (Tools > Macros). Then you can look at the script and see what it is doing. Once the script is working the way you want, here's a good post on running a script from a button: https://www.benlcollins.com/apps-script/google-sheets-button/

A: Since you plan on doing 3 types of sorting, you could use three buttons, each for the wanted type of sort. Then you could attach to each one the type of sorting, like presented below.
The global variables sheet and range.
var sheet = SpreadsheetApp.getActive().getActiveSheet();
var range = sheet.getRange(3, 2, 11, 10);

The function sort1 sorts your data by points, descending:
function sort1() {
 range.sort([{column:11,ascending:false}]);
}

The function sort2 sorts your data by games, ascending:
function sort2() {
 range.sort([{column:5,ascending:true}]);
}

The function sort3 sorts your data by difference, descending:
function sort3() {
 range.sort([{column:10,ascending:false}]);
}

Afterwards, in order to assign the above functions, you should create three buttons, like this:

After creating the buttons, you should assign to each one of the them the above functions:

*

*SORT BY POINTS button -> sort1;

*SORT BY GAMES button -> sort2;

*SORT BY DIFF button -> sort3;
If you want to use all the sorting criteria in one instruction, you should just use all of them in the same sort method.
range.sort([{column:11,ascending:false},{column:5,ascending:true},{column:10,ascending:false}]);

Furthermore, I suggest you check the above links since they might be of help in your future development:

*

*Sheet Class Apps Script;

*Range Class Apps Script.


text:
Q: Why do I have to show this subspace is an invariant subspace? Consider a vector space $V \cong \mathbb{R}^n$ with an operator $I \in O(n)$ satisfying the property $I^2 = -Id_{V}$. See Linear Complex Structure for context. I want to show that $V$ has real dimension $2n$ (even dimension).
To do this, I was given the hint of working with $W = span\{x,Ix\}$ for a vector $x \in V$. It can be shown easily that $W$ is an invariant subspace of $I$ and $x \; \bot \; Ix$. Next I was told to note that $V = W \oplus W^{\perp}$ and to show that $W^{\perp}$ is also an invariant subspace of $I$.
This is where I am confused. I do not understand why we should show that $W^{\perp}$ is also an invariant subspace. I see that $W$ has degree $2$ and $W^{\perp}$has degree $n-2$, but i'm not really sure what I should be examining with the directsum $W \oplus W^{\perp}$.

A: Let $\vec{0}\neq x\in V$ be arbitrary and
$$W = \text{span}(\{x,Ix\}).$$
W is invariant
Since $I$ is orthogonal, we get $x\perp Ix$. Since $I^2x=-Ix\neq \vec{0}$, we have
$$\text{dim}(W)=2. $$
The set $W$ is invariant with respect to $I$ since
$$IW=I\left(\text{span}(\{x,Ix\})\right) = \text{span}(\{Ix,I^2x\}) = W.$$
$W^\perp$ is invariant
Consider $y\in W^\perp$ i.e. $y\perp x,\ y\perp Ix$. We get
$$\langle Iy,x\rangle=\langle I^2y,Ix\rangle=-\langle y,Ix\rangle=0$$
and
$$\langle Iy,Ix\rangle=\langle I^2y,I^2x\rangle=\langle y,x\rangle=0$$
Therefore $Iy\in W^\perp$.
Dimension argument
If $W^\perp=\{0\}$, the dimension of $V$ is $2$ and therefore even. If not, choose any $\vec{0}\neq x_2\in W^\perp$ define
$$V_2=W^\perp,\ I_2=I|_{V_2},\ W_2=\text{span}(\{x_2,Ix_2\})$$
We can apply the same algebra on $(V_2, I_2, W_2, x_2)$ as we did previously on $(V,I,W,x)$. Note that the invariance of $W^\perp=V_2$ lets us view $I_2$ as an operator
$$I_2: V_2\rightarrow V_2$$
We can therefore repeat the prevoius step to get
$$V = W \oplus W_2 \oplus W_3 \oplus ... \oplus W_k $$
$$\text{dim}(W_i) = 2,\ i=1,...,k$$
for some $k\in \mathbb{N}$. Now we can conclude
$$\text{dim}(V) = 2k$$
which is even.

A: Note that if $I$ satisfies $I^2 = -\mathrm{Id}_V$ then
$$ \det(I^2) = \det(I)^2 = \det(-\mathrm{Id}_V) = (-1)^{\dim V} $$
which immediately implies that $\dim V$ must be even. You don't even need to assume that $I$ is orthogonal.

A: The reason is matters that $W^{\perp}$ is invariant is that you can treat it as a vector space in its own right that has a linear transformation $I:W^{\perp}\to W^{\perp}$ with $I^2=-Id_{W^{\perp}}$. Since $W^{\perp}$ has strictly smaller dimension than $V$, we can use this fact in an induction proof to conclude that $\dim W^{\perp}$ is even. Now $\dim V=\dim W^{\perp}+\dim W$. Since $\dim W=2$, $\dim V$ is even.


text:
Q: NullPointerException When Loading Objects Into A ListView I'm attempting to do some mock-ups of a UI of an application that I'm building. I'm using a Navigation drawer as the root layout and I'm using nested fragments for one of my menu items in order to use a ViewPager with tab indicators. That part works fine when I just populate each of the fragments with just some basic text, but when I replaced the basic text in one of the children fragments (one of the tab views) with a ListView; I am getting a java.lang.NullPointerException in my fragment class.
public class FragmentVenues extends ListFragment {

private static final String ARGUMENT_KEY_PROPERTIES = "venue";

public static FragmentVenues newInstance(ArrayList<Venue> venues) {
    final Bundle args = new Bundle();
    args.putParcelableArrayList(ARGUMENT_KEY_PROPERTIES, venues);

    final FragmentVenues f = new FragmentVenues();
    f.setArguments(args);
    return f;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final List<Venue> venues =      getArguments().getParcelableArrayList(ARGUMENT_KEY_PROPERTIES);//error here
    setListAdapter(new VenueListAdapter(getActivity(), venues));
}

This is the ListAdapter that accesses a class that fills creates the objects to load into the ListView.
public class VenueListAdapter extends ArrayAdapter<Venue>{
private final LayoutInflater mInflater;

public VenueListAdapter(Context context, List<Venue> objects) {
    super(context, -1, objects);
    mInflater = LayoutInflater.from(context);

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final Venue venue = getItem(position);

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.fragmentvenues, parent, false);
    }

    // This will be made more efficient later
    TextView tv = (TextView) convertView.findViewById(R.id.city);
    tv.setText(venue.getCity() + ", " + venue.getState());
    tv = (TextView) convertView.findViewById(R.id.venuename);
    tv.setText(venue.getVenueName());
    tv = (TextView) convertView.findViewById(R.id.street);
    tv.setText(venue.getStreetAddress());
    tv = (TextView) convertView.findViewById(R.id.number);
    tv.setText(venue.getPhoneNumber());

    return convertView;

}
}

I'm trying to figure out what I'm doing wrong and/or if there's something I'm missing? This same code worked when I was using Action Bar Tabs but I abandoned them when I realized they're not meant to work with the Navigation Drawer. Below is the stack trace:
 03-17 23:45:39.345: E/AndroidRuntime(2184): FATAL EXCEPTION: main
03-17 23:45:39.345: E/AndroidRuntime(2184): java.lang.NullPointerException
03-17 23:45:39.345: E/AndroidRuntime(2184):     at com.testapp.slidingmenu.FragmentVenues.onActivityCreated(FragmentVenues.java:47)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1508)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.View.measure(View.java:15848)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.View.measure(View.java:15848)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.View.measure(View.java:15848)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.View.measure(View.java:15848)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:651)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.View.measure(View.java:15848)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.View.measure(View.java:15848)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.View.measure(View.java:15848)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.View.measure(View.java:15848)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.Choreographer.doFrame(Choreographer.java:532)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.os.Handler.handleCallback(Handler.java:730)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.os.Looper.loop(Looper.java:137)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at android.app.ActivityThread.main(ActivityThread.java:5103)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at java.lang.reflect.Method.invokeNative(Native Method)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at java.lang.reflect.Method.invoke(Method.java:525)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-17 23:45:39.345: E/AndroidRuntime(2184):     at dalvik.system.NativeStart.main(Native Method)

A: Implement Parcelable on both Venue Class and Fragment.
public class Venue implements Parcelable{

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub

}

}