text:
Q: How to properly static cast a vector in C++? I have a code in which at the end of a function I need to cast from int to double all the elements of an array in order to being able to do a final push_back before exiting the function. The code I have right now is:
template <class T, size_t dims> class A {
    typedef typename std::array<int, dims> ArrayInt;
    typedef typename std::array<double, dims> ArrayDouble;
    typedef typename std::vector <ArrayDouble> VectorDouble;

/* ...*/

foo() {
   /*  ...*/

   ArrayInt myArrayInt;
   ArrayDouble myArrayDouble;
   VectorDouble myVectorDouble;

    /* Initialize myArrayInt
    Do some other stuff */

    for (int i = 0; i < dims; ++i)
        myArrayDouble[i] = static_cast<double>(myArrayInt[i]);

    myVectorDouble.push_back(myArrayDouble);
    }
}

It works properly, but I do not feel comfortable about the lines:
for (int i = 0; i < dims; ++i)
    myArrayDouble[i] = static_cast<double>(myArrayInt[i]);

Is there any better way of doing this?
Thank you.

A: You can use a function from algorithm.
With copy_n :
std::copy_n( myArrayInt.begin(), dims, myArrayDouble.begin() );

or with copy :
std::copy( myArrayInt.begin(), myArrayInt.end(), myArrayDouble.begin() );

A: This can be written with less code, but it is explicit.
ArrayInt myArrayInt;
ArrayDouble myArrayDouble;
VectorDouble myVectorDouble;

/* Initialize myArrayInt
Do some other stuff */

using std::transform;
using std::copy;
using std::begin;
using std::end;

// with explicit conversion
auto to_double = [](const int i) { return double{i}; };
transform(begin(myArrayInt), end(myArrayInt), begin(myArrayDouble),
    to_double);

// with implicit conversion
copy(begin(myArrayInt), end(myArrayInt), begin(myArrayDouble));


text:
Q: Why does my carousel rotate when the page loads, but then stops completely? I am creating a full-stack application and for my hero page, I am working on adding a carousel that rotates images in the background.
So far I have created the HTML, CSS, and JavaScript files.
When the page loads, it rotates but then the carousel stops working and just stays on the first line.
I am not too sure if there is an error in my code but I would appreciate it if someone helped me out.

var slides = document.querySelectorAll('.slide');
var currentSlide = 0;

function changeSlide() {
  for (var i = 0; i < slides.length; i++) {
    slides[i].style.opacity = 0;
  }

  currentSlide = (currentSlide + 1) % slides.length;
  slides[currentSlide].style.opacity = 1;
}

setInterval(changeSlide, 3000);
*{
    margin: 0%;
    padding: 0%;
}
/*------------------------------Hero Page---------------------------------*/
.carousel {
    width: 100%;
    height: 700px;
    position: relative;
    overflow: hidden;
  }

  .slide {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    opacity: 0;
    transition: opacity 1s ease-in-out;
  }

  .slide:first-child {
    opacity: 1;
  }

  .slide-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    color: white;
  }
  .slide-1 {
    background-image: url(Images/derek-baumgartner-A7sfB4yKS7s-unsplash.jpg);
  }

  .slide-2 {
    background-image: url(Images/andrew-bain-jO_Q3EY_T0E-unsplash.jpg);
  }

  .slide-3 {
    background-image: url(Images/aaron-dowd-N7PDwky8doM-unsplash.jpg);
  }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
     <link rel="stylesheet" href="practice.css">
    <title>Welcome to Washington State - Home Page</title>

Slide 1

Slide 2

Slide 3

A: The problem is that you are loading your script before the page has been created and the script is running as soon as it is loaded.
You can add defer to the script, like so:

Or you can move the script to the end of the HTML.
Script Tag - async & defer would be a good source of information to read for this problem.
To make it easier to see your problem, I removed your images and simply set a background-color, height, and width in the CSS to see the slides and I reduced the delay in setInterval to 1500.

var slides = document.querySelectorAll('.slide');
var currentSlide = 0;

function changeSlide() {
  for (var i = 0; i < slides.length; i++) {
    slides[i].style.opacity = 0;
  }

  currentSlide = (currentSlide + 1) % slides.length;
  slides[currentSlide].style.opacity = 1;
}

setInterval(changeSlide, 1500);
* {
  margin: 0%;
  padding: 0%;
}

/*------------------------------Hero Page---------------------------------*/

.carousel {
  width: 100%;
  height: 700px;
  position: relative;
  overflow: hidden;
}

.slide {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.slide:first-child {
  opacity: 1;
}

.slide-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
}

.slide-1 {
  background-color: red;
  height: 150px;
  width: 200px;
}

.slide-2 {
  background-color: green;
  height: 150px;
  width: 200px;
}

.slide-3 {
  background-color: blue;
  height: 150px;
  width: 200px;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="practice.css">
  <title>Welcome to Washington State - Home Page</title>

Slide 1

Slide 2

Slide 3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importar dados do Mysql para Excel To querendo importar dados do Mysql para o excel usando Python, quando tento faze-lo da um erro de tuple. Alguém com mais experiencia pode me ajudar?
Segui o código e o erro:
# coding=utf-8

from Tkinter import *
from os import popen
import tkMessageBox
import sys
import ttk
import os,tkFileDialog
from PIL import ImageTk,Image
import MySQLdb
import PIL
import xlwt
import xlrd
import xlutils

class criarXLS:
    def __init__(self,master=None):
        self.master = master
        self.tela = Frame(width=500,height=300)
        self.tela.place(x=10,y=10)
        self.botGerar = Button(self.tela,text='Gerar Rel.',command=self.criarTabela)
        self.botGerar.grid(row=1,column=1)

    def conexaoBanco(self):
        BANCO = "ipuser_cde"
        USER = "root"
        PASSWD = "charlote1"
        HOST = "192.168.1.249"
        try:
            con = MySQLdb.connect(db=BANCO, user=USER, passwd=PASSWD, host=HOST)
            print("Conseguiu conectar ao Banco de Dados")
            #self.desativarOPDB()
        except MySQLdb as erro:
            print("Nao conseguiu conectar ao Banco de Dados.: ", erro)

        return con

    def criarTabela(self):
        self.workbook = xlwt.Workbook()
        self.worksheet = self.workbook.add_sheet('Rel.User')

        db = self.conexaoBanco()
        cursor = db.cursor()
        sql = "select iduser,nome,email from usuario"
        cursor.execute(sql)
        dadosUser = cursor.fetchall()

        self.worksheet.write(0,0, u'ID')
        self.worksheet.write(0,1, u'Nome')
        self.worksheet.write(0,2, u'Email')
        for i,user in enumerate(dadosUser()):
            self.worksheet.write(i + 1, 0, user['iduser'])
            self.worksheet.write(i + 1, 1, user['nome'])
            self.worksheet.write(i + 1, 2, user['email'])
        self.workbook.save('Rel-User.xls')
        db.close()

root = Tk()
root.geometry('1350x700+0+0')
root.configure(background='Grey21')
criarXLS(root)
root.mainloop()

Erro:
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
    return self.func(*args)
  File "E:/CharIp ServerFTP_1.1/CharIP_1.1.5/criar_rel.py", line 62, in criarTabela
    for i,user in enumerate(dadosUser(0)):
TypeError: 'tuple' object is not callable

A: dadosUser = cursor.fetchall()
# ...
for i,user in enumerate(dadosUser()):
    # ...

Você está tentando usar dadosUser() como uma função, dadosUser contém uma lista de tuplas ou uma lista vazia segundo a documentação.
Para iterar sobre a lista, retire ():
for i,user in enumerate(dadosUser):
    # ...


text:
Q: What is the logic behind string removal? Can someone explain the logic behind the order of .* and *.? Why do they have to be swapped when I want to remove from front and remove from back?
# IP="1.2.3.4"

# echo ${IP%.*}
1.2.3

# echo ${IP#*.}
2.3.4

A: %.* removes the last octet and the dot that precedes it. #*. removes the first octet and the dot that follows it. It's the preceding dot vs. following dot difference that explains why you swap the dot.
From the bash man page:

${parameter#word}
${parameter##word}

*

*Remove matching prefix pattern.  The word is expanded to produce a pattern just as in pathname expansion.  If the  pattern  matches
  the  beginning  of  the  value  of parameter, then the result of the expansion is the expanded value of parameter with the shortest
     matching pattern (the # case) or the longest matching pattern (the ## case) deleted.  If parameter is @ or *,  the  pattern
     removal  operation  is  applied  to each positional parameter in turn, and the expansion is the resultant list.  If parameter is an
     array variable subscripted with @ or *, the pattern removal operation is applied to each member of  the  array  in  turn,  and  the
     expansion is the resultant list.

  ${parameter%word}
${parameter%%word}

*

*Remove matching suffix pattern.  The word is expanded to produce a pattern just as in pathname expansion.  If the pattern matches a
        trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter  with  the
        shortest  matching pattern (the % case) or the longest matching pattern (the %% case) deleted.  If parameter is @ or *, the
        pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list.   If  parameter
        is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the
        expansion is the resultant list.


text:
Q: Bound states, scattering states and infinite potentials I am doing my first semester of Quantum Mechanics and we're using Griffith's Introduction to Quantum Mechanics. As he is introducing the Dirac delta function potential he explains bound and scattering states, and I understand that a system is considered bound if the energy of the system is less than the potential at infinity, that is
\begin{align}
\text{Bound state: } E &< \lim_{|x| \to \infty} V(x)\\
\text{Scattering state: } E &> \lim_{|x| \to \infty} V(x).
\end{align}
That makes sense, and he then continues by saying that this implies that $E<0$ for bound states and $E>0$ for scattering states, as you can always add a constant to the potential energy to make it zero at infinity.
He also explains how the solution to the Schrödinger equation for bound states is a discrete linear combination, and the solution for scattering states is an integral which cannot be normalized, and therefore does not exist. He then continues with the Dirac delta function potential unabated.
The problem I have is how to reconcile this with the previous chapter, in which he treated the harmonic oscilator - a bound system - and found the energy levels to be
$$E_n = \hbar \omega \left(\frac{1}{2}+n\right),$$
which is positive even though the potential goes to infinity at infinity. I suppose you could "subtract infinity" and get an infinitely negative energy (and 0 potential at infinity), but that's a bit weird at best. Part 1 of the question: Is that all there is to it? "Subtract infinity" and then the second inequality ($E<0$) works?
Part 2 of the qustion: since infinite potentials are just approximations and do not really exist (or do they?), how can bound states ever exist (Griffith remarks that finite potentials can be overcome by tunneling)? Additionally, scattering states also do not exists as their wavefunctions are non-normalizable. So the conclusion is that nothing really exists according to Quantum Mechanics... which can't be right, surely?

A: The distinction to be made here is that, for the quantum harmonic oscillator system, there are no unbound states, only bound states thus, there is no benefit to insisting the states have negative energy, no reason to 'subtract infinity' in order to zero the potential at infinity.
However, in systems that permit both bound and unbound states, it is reasonable to zero the potential at infinity for the same reason that we do this classically.
For example, in the classical central force problem, there is a state in which particle can 'escape to infinity' where it will have zero kinetic energy (more precisely, the kinetic energy of the particle asymptotically approaches zero).  If we set the potential energy to be zero at infinity, then the total energy 'at infinity' is zero.  Thus, the particle with zero total energy 'sits on the boundary' between those particles with not enough energy to 'reach' infinity and those that do.
But, for the classical harmonic oscillator potential, no particle can escape to infinity.  The kinetic energy of the particle will periodically and instantaneously be zero.  In this case, it is reasonable that the state where the total energy is always equal to the potential energy (the state where the kinetic energy is always zero) be the zero total energy state; all other states having positive total energy.

So the conclusion is that nothing really exists according to Quantum
  Mechanics... which can't be right, surely?

That's not remotely the correct conclusion to draw.  One might conclude instead that
(1) The conception of bound state must be modified in the passage from classical mechanics to quantum mechanics and
(2) the physical (normalizable) unbound states are not eigenstates of the Hamiltonian, i.e., the physical unbound states are not states of definite energy but are, instead, a distribution of energy eigenstates, e.g., a wavepacket.

A: Part 1. Essentially you're right. You can think of it as subtracting infinity from the energy. A better way to view it is that the convention that the zero of energy should correspond to potential at infinity was always an arbitrary choice. Normally it is a very sensible convention, but if the potential diverges at infinity, as is the case for the harmonic oscillator, clearly another choice would be better. In practice we normally use harmonic oscillators as approximations to more complex potentials which do not diverge and this often works pretty well as we require the wavefunction to go to zero at infinity anyway.
Part 2 Bound States are defined to be those states with a lower energy than a free particle in a given potential. A particle cannot go from a bound state to a continuum state without an input of energy. If I have an isolated hydrogen atom the electron cannot spontaneously escape from the proton because this would increase its energy.
Quantum tunnelling occurs when there are two areas of low potential separated by an area of high potential, where the particle would be forbidden to enter classically. This can be a pair of potential wells or two areas of free space separated by a potential barrier (which is what Griffith was referring to) So for example if I have my hydrogen atom and bring another proton close to it the electron can tunnel from one proton to the other, even though it could not became a free particle and so classically could not leave the atom it started out bound to. Generally what happens in these situations with multiple potential wells is that the in the stationary states the particle is in a superposition of being in both wells. This is what happens when a covalent bond forms.


text:
Q: Convert CSV to JSON in desired format using python I would like to collect some insights on getting below output from it's corresponding input, I  tried some code but couldn't get result I wanted. Would like to see the table getting converted to desirable format as I have to work with huge CSV in later stage. Any inputs are highly appreciated.
Input:

Reference
mcc
Value
currency

abcd1234
5300
134.09
USD

abcd1235
5411
38.48
USD

Code used:
from csv import DictReader
from itertools import groupby
from pprint import pprint
import json

with open('Test_bulk_transactions_data.csv') as csvfile:
    r = DictReader(csvfile, skipinitialspace=True)
    data = [dict(d) for d in r]

    group = []
    uniquekeys = []

    for k, g in groupby(data, lambda r: (r['reference'], r['mcc'])):
        group.append({
            "reference": k[0],
            "mcc": k[1],
            "amount": [{k:v for k, v in d.items() if k not in ['reference','mcc']} for d in list(g)]})
        uniquekeys.append(k)

print(json.dumps(group, indent = 3) + '}')

Current Output:
[
   {
      "reference": "abcd1234",
      "mcc": "5300",
      "amount": [
         {
            "value": "134.09",
            "currency": "USD"
         }
      ]
   },
   {
      "reference": "abcd1235",
      "mcc": "5411",
      "amount": [
         {
            "value": "38.48",
            "currency": "USD"
         }
      ]
   }
]}

Desired Output:
{
  "cardTransactions": [
    {
      "reference": "abcd1234",
      "mcc": "5300",
      "amount": {
        "value": 134.09,
        "currency": "USD"
      }
    },
    {
      "reference": "abcd1235",
      "mcc": "5411",
      "amount": {
        "value": 38.48,
        "currency": "USD"
      }
    }
  ]
}

A: Looks like you just need to append everything into "cardTransactions" key, and  the value can be cast to float when created.
"amount": [{k: float(v) for k, v in d.items() if k not in ['reference','mcc']} for d in list(g)]})

group = [] to group = defaultdict(list)
and group['cardTransactions'].append(... code as usual ...)

A: your desired output will not allow for multiple value/currency in a given transaction, so you don't need to use groupby at all.
The process could be like this:
data = { 'cardTransactions':
         [{ 'amount': {'value'   : float(d.pop('Value')),
                       'currency': d.pop('currency')},
             **d }
          for d in r ]}

print(json.dumps(data, indent = 3))


text:
Q: Mouse on left of screen move image to left, same when mouse on right of screen I'm trying to get an image that is around 1920x1200px to pan around on a 800x600px browser window.
So if my mouse is on the top-left of the browser window the image is alined so it's top-left margins are on the top-left of the browser window. The same goes for the bottum-right.
So if the mouse is in the centre of the screen the image should be centered too.
Im not sure what calculations are needed as my math is a bit rusty.
Currently I'm using a bit of javascript that just moves the image using CSS's top/left properties but without much success as it's just moving the picture around from it's top/left corner.
I'v also set the image's position to absolute in css.
function updateImgPosition( e )
{
    var avatar = document.getElementById("avatar");
    // Width
    var windowWidth = window.innerWidth;
    var mouseWidthLocation = e.x;
    var percentOfWidth = (100 / windowWidth) * mouseWidthLocation;

    // Height
    var windowHeight = window.innerHeight;
    var mouseHeightLocation = e.y;
    var percentOfHeight = (100 / windowHeight) * mouseHeightLocation;

 avatar.style.top   = percentOfHeight + "%";
 avatar.style.left  = percentOfWidth + "%";

}

document.onmousemove = updateImgPosition;

This is a demo of what I have: http://jsfiddle.net/uQAmQ/1/

A: Fiddle: http://jsfiddle.net/uQAmQ/2/
You should not "pan" on an absolutely positioned element, because the window's width and height keep changing according to the image. A smoother solution involves using a background image. See the middle of my answer for the used logic.
Consider this JavaScript (read comments; HTML + CSS at fiddle):
(function(){ //Anonymous function wrapper for private variables
    /* Static variables: Get the true width and height of the image*/
    var avatar = document.getElementById("avatar");
    var avatarWidth = avatar.width;
    var avatarHeight = avatar.height;
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;

    /* Logic: Move */
    var ratioY = (avatarHeight - windowHeight) / windowHeight;
    var ratioX = (avatarWidth - windowWidth) / windowWidth;

    function updateImgPosition( e ) {

        var mouseY = e.pageX; //e.pageX, NOT e.x
        var mouseX = e.pageY;
        var imgTop = ratioY*(-mouseY);
        var imgLeft = ratioX*(-mouseX);
        document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";

    }

    /* Add event to WINDOW, NOT "document"! */
    window.onmousemove = updateImgPosition;
})();

The logic behind it:

*

*Relative units cannot be used, because the image size is specified in absolute units.

*The offsets should change according to a specific ratio, which is similar to: image size divided by window size.However, this ratio is not complete: The image would disappear at the bottom/left corner of the window. To fix this, substract the window's size from the image's size. The result can be found in the code at variable ratioX and ratioY.

The previous code had to be loaded at the window.onload event, because the image's size was dynamically calculated. For this reason, a HTML element was also included in the body.

The same code can be written much smaller and efficient, by specifying the size of the background in the code. See this improved code. Fiddle: http://jsfiddle.net/uQAmQ/3/
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
    var avatarWidth = 1690;
    var avatarHeight = 1069;
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;

/* Logic: Move */
    var ratioY = (avatarHeight - windowHeight) / windowHeight;
    var ratioX = (avatarWidth - windowWidth) / windowWidth;

function updateImgPosition( e ) {
    var mouseX = e.pageX; //e.pageX, NOT e.x
    var mouseY = e.pageY;
    var imgTop = ratioY*(-mouseY);
    var imgLeft = ratioX*(-mouseX);
    document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";

}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();

If you don't mind a decreased code readability, the following code is the best solution, Fiddle: http://jsfiddle.net/uQAmQ/4/:

(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    var ratioY = (windowHeight - 1069) / windowHeight;
    var ratioX = (windowWidth - 1690) / windowWidth;

    window.onmousemove = function( e ) {
        document.body.style.backgroundPosition = ratioX * e.pageX + "px " + ratioY * e.pageY + "px";
    }
})();


text:
Q: Email Issue in Magento 2 Email is not received after subscribe but I got a success message in the home page. How to fix it?

A:
Newsletters are for easily inform customers about new products,
  specials, promos, etc.

Please read here Newsletter Functionality
Also check How to configure Configuring Newsletters
Hope it Helps.

A: You need to install SMTP extension to send emails in local environment
https://www.mageplaza.com/magento-2-smtp/
And You can see the details for the configuration here


text:
Q: Composition of Differential Operators If I have:
$A=\partial_x^2+u(x)$
$B=u(x)\partial_x$
How do I compose: $AB$ and $BA$?

A: This is just usual composition of functions: for all $f$ in an appropriate domain
$(AB)(f)=A(B(f))=(\partial^2_x+u)(u\partial_x f)=\partial^2_x (u\partial_x f)+u^2\partial_x f=\cdots$ using the chain rule, and similarily for $BA$. Notice that $u$ acts as a multiplication operator. Apart from that, it is totally crucial for composition that you specify both domain and codomain of $A$ and $B$ and in particular what is assumed about $u$ (say domain and codomain is $C^\infty$, and $u$ be also of class $C^\infty$).


text:
Q: Cannot compare the values of two columns correctly using tidyverse I have a dataset with several columns and about 22,000 rows. My goal is to determine if each row equals the maximum value of that row. I do so by creating a dummy variable column.
Here is an example of the data.

Here is the code I have. testdf is the dataframe and test2 is the output.
Please excuse the fact that the third and fourth rows do the same thing as the fifth row's command. I had tried it manually to keep my own sanity.
test2 = testdf %>%
  ungroup() %>%
  mutate(New_Column_1 = max(Column_C)) %>%
  mutate(New_Column_2 = if_else(Column_C == New_Column_1, "Yes", "No")) %>% # the previous and this line execute the next line manually
  mutate(`Final?` = case_when( # this method still doesn't work
    Column_C == max(Column_C) ~ "Y",
    TRUE ~ "N"
  ))

Here is the output.

Since all the numbers in Column_C are the same, I expected for all rows to return a "Y" or "Yes". However, only the seventh and twelfth rows returned a "Y" or "Yes" in columns "Final?" and "New_Column_2."
Even more weirdly, when I tried to create a reproducible example using dput and ran the same code, the results were correct. Here is the result after running the same code on the dataframe created using dput.

I'm not sure why the reproducible example doesn't behave incorrectly and if the reproducible dataframe will be useful, but here it is below anyway.
testdf_dput = structure(list(Column_A = 1:12, Column_B = c(458, 458, 458, 458,
438, 407, 382, 355, 345, 338, 322, 307), Column_C = c(458, 458,
458, 458, 458, 458, 458, 458, 458, 458, 458, 458), Column_D = c(531,
531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531), Column_E = c(181833.517467249,
181833.517467249, 181833.517467249, 181833.517467249, 188243.751141552,
193750.334152334, 198517.429319372, 201049.918309859, 203428.110144927,
205612.289940828, 205185.167701863, 206427.749185668), Column_F = c("Melissa",
"Dominique", "Ronald", "Jedediah", "Samantha", "Justin", "Jeanmarc",
"Tiffany", "Jacob", "David", "Schyanne", "Vincent"), Column_G = c("2019",
"2019", "2019", "2019", "2019", "2019", "2019", "2019", "2019",
"2019", "2019", "2019")), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))

library(tidyverse)

test3 = testdf_dput %>%
  mutate(New_Column_1 = max(Column_C)) %>%
  mutate(New_Column_2 = if_else(Column_C == New_Column_1, "Yes", "No")) %>% # the previous and this line execute the next line manually
  mutate(`Final?` = case_when( # this method still doesn't work
    Column_C == max(Column_C) ~ "Y",
    TRUE ~ "N"
  ))

Please let me know if you've experienced something like this. I have no idea what is going on.
Thanks in advance.


text:
Q: How to auto-hide bookmarks bar in Chrome? I am looking for a way to auto-hide the bookmarks bar in Chrome, so that it only shows when I hover over the area.
I'd also like a method to auto-hide the address bar in Chrome that works in a similar fashion.
A Google search gave me a method for the latter, but it doesn't seem to work any more (no "Compact Navigation") option in about:flags as far as I can see).
All suggestions welcome, including extensions.

A: Try control + Shift + B, which hides bookmark bar when any website is opened and only shows in a new tab or home page.

A: If you have a Windows computer, you can make the browser full-screen with F11. This auto-hides the address bar and bookmark bar and when you move your mouse to the top of the screen, it will show up again. However, both the address bar and bookmark bar will show up; as far as I know there is no way to make them show separately.

A: There is currently no way to permanently hide the bookmarks bar in Chrome. sadly this type of behaviour has led to a prevalence of junk "help" websites offering pretty much the same useless advice.
Ultimately until the feature is changed, another browser may be the answer.
I gets rather tedious using keystrokes for every tab. I suppose the developers at Google have a lot of screen real estate and don't think about people on 800x480 when adding these features, or assume they fullscreen by default.
Personally I have a page of bookmarks for my home page so I can remove the bookmarks from chrome. This does not suit everybody.


text:
Q: Is a parameterized java persistence query susceptible to sql injections? For eg. i have:
Input:
ArrayList<Integer> idlist
String nameText

    String q = "DELETE FROM myTable AS a WHERE a.name LIKE '%' || :name || '%' OR a.id IN (:idlist)";

    Query query = entityManager.createQuery(q);
    query.setParameter("name", nameText);
    query.setParameter("idlist", idlist);

query.executeUpdate();

Would the above snippet of code susceptible to sql injections?
I have one more question is there a diffrence between the way above query is built and if we form query by criterias:
CriteriaBuilder cb = em.getCriteriaBuilder();

  CriteriaQuery<Country> q = cb.createQuery(Country.class);
  Root<Country> c = q.from(Country.class);
  q.select(c);

Is there any advantage of one over another?

A: No, it wouldn't. That's the whole point of parameterized queries.

A: There is no chance for SQL injection with prepared statements.
But if the values of parameter are entered by users, the expression LIKE % || :name || % can be misused by entering only one letter and deleting all the records that contain that letter anywhere in the a.name column


text:
Q: Using one memorystream for multiple file search iterations I'm having several methods which each apply an operation to the a textfile, where the next operation requires the result of the previous operation as input:
private TextReader input = new StreamReader("input.txt");
private TextWriter output = new StreamWriter("output.txt");
MemoryStream result_1 = new MemoryStream();
MemoryStream result_2 = new MemoryStream();

Operation_1(input, ref result_1);
Operation_2(result_1, ref result_2);
Operation_3(result_2, output);

The code for Operation_1:
   private void Operation_1(TextReader input, ref MemoryStream output)
    {
        TextWriter outputWriter = new StreamWriter(output);
        String line;

        while (input.Peek() >= 0) //while not end of file
        {
            line = input.ReadLine();
            //perform operation on line
            outputWriter.writeline(line);
        }
        input.Close();
    }

the code for operation_2:
   private void Operation_2(TextReader input, ref MemoryStream output)
    {
        input.Seek(0, SeekOrigin.Begin); //reset stream to start of file
        TextReader inputReader = new StreamReader(input);
        TextWriter outputWriter = new StreamWriter(output);
        String line;

        while (inputReader.Peek() >= 0) //while not end of file
        {
            line = inputReader.ReadLine();
            //perform operation on line
            outputWriter.writeline(line);
        }
        inputReader.Close();
    }

The code for operation_3:
    private void operation_3(MemoryStream input, TextWriter output)
    {
       input.Seek(0, SeekOrigin.Begin);  //reset stream to start of file
       TextReader inputReader = new StreamReader(input);
       String line;

       while (inputReader.Peek() >= 0) //while not end of file
       {
            line = inputReader.ReadLine();
            //perform operation on line
            output.writeline(line);
       }
       inputReader.Close();
       output.Close();
    }

Now the problem is that i'm not getting the same result as storing each intermediate result to a physical txt file on the harddisk and using that file for the next operation. A few lines and the end of the file is missing.
Also this seems like not a very clean and generic way of doing it.
So hence my question; why are my results different when using MemoryStream for the intermediate results and is there a cleaner, more flexible way of doing this? (I want to work towards a solution were it is possible to choose if you want to save the intermediate results or not).

A: *

*They are different, because you forgot to flush your writers.

*The ref modifiers are not needed, because you don't create a new MemoryStream in your operations

Your methods would be a bit cleaner this way:
private void Operation_1(TextReader input, Stream output)
{
    TextWriter outputWriter = new StreamWriter(output);
    String line;

    outputWriter.Write(input.ReadToEnd());
    outputWriter.Flush();

    input.Close();
}

private void Operation_2(Stream input, Stream output)
{
    input.Seek(0, SeekOrigin.Begin); //reset stream to start of file
    TextReader inputReader = new StreamReader(input);
    TextWriter outputWriter = new StreamWriter(output);

    outputWriter.Write(inputReader.ReadToEnd());
    outputWriter.Flush();
    inputReader.Close();
}

The code for operation_3:
private void operation_3(Stream input, TextWriter output)
{
   input.Seek(0, SeekOrigin.Begin);  //reset stream to start of file
   TextReader inputReader = new StreamReader(input);

   output.Write(inputReader.ReadToEnd());

   inputReader.Close();
   output.Flush();
   output.Close();
}

A: I have a suggestion to change your code. Maybe instead of using Streams and TextReaders you could just work with IEnumerable.
Please see the sample below (It's just a sample. Error handling not included to keep the sample simple.)
The result of the previous operation is provided as parameter to the next. Therefore, it get's executed as following Operation3(Operation2(Operation1))).
The first sample below is reading and changing the lines contained in the file line by line
The second sample below is reading the whole file and changing the lines providing all lines to the next operation (lines.ToArray() reads the whole file).
With streams you always have to be careful that they are disposed correctly and at the desired time (for example StreamReader closes the inner stream by default when StreamReader gets disposed).
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main()
        {
            //line per line...
            File.WriteAllLines
                (
                    @"C:\temp\output.txt",
                    ChangeLines(File.ReadLines(@"C:\temp\input.txt"),
                                line =>
                                LineOperation3
                                    (
                                        LineOperation2
                                            (
                                                LineOperation1(line)
                                            )
                                    )
                        )
                );

            //lines per lines...
            File.WriteAllLines
               (
                   @"C:\temp\output2WithCount.txt",
                   ChangeLines(File.ReadLines(@"C:\temp\input.txt"),
                               lines =>
                                        LinesCountOperation
                                        (
                                            LinesCountOperation
                                            (
                                                LinesCountOperation(lines,LineOperation1),
                                                LineOperation2
                                            )
                                            , LineOperation3
                                          )
                       )
               );
        }

        private static IEnumerable<string> ChangeLines(IEnumerable<string> lines, Func<string, string> lineFunc)
        {
            foreach (var line in lines)
            {
                yield return lineFunc(line);
            }
        }

        private static IEnumerable<string> ChangeLines(IEnumerable<string> lines, Func<IEnumerable<string>, IEnumerable<string>> linesFunc)
        {
            foreach(var changedLine in linesFunc(lines))
            {
                if (changedLine != null)
                {
                    yield return changedLine;
                }
            }
        }

        private static IEnumerable<string> LinesCountOperation(IEnumerable<string> lines, Func<string, string> lineFunc)
        {
            var readAllLines = lines.ToArray();
            var linesCount = readAllLines.Count();

            foreach (var line in readAllLines)
            {
                var changedLine = lineFunc(line);
                if (changedLine == null)
                {
                    continue;
                }
                yield return string.Format(CultureInfo.InvariantCulture, "{0}-{1}", linesCount, changedLine);
            }
        }

        private static string LineOperation1(string line)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}{1}", line, "1");
        }

        private static string LineOperation2(string line)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}{1}", line, "2");
        }

        private static string LineOperation3(string line)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}{1}", line, "3");
        }
    }
}


text:
Q: How can I put a gradient color on a button text? So, i have this bootstrap button:
<button type="button" class="btn btn-outline-primary btn-lg">Some text</button>

and I want to make the button text ("Some text") to have this gradient:
linear-gradient(to bottom right, #67b26f, #4ca2cd);

I tried to set the color property to add gradient using CSS, but not working.
Is there a way using CSS to give that text a gradient color?
Thank you and have a good day!

A: Try this one

button {
 font-size: 72px;
 background: -webkit-linear-gradient(#eee, #333);
 -webkit-background-clip: text;
 -webkit-text-fill-color: transparent;
}
<button type="button" class="btn btn-outline-primary btn-lg">Some text</button>

UPDATE
If you want to add background-color for button then you can use :after
  content.

LIke this :

button {
  position: relative;
  font-size: 72px;
  background: -webkit-linear-gradient(#eee, #333);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* for adding bg-color for btn */
button:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: blue;
  z-index: -1;
}
<button type="button" class="btn btn-outline-primary btn-lg">Some text</button>

A: Try setting the gradient as the background-image and then set the text color to transparent and then use the -webkit-background-clip property to set it to text. Try this:
.gradient-text {
    background-image: linear-gradient(to bottom right, #67b26f, #4ca2cd);
    -webkit-background-clip: text;
    color: transparent;
}

now just add the gradient-text class to the button and make sure it comes after the bootstrap styles :)


text:
Q: How can I stack multiple frames in Tkinter For my project, I need to create a GUI using Tkinter. I wanted to divide it into 4 different frames, each with different background colors. However, when I do this, only the first frame's background color is shown. I attached my code below as well as a screenshot of the output I'm getting.

from Tkinter import *
import tkMessageBox

root = Tk()
root.geometry("950x800")
root.configure(background="black")

def test():
   print("this is a test")

# *****Frames*****

fileFrame = Frame(root)
fileFrame.configure(background="yellow")
fileFrame.pack()
attributeFrame = Frame(root)
attributeFrame.configure(background="red")
attributeFrame.pack()
constraintFrame = Frame(root)
constraintFrame.configure(background="purple")
constraintFrame.pack()
preferenceFrame = Frame(root)
preferenceFrame.configure(background="blue")
preferenceFrame.pack()

# *****File Frame*****

label_1 = Label(fileFrame, text="Enter Attributes file name:", anchor="e",
bg="red", font="Times 25", width=25, height=1)
label_2 = Label(fileFrame, text="Enter hard constraints file name:",
anchor="e", bg="blue", fg="yellow", font="Times 25", width=25, height=1)
label_3 = Label(fileFrame, text="Enter preferences file name:",
anchor="e", bg="purple", fg="green", font="times 25", width=25, height=1)
entry_1 = Entry(fileFrame, font="Times 25")
entry_2 = Entry(fileFrame, font="Times 25")
entry_3 = Entry(fileFrame, font="Times 25")
button_1 = Button(fileFrame, text="Submit", bg="red", font="Times 20")
button_2 = Button(fileFrame, text="Submit", bg="blue", fg="yellow",
font="Times 20")
button_3 = Button(fileFrame, text="Submit", bg="purple", fg="green",
font="Times 20")
label_1.grid(row=0, padx=5, pady=5)
entry_1.grid(row=0, column=1)
button_1.grid(row=0, column=2, padx=5, pady=5)
label_2.grid(row=1, padx=5, pady=5)
entry_2.grid(row=1, column=1)
button_2.grid(row=1, column=2, padx=5, pady=5)
label_3.grid(row=2, padx=5, pady=5)
entry_3.grid(row=2, column=1)
button_3.grid(row=2, column=2, padx=5, pady=5)

# *****Attribute Frame*****

label_Attribute_header = Label(attributeFrame, text="Attributes:",
bg="red", font="Times 25", width=25, height=1)
label_Attribute_header.pack()

# *****Constraint Frame*****

label_Constraint_header = Label(constraintFrame, text="Hard Constraints:",
bg="purple", fg="green", font="Times 25", width=25, height=1)
label_Constraint_header.pack()

# *****Preference Frame*****

label_Preference_header = Label(preferenceFrame, text="Preferences:",
bg="blue", fg="yellow", font="Times 25", width=25, height=1)
label_Preference_header.pack()

root.mainloop()

I expect there to be 4 different frames, all stacked on top of each other with different background colors, but instead only the first frame has a background color. Can somebody explain to me why this is and how I should go about fixing this? Thanks

A: Your frames are there. The bottom three frames have fewer things in them and you haven't given them any padding. The frame shrinks to fit, so when you just have one item, you won't see the frames.
You can easily see the frames if you do one of two things:
First, you can request that the frames fill their parent window in the x direction. When you do this, you'll see them:
fileFrame.pack(fill="x")
attributeFrame.pack(fill="x")
constraintFrame.pack(fill="x")
preferenceFrame.pack(fill="x")

Second, instead of or in addition to that, you can give padding around the labels in the bottom frames. That will let the frame colors appear.
label_Attribute_header.pack(padx=20, pady=20)
...
label_Constraint_header.pack(padx=20, pady=20)
...
label_Preference_header.pack(padx=20, pady=20)


text:
Q: Should a method should be throwing an exception to the Unit Test? I have a simple method for sending emails:
public void notifyEmail(string messageSubject, string messageBody)
{
   MailMessage message = new MailMessage(from, to);

   message.Subject = messageSubject;
   message.Body = messageBody;

   SmtpClient client = new SmtpClient(smtp_client);
   client.Send(message);

   message.Dispose();//release everything related
}

And a unit test (I'm learning):
[TestMethod()]
    public void notifyEmailTest()
    {
        eMail target = new eMail("TEST Subject","TEST Body"); // TODO: Initialize to an appropriate value

        bool testSent = true;
        try
        {
            target.notifyEmail();
        }
        catch (Exception)
        {
            testSent = false;
        }

        Assert.IsTrue(testSent);
    }

I deliberately set the smtp_client variable value to something invalid.
Running the code in my project results in an error.
Running the test method results in a Pass.  Should my test or method be structured differently so that errors will fail the test?

A: If you expect that target.notifyEmail() should be throwing an exception, then that's what you should be testing for. If you were using NUnit you could use Assert.Throws<T>, e.g.
[Test]
public void notifyEmailTestFails()
{
    // TODO: Initialize to an appropriate value
    eMail target = new eMail("TEST Subject","TEST Body");
    Assert.Throws<InvalidOperationException>(target.notifyEmail());
}

However, now I see you're using VSUnit you should be using [ExpectedException(typeof(...))]
as mentioned in other answers.
In general you should have separate tests for success, failure, and for exception conditions.

A: I always do everything I can to avoid putting try-catch clauses on my unit tests. Instead try using the ExpectedException attribute (the attribute is the same for NUnit and MSTest) and set the type to the exception you are expecting i.e.
[TestMethod]
[ExpectedException(typeof(NetworkException))]
public void ShouldThrowNetworkExceptionIfSmtpServerIsInvalid)
{
     //... test code here.
}

Another approach that I have used is to create a static class with an AssertExpectedException method since sometimes a method can throw the same type of exception for different reasons and the only way to know for sure if the accurate message is being returned is with custom code since the attribute does not assert the message the thrown exception is returning.
Hope this helps.
Regards.

A: The way I normally do this is to decorate the test with ExpectedException (
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute(v=vs.80).aspx)
. But you want to catch something MUCH less generic than "Exception."
If you don't want to use expected exception, then instead of:
 bool testSent = true;

        try
        {
            target.notifyEmail();
        }
        catch (Exception)
        {
            testSent = false;
        }

        Assert.IsTrue(testSent);

You can be a little less verbose:
try{
 target.notifyEmail();
 Assert.Fail("Expected an exception here");
}
catch (SmtpException){

}

A: I would highly recommend you to try the FluenAssertions:
http://fluentassertions.codeplex.com/
They are simple awesome and Elegant
And they let you check the exception message (You can not do that with the ExpectedException attribute)
Example:
using FluentAssertions;

[TestMethod]
public void notifyEmailTest()
{
    eMail target = new eMail("TEST Subject","TEST Body"); // TODO: Initialize to an appropriate value

target.Invoking(x => x.notifyEmail())
    .ShouldThrow<YourExcpectedException>()
            .WithMessage("Your expected message", FluentAssertions.Assertions.ComparisonMode.Substring);
}


text:
Q: Qt and Qt Creator. Pure installation I used Qt Creator 3.5.0 without any problems. But after these actions I got some issues:

*

*I always used Qt Creator without super permissions, but at that time I launched it as root

*After that I tried to run Qt Creator as usually but got a lot of errors like:

Cannot overwrite file
  /home/user/.config/QtProject/qtcreator/qtversion.xml: Permission
  denied
Could not save session to file
  /home/user/.config/QtProject/qtcreator/default.qws
Cannot overwrite file
  /home/user/.config/QtProject/qtcreator/qnx/qnxconfigurations.xml:
  Permission denied

*My Android emulator settings has been reset.

*I also got some messages like:

No .user settings file created by this instance of Qt Creator was
  found...

*I could not save some files due to:

Cannot set permissions for /home/user/QtProjects/test_project/mainwindow.cpp to writable.
  Could not save the files.

*
/home/user/QtProjects/build-test_project-Desktop-Debug/ui_mainwindow.h:13:
  error: QtWidgets/QAction: No such file or directory

*But the main problem is that I can't use some my packages which are already installed:

No package 'gstreamer-video-1.0' found
No package 'gstreamer-1.0' found
Project ERROR: Unknown module(s) in QT: webkitwidgets

Some of these errors occurs with sudo, some - without.
I already tried to completely reinstall Qt, Qt Creator(using apt-get and online installer) and missing packages and I also removed dir QtProject and file QtProject.conf from /home/user/.config, but without success.
So how can I absolutely clean and purge Qt, its configs and settings and make pure reinstallation to solve these problems?

A: To answer #2, #4, and #5 - these all stem from file ownership being by the 'root' user, caused by when you launched Qt Creator as root.
To fix these issues:
$ chown user:user -R /home/user/.config/QtProject/qtcreator
$ chown user:user -R /home/user/QtProjects
$ rm -Rf /home/user/QtProjects/build-test_project-Desktop-Debug

The first two directives makes sure that all the Qt projects you have in QtProjects and all Qt Creator user settings files are owned by the user, so it can be accessed by the Qt Creator project when launched by the user.
The last directive removes your build files, which will be regenerated when you next build - in case they are in an inconsistent state due to the permissions being wrong.
As to #7 - as what Frank Osterfeld mentioned, you have enabled Qt Webkit support in your project, and it's been removed from Qt as of Qt 5.6*. I would recommend replacing your usage of Qt Webkit with Qt WebEngine.
* https://wiki.qt.io/New_Features_in_Qt_5.6#Removed_Modules


text:
Q: Contar quantas vezes um valor aparece em uma Coluna PHP e SQL Gostaria de que o código automaticamente contasse e mostrasse ao lado das opções do formulário, a quantidade de vezes que os valores que são puxados do banco de dados aparecem na TABELA clients COLUNA conta
obs: Os valores das opções são puxadas da TABELA accounts COLUNA usuario,
e queria que os valores puxados que estão nas opções fossem contados na TABELA clients COLUNA conta
queria deixar assim igual na imagem:
https://i.stack.imgur.com/xceBC.png
já esse último valor não está na cadastrado na tabela accounts coluna usuario então por isso ele não precisa aparecer nas opções e nem ser contado.
https://i.stack.imgur.com/hB6Jh.png
SELECT conta, COUNT(*)
FROM clients
GROUP BY conta

      <text class="bold">
        Conta *
        </text>

        <select name="conta" class="form-control" required>
                <option value="">Selecione a conta</option>
            <?php
                while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {
                {
                echo "<option value='".$row['usuario']."'>".$row['usuario']."</option>";
                }
}
?>
        </select>

e se possivel se contar e der 6 ou mais, desabilitar a opção (disabled).

A: Dê um alias a contagem:
SELECT conta, COUNT(0) total FROM clients GROUP BY conta

No while verifique se o total é maior que 5, e defina o disabled, e o resto é concatenar:
<?php
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {

    # verifica se é maior que 5 e seta disabled
    $disable = ($row['total'] > 5) ? 'disabled' : '';
    # gera linha
    echo '<option value="' . $row['conta'] . '" ' . $disable . '>' . $row['conta'] . '(' . $row['total']  . ')</option>';
}
?>


text:
Q: SQL Query to pull only Hard Bounces? I currently manually update a database by exporting bounced email addresses using the code below:
SELECT DISTINCT UPPER(EmailAddress) as EmailAddress, SubscriberKey
FROM _Subscribers
WHERE Status = 'held'
OR Status = 'bounced'

We want to change this so we only get hard bounces and can still email addresses with a soft bounce. The BounceCategory column appears to be attributed to another table - how do I update the code?
Apologies if something similar has been asked, I'm brand new to this and very lost.

A: You will need to join up to the _Bounce data view.
SELECT DISTINCT UPPER(s.EmailAddress) as EmailAddress,
s.SubscriberKey,
b.BounceCategory
FROM _Subscribers as s
INNER JOIN _Bounce as b
ON b.SubscriberKey = s.SubscriberKey
WHERE b.BounceCategory = 'Hard bounce'

To add in a column from an additional data extension you can just add another join in the query.
SELECT DISTINCT UPPER(s.EmailAddress) as EmailAddress,
s.SubscriberKey,
b.BounceCategory,
bh.PROMO_KEY
FROM _Subscribers as s
INNER JOIN _Bounce as b
ON b.SubscriberKey = s.SubscriberKey
INNER JOIN BounceHeld as bh
ON bh.SubscriberKey = s.SubscriberKey
WHERE b.BounceCategory = 'Hard bounce'


text:
Q: Looking to create column of "rank arrays" based on another column of Array(Float) type Here is my dataset:
score
[0.3, 0.5]
[0.1, 0.6, 0.7]

Desired Dataset:
score            rank
[0.3, 0.5]      [1, 2]
[0.1, 0.6, 0.7] [1, 2, 3]

This is my initial attempt:
df_upd = df.withColumn("rank", F.array([F.lit(i) for i in range(1, F.size("score") + 1)]))

I get this error:

TypeError: range() integer end argument expected, got Column.

I'm wondering if there are any concise ways to do this or will I have to explode df and then create a rank column using Window functions

A: It looks like you want just create a sequence from 1 to size(score), you can use sequence function for that:
from pyspark.sql import functions as F

df = spark.createDataFrame([([0.3, 0.5],), ([0.1, 0.6, 0.7],)], ["score"])

df.withColumn("rank", F.expr("sequence(1, size(score))")).show()

#+---------------+---------+
#|          score|     rank|
#+---------------+---------+
#|     [0.3, 0.5]|   [1, 2]|
#|[0.1, 0.6, 0.7]|[1, 2, 3]|
#+---------------+---------+


text:
Q: zend studio + xampp server file transfer i been using aptana and dreamweaver for some long time, but now i wanted to use zend studio, because of there latest release and it says it can help on debugging while coding on javascript/php.
Now the thing is, i keep my project in different location and testing project in different location, just for safety and some wired thing dont happen, which sometimes empty the code for no reason. anyway in other two application i can easily make remote connection and transfer the file using the arrow button or by keyboard CTRL+ALT+U . it will upload and i can just refresh the browser to check it. on zend, i dont see any remote connections and i did change the server connection, but im not sure how i can easily transfer files, like i do in other IDE. can anyone help me on this for creating a remote connection and setting up the keywords, so i can continue to do what i use to do.

A: i found File Synchronization plugin for eclipse, that worked out pretty well too, its just it will auto upload, rather then i will press ctrl+alt+u, which i like more better then auto. oh well, something better then nothing.


text:
Q: Why can I declare the datatype of a variable twice? In the code below:
public class Square
{
    private double side;

    public Square(double a)
    {
        double side = a;
    }

    public double area()
    {
        return side * side;
    }

    public static void main(String[] args)
    {
        Square r = new Square(10.0);
        System.out.println(r.area());
    }
}

When the field is declared:
 private double side;

and then in the constructor:
double side = a;

Why is an error not thrown?
I would think so because we are declaring the datatype of the variable double twice. Why does this code execute?

A: Because the second one declares a variable local to the constructor. It overshadows the member variable (which you can still access there via this.side).
In that context, that declaration is perfectly useless, as that variable will disappear as soon as the constructor ends.
Also, even if it was a problem, it wouldn't throw a runtime error. It would be a compile-time error.

A: Declaring a variable involves declaring its data type as well, so you are essentially asking about declaring the same variable twice.
You are right in assuming that declaring the same variable twice is not possible, but that's not happening in your code. Your
private double side;

is a data member of Square object, that is, a property of squares. It is declared in the block of the class definition, hence it's a data member.
Your
double side = a;

is a local variable defined in a method, which is the constructor in our case. It's legal syntactically, since it's not a member of Square and hence it has nothing to do with the member. Now, having said that I must mention that you have made a mistake, since inside the constructor you have declared a variable with the same name as your data member, initialized your local variable and then you never use it, while in another method you assume that side is initialized. So you have almost certainly intended to initialize your data member in your constructor, like:
public Square(double a)
{
    this.side = a;
}

or even
public Square(double a)
{
    side = a;
}


text:
Q: update text on a WPF page with delays I new to WPF, and have to put a basic application together
It consists of one main window with a frame, and one page
the page has a basic status text -
the requirement is that when the page loads up, the application has to do a bunch of REST call to fetch some data from remote source, and update the status text as it fetches
problem is, as I update the text, it doesn't seem to be reflected on the page, or maybe it's being blocked - even though I've used Task
so far, I have the following code for testing:
 private void Page_Loaded(object sender, RoutedEventArgs e) {
        var wnd = Window.GetWindow(this);
        wnd.ContentRendered += Wnd_ContentRendered;
    }

    private void Wnd_ContentRendered(object sender, EventArgs e) {
        DisplayMessages();
    }

    private void DisplayMessages() {
        authenticationText.Text = "text one";
        var t = Task.Delay(5000);
        t.Wait();
        authenticationText.Text = "text two";
        t = Task.Delay(5000);
        t.Wait();
        authenticationText.Text = "text three";
        t = Task.Delay(5000);
        t.Wait();
    }

even though I'm waiting after each task, the UI doesn't get updated - rather it just displays text three directly after method is finished - suggestions ?
P.S: there's also a WPF loader on that page, I've noticed that it doesn't get animated as well - it seems the delay is working but everything on the UI isn't updated

A: I would suggest for getting the data from REST implementation , you should use the background worker and on the basis of completion of thread or progress changed you need to update the UI thread accordingly.
for getting the better insights on background worker.. kindly use this link
How to use WPF Background Worker
In your case you can use progresschanged event of the backgroundworker..
Please Create some property lets say StatusText with InotifyPropertyChanged Interface implemented  and bind (use TwoWay Binding) it with the Text property of the  authenticationText control .... and in the progress changed event of the backgroundworker set the value of the StatusText  property,., which will automatically updates the UI.

A: You could try to invoke these results on the UI Thread...
Run your task normally with Task.Run or whatever. Each time you are ready to set some property on UI Thread you should invoke it through the dispatcher..
    Task.Run(() =>
    {
        var _Temp = getSomePropTask();
        Thread.Sleep(1000);
        App.Current.Dispatcher.Invoke(()=>{
            authenticationText.Text = _Temp;
        });
    });

A: Thanks to suggestion by Ashok, I did some background reading and have come up with the following solution using Task, async and await - which is simpler to manage than background worker threads:
private void Page_Loaded(object sender, RoutedEventArgs e) {
    var wnd = Window.GetWindow(this);
    wnd.ContentRendered += Wnd_ContentRendered;
}

private void Wnd_ContentRendered(object sender, EventArgs e) {
    GetDataAsync();
}

 private async void GetDataAsync() {
        authenticationText.Text = "Connecting...";
        await Task.Delay(5000);
        authenticationText.Text = "Getting Member Details...";
        List<MemberServiceModel> memberList = await GetMembersAsync();

        // more code for handling response
}

private List<MemberServiceModel> GetMembers() {
            //get all members synchronous
            var request = new RestRequest("Members/Admin", Method.GET);
            var response = _client.Execute<List<MemberServiceModel>>(request);
            if (response.ResponseStatus != ResponseStatus.Completed) {
                //TODO
                _restErrorStatus = response.ResponseStatus.ToString();
                _restErrorMessage = response.StatusDescription;
                _logger.Error("Error in GetMembers");
                _logger.Error("Status:" + _restErrorStatus);
                _logger.Error("Description:" + _restErrorMessage);
            }
            return response.Data; ;
        }

        private Task<List<MemberServiceModel>> GetMembersAsync() {
            //get all members asynchronous
            return Task.Run(new Func<List<MemberServiceModel>>(GetMembers));
        }


text:
Q: Rails 4 not using form method PATCH, defaulting to POST I have the following line which generates a form tag;
<%= form_for :stream, url: stream_path(@stream), method: :patch do |f| %>

It generates the following;
<form method="post" action="/streams/52b02d267e3be39d3da5aa609f1049d7" accept-charset="UTF-8">

If I change it to :put it still has it has post but if I write method: :get it will change it to get
Does anyone have any idea why it would be doing this and what I can do to prevent it?
Here is the output from rake routes;
    Prefix Verb   URI Pattern                 Controller#Action
    streams GET   /streams(.:format)          streams#index
           POST   /streams(.:format)          streams#create
 new_stream GET   /streams/new(.:format)      streams#new
edit_stream GET   /streams/:id/edit(.:format) streams#edit
     stream GET   /streams/:id(.:format)      streams#show
          PATCH   /streams/:id(.:format)      streams#update
            PUT   /streams/:id(.:format)      streams#update
         DELETE   /streams/:id(.:format)      streams#destroy

The background is this is a simple edit form, all I want it to do is his the update method of the controller.
Follow up
In my layout file I am bringing in csrf_meta_tags and my javascript_include_tag links to a file called "stream" which has the following
//= require jquery
//= require jquery_ujs

A: method: (:get|:post|:patch|:put|:delete)

from the documentation:

"in the options hash. If the verb is not GET or POST, which are natively supported by HTML forms, the form will be set to POST and a hidden input called _method will carry the intended verb for the server to interpret."

source: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

A: is //= require jquery_ujs in your application.js?
also make sure
<%= javascript_include_tag "application"%>
<%= csrf_meta_tag %>

are present in your layout file.


text:
Q: Can't connect to mysql using localhost I'm using Mac and latest MySQL. Recently I've updated OS to El Capitan and now realised that 'localhost' as a name does not work anymore, but only 127.0.0.1.
Is there some settings where I can define for mysql that localhost is actually 127.0.0.1?
Here is the message in Drupal (it's because I'm using localhost).

This settings in Drupal are using in order to connect to mysql database.
If I use localhost it does not work, if I use there 127.0.0.1 - it works well.

A: I followed option #1 under "THREE options to fix MySQL 5.6" and my errors went away - Mysql 5.6 headaches on Mac OSX.

A: I've updated localhost to 127.0.0.1 and it started to work.


text:
Q: Magento 2 Can I disable Magento_Tax module? Tax is useless for my shop. Can I disable/remove the Magento_Tax module? If yes, how can I disable/remove it? Thanks.

A: You can disable in admin:
Store --> Configuration --> Advanced --> Magento_Tax: Disable


text:
Q: "State information lost" in SimpleSamlphp I got an error State information lost "State information lost" in SimpleSamlphp.
Use sprint-security as SP, and configure the Idp on Simplesamlphp.
Then,it's ok by browser to redirect the SP webpage to Idp, but after login the username and password, I got an error,
"State information lost".
```
Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] array (
  'id' => 'a3a41e7aia439d7371j5e742e35jhi',
  'url' => NULL,
)
Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] Ron====sid===end
Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] NULL
Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] Ron====url===end
Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] Ron====state:NULL
Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] SimpleSAML_Error_NoState: NOSTATE
Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] Backtrace:
Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] 2 /var/simplesamlphp/lib/SimpleSAML/Auth/State.php:274 (SimpleSAML_Auth_State::loadState)
Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] 1 /var/simplesamlphp/modules/saml/www/sp/saml2-acs.php:91 (require)
Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] 0 /var/simplesamlphp/www/module.php:137 (N/A)
Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] Error report with id f9c150bb generated.

```
I found the  stateID was from  which sent by SP. And then in Idp side, now the logs shows the sessions contains two valid cookies for a phpsession, and an authtoken. But both of these Ids could not match with the "RequestId", or "InResponseTo" in the response.
I'm just stuck here. How does it happen? Anyone can help? Thanks in advance.

A: I found the the logic of the php was following with the SP php scripts in my case, and more obviously was that when I changed the "stateId" manually, I got an error like this:
 SimpleSAML_Error_Exception: This SP [https://domainname/simplesaml/module.php/saml/sp/metadata.php/default-sp]  is not a valid audience for the assertion. Candidates were: [com:vdenotaris:spring:sp]
which it's very strange and out of my expectation. Then I checked the file
"metadata/saml20-sp-remote.php" that SimpleSAMLphp Documentation says it's for adding the SP metadata into Idp configuration to let it know.
Finally, I found that I populated in the wrong SP metadata here.
It goes wrong if it like this:
$metadata['com:vdenotaris:spring:sp'] = array(
        'AssertionConsumerService' => 'https://domainname/simplesaml/module.php/saml/sp/saml2-acs.php/default-sp',
        'SingleLogoutService' => 'https://domainname/simplesaml/module.php/saml/sp/saml2-logout.php/default-sp',
);

The AssertionConsumerService and SingleLogoutService should be assigned the URLs in your SP,since they're the services on the SP.
So it should be like this:
$metadata['com:vdenotaris:spring:sp'] = array(
        'AssertionConsumerService' => 'https://SPonRonSever:8443/prj/saml/SSO',
        'SingleLogoutService' => 'https://SPonRonSever:8443/prj/saml/SingleLogout',
);

Then when you type  "https://SPonRonSever:8443/prj" in the address bar of the browser, it could jump to the login page provided by Idp, after authentication, you could access the web page you wanted.


text:
Q: Android Recognize voice of 2 people differently I want to develop an android app.
One feature of the app is recognize 2 people's voice.
It will be kike this - when the app will open, 2 people will talk in front of it.
App will detect 2 persons speaking and will calculate how much % (let 2 persons are A and B) person A spoke and same for person B.
So, say, after 1 minute the app will tell A talks 80% and B talks 20%.
So, what I need is how to differentiate 2 people's voice.
I have tried SpeechRecognizer and android.speech.tts . But I can't make it working.
Is it possible in android to differentiate 2 people's voice?
Thanks in advance for helping.

A: SpeechRecognizer or TTS will not help you as they have designed to recognize speech. You have to use DSP technology, in order to recognize the speaker. Due to the complexity, i don't think you can achieve this within the device itself. You can save your audio (using something like AudioRecord in Android) and then send it to a server. in the server side you can run a speaker recognition program. ALIZE is a quite popular open source tool for this.


text:
Q: Grouping a sorted table into 5% segments for counts, sums, avgs I'm looking at a table of customers for an ecommerce website and trying to group the customers by revenue into 5% segments and run a few COUNTs, SUMs, and AVGs across each segment.
I've started by ORDER-ing the table by revenue and adding a ROW_NUMBER() function, but I'm struggling with how to turn that into a "percentile" column I can GROUP the rows with.
It would have to be something where you divide the ROW_NUMBER() by the COUNT of customers, but that's what I need help with.
The basic customers table looks something like this:
customer_id  | num_orders | revenue
-------------------------------------
      1      |     1      |   50.0
      2      |     3      |   60.0
      3      |     7      |   80.0
      4      |     2      |   90.0
      5      |     9      |   110.0
      6      |     1      |   160.0
      7      |     2      |   80.0
      8      |     1      |   10.0
      9      |     3      |   120.0
      10     |     2      |   120.0
...
      515    |     2      |   70.0
      516    |     3      |   30.0
      517    |     6      |   20.0
      518    |     1      |   10.0
      519    |     8      |   120.0

And I'm looking for something like this:
  percentile   | num_customers | num_single_orders | avg_revenue
-----------------------------------------------------------------
      5%       |       26      |          1        |   2050.0
      10%      |       26      |          2        |   260.0
      15%      |       26      |          4        |   180.0
      20%      |       26      |          5        |   90.0
      25%      |       26      |          9        |   70.0
      30%      |       26      |          11       |   60.0
      35%      |       26      |          15       |   50.0
      40%      |       26      |          16       |   40.0
      45%      |       26      |          17       |   35.0
      50%      |       26      |          18       |   30.0
...
      100%     |       26      |          25       |   1.0

My code would look something like this:
SELECT
COUNT(customer_id),
SUM(CASE WHEN num_orders = 1 THEN 1 ELSE 0 END) num_single_orders,
AVG(revenue),
ROUND(row/COUNT(customer_id),0) percentile

FROM (
  SELECT
  customer_id,
  num_orders,
  revenue,
  ROW_NUMBER() OVER (ORDER BY revenue DESC) AS row

  FROM customers
)
GROUP BY percentile

But I don't know how to divide "row" by a COUNT without GROUPing by row, because that doesn't work either. I'm sure there's a simple solution I haven't figured out yet.
Thank you for anyone that can help!

A: You can use ntile(), but your method also works.  Put count() in the subquery:
SELECT FLOOR(seqnum * 100 / cnt) as tile,
       COUNT(customer_id),
       COUNTIF( num_orders = 1 )   as num_single_orders,
       AVG(revenue),
ROUND(row/COUNT(customer_id),0) percentile

FROM (SELECT c.*,
             ROW_NUMBER() OVER (ORDER BY revenue DESC) - 1 AS seqnum,
             COUNT(*) OVER () as cnt
      FROM customers c
     ) c
GROUP BY tile
ORDER BY tile;

This produces 100 groups.  If you want 20, then use 20 instead of 100.
Note that the groups will be as close in size as possible, so tied values can be in different tiles.  If you want to keep such values together, use rank() instead of row_number().

A: Below is for BigQuery Standard SQL
Assuming you want 20 segments ... (otherwise you should change 20 to whatever you want in two places below)
#standardSQL
SELECT (100 * segment / 20) AS percentile, *
FROM (
  SELECT
    CEIL(row_num * 20 / cnt) AS segment,
    COUNT(customer_id) num_customers,
    COUNTIF(num_orders = 1) AS num_single_orders,
    ROUND(AVG(revenue), 2) avg_revenue
  FROM (
    SELECT
      customer_id,
      num_orders,
      revenue,
      ROW_NUMBER() OVER(ORDER BY revenue DESC) AS row_num,
      COUNT(*) OVER() AS cnt
    FROM `project.dataset.customers`
  )
  GROUP BY segment
)
-- ORDER BY segment

output will looks like
Row percentile  segment num_customers   num_single_orders   avg_revenue
1   5.0         1.0     1               1                   160.0
2   10.0        2.0     2               0                   120.0
3   15.0        3.0     2               0                   120.0
4   20.0        4.0     1               0                   120.0
. . .
18  90.0        18.0    2               1                   55.0
19  95.0        19.0    2               0                   25.0
20  100.0       20.0    2               2                   10.0


text:
Q: What do I get for holding gyms? So far, gyms in my area flip so frequently that I haven't been able to hold more than one gym at a time when collecting my rewards. I know the reward for a single gym is 500 stardust and 10 coins.
Does this reward scale linearly with multiple gyms, or does it follow a different progression? I've also heard there might be some kind of bonus for holding a gym for more than a day, but haven't managed to do it. Is there a bonus for that (or any other kinds of bonuses)?

A: I'm currently king of a level 10 gym, and have been for roughly 27 hours, I got no bonus other than the usual 10 coins and 500 stardust. So holding a gym for 24 hours just makes you feel special, and that's about it.

A: The reward scales linearly it's 500 dust and 10 coins per gym up to 5000 dust and 100 coins per defender bonus collection. You can collect your defender bonus if you haven't collected for at least 21 hours prior.
I have held gyms for multiple days and haven't seen any sort of bonus when collecting the defender bonus. Perhaps there is an xp bonus or something but I have never seen it in the journal so I doubt it exists.

A: Apparently you have to go into the "Shop" and click on the shield in the top right corner. You can then collect a defender bonus every 21 hours from that point.
I have no Pokemon at gyms rt now so I haven't been able to test that

A: I have held for gyms for the day and there is a shield that you can collect stuff from in the shop. I got 2000 dust and 40 coins


text:
Q: Global redirect back to front page if claim is empty or does not exist (NOT identity verification) Just to be clear: I am NOT talking about claims-based identity validation.
I am building an app in which I make fine use of Identity 2.2 to provide validation. It is sufficient for my needs.
My problem is that once a user logs in, only the first page is widely accessible without storing additional information in the user's "session". In particular, when the user clicks on a major internal item (for sake of convenience, let's call this a "customer module", the Guid for that customer is stored in a claim held by the user. That way, the user can move from page to page and still have that same customer's data brought up on every page regardless of what chunk of data the page was meant to display. This claim is only refreshed with something different when they return to the main page and click on another customer.
For security's sake I would like to ensure that if a claim gets accidentally dropped or set to empty, the user gets shunted back to the main page regardless of where they are in the system, and preferably without having to put code in each and every page action of every controller.
Suggestions? Or am I completely wrong by making use of claims? Because it's still early enough in the project to make a u-turn if the advantages of a different method are compelling enough.
EDIT:
Just to let people know my solution: Because only one group of people will be accessing this application (the users that interact with companies, this app is to record the interactions and "company information"), I decided to use a base controller. The users would be able to log on and view lists of companies without coming across any page that derived from BaseController, but once they chose a Company to work with, they needed to have Claims set to be able to maintain page-by-page contact with this company's information. This information would be reset only when they chose a different company, but since there was always a chance that a claim could be disabled, I needed something to automagically redirect them back to the list of companies to re-set the claims. A BaseController that was employed by only those pages where information specific to one company would be displayed was the perfect solution.
A base controller is simple. Just create a controller called BaseController and you're off to the races. Change any controller that needs to work with this base controller such that they are public class YourOtherController : BaseController.
I initially tried to make an Initialize method to handle everything, but ran into a rather big problem: I was unable to successfully both access and write to my Claims. As in, I was able to either read my claims but not make use of my ClaimWriter extension, or I was able to make use of my ClaimWriter extension but be unable to read claims in the first place. Since Initialize is wayyyy too low in the stack to actually do both these things, I abandoned it and went for an OnActionExecuted method, which ended up being successful. My code ended up being this:
public class BaseController : Controller {
  private ApplicationDbContext db = new ApplicationDbContext();
  protected override void OnActionExecuted(ActionExecutedContext filterContext) {
    base.OnActionExecuted(filterContext);
    var principal = ClaimsPrincipal.Current.Identities.First();
    var company = User.GetClaimValue("CWD-Company");
    var prospect = User.GetClaimValue("CWD-Prospect");
    if(string.IsNullOrEmpty(company)) {
      filterContext.HttpContext.Response.Clear();
      filterContext.HttpContext.Response.Redirect("/");
      filterContext.HttpContext.Response.End();
    }
    if(!string.IsNullOrEmpty(company) && string.IsNullOrEmpty(prospect)) {
      var id = new Guid(company);
      var prospecting = db.Prospecting
        .Where(x => x.CompanyId.Equals(id))
        .Select(x => x.ProspectingId)
        .ToList().SingleOrDefault();
      if(prospecting.Equals(Guid.Empty)) { // null prospecting
        User.AddUpdateClaim("CWD-Prospecting", "");
      } else { // fill prospecting
        User.AddUpdateClaim("CWD-Prospecting", Convert.ToString(prospecting));
      }
    }
  }
}

I am probably going to change the if(prospecting.Equals(Guid.Empty) part of the Prospecting section to automagically create the first entry in the db (with all null values except for the ProspectingId and the CompanyId, of course), but this is what works for now.

A: That's a fine use of claims you describe, no need a u-turn. What you need is a MVC filter, authorisation filter. Something like this:
public class MyAuthorisationFilter : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var principal = HttpContext.Current.User as ClaimsPrincipal;

        if(!principal.Claims.Any(c => c.Type == "My Claim Name"))
        {
            // user has no claim - do redirection
            // you need to create 'AuthenticateAgain' route to your table of routes
            // or you can do other means of redirection
            filterContext.Result = new RedirectToRouteResult("AuthenticateAgain", new RouteValueDictionary());
        }
    }
}

Then you can add it globally in your filters configuration, but you'll have to exclude your authorisation page from this filter. Or apply on per controller basis - whenever this needs to happen.
This is very basic form of filter - a lot of checks are stripped out, but it gives a general direction how to proceed.
Update

*

*This is a good article about Authorise attribute.

*Here use of AllowAnonymous attribute is explained

The way you use it - depends on your scenario. In most cases when you only expose a login page to the world - it is sufficient to add this attribute as a global filter (see second link, part about RegisterGlobalFilters) and then sprinkle [AllowAnonymous] on top of controllers/actions which should be exposed without authentication.
Another approach is to have a base controller that has your attribute applied. And then all your controllers inherit from this base controller. This is more sufficient when global filter does not cut it: cases when you expose different pages to different users - think companies and customers. Your controllers for companies will inherit CompaniesBaseController that has [CompaniesAuthFilter] and customers will be inheriting from CustomersBaseController with [CustomersAuthFilter].


text:
Q: Angular UI date picker error message in same line In this plunk I have an Angular UI date picker with an error message that is displayed when the date is invalid. Problem is that the error message is shown below the date instead of the same line. How to fix this?
HTML
  <form name="form1" ng-submit="validate(form1)" novalidate>

          <input type="text" class="form-control" ng-model="dtFrom"
               is-open="config1.opened"  uib-datepicker-popup="MM-dd-yyyy"
               close-text="Close" name="dtFrom" />

               <button type="button" class="btn btn-default" ng-click="open1($event)">

               </button>

Invalid Date

  </form>

Javascript
var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap']);

app.controller('ctl', function ($scope) {

    $scope.dtFrom = new Date ();

    $scope.config1 = {};
    $scope.config1.opened = false;
    $scope.open1 = function(event){
         event.preventDefault();
         event.stopPropagation();
         $scope.config1.opened = true;
    };

});

A: You can add class list-inline in it.
Here is plnkr
http://plnkr.co/edit/23CxCMDRK6DBiW115K7T?p=preview

A: The reason you are seeing this misalignment is because you are using bootstrap classes but are not correctly applying them to all the corresponding elements. When you use an input-group as you've applied to the
 element, you are using a specific bootstrap class that adds styling to the components, like display:table. To have a correct behavior for the whole form, you need to keep using these classes on sibling elements. Namely input-group and form-control. Using these you will notice that its better aligned to its neighbor in both position and height. Additionally its best to wrap all these components in a valid row and column classes for parent elements. I've added an updated version of your plnkr showing how these changes behave:
plnkr


text:
Q: Duplicity error while restoring i'm trying to restore one folder by duplicity backup, but i always get this traceback error
i googled that all the morning but i solve it :(
i use this command duplicity -v9 --no-encryption --force --file-to-restore Operadora/Irene file:///mnt/nas irene because i want to restore the realiteve Irene folder
  Traceback (most recent call last):
  File "/usr/bin/duplicity", line 1548, in <module>
    with_tempdir(main)
  File "/usr/bin/duplicity", line 1534, in with_tempdir
    fn()
  File "/usr/bin/duplicity", line 1383, in main
    do_backup(action)
  File "/usr/bin/duplicity", line 1462, in do_backup
    restore(col_stats)
  File "/usr/bin/duplicity", line 729, in restore
    restore_get_patched_rop_iter(col_stats)):
  File "/usr/lib/python2.7/dist-packages/duplicity/patchdir.py", line 558, in Write_ROPaths
    for ropath in rop_iter:
  File "/usr/lib/python2.7/dist-packages/duplicity/patchdir.py", line 521, in integrate_patch_iters
    for patch_seq in collated:
  File "/usr/lib/python2.7/dist-packages/duplicity/patchdir.py", line 389, in yield_tuples
    setrorps(overflow, elems)
  File "/usr/lib/python2.7/dist-packages/duplicity/patchdir.py", line 378, in setrorps
    elems[i] = iter_list[i].next()
  File "/usr/lib/python2.7/dist-packages/duplicity/patchdir.py", line 107, in filter_path_iter
    for path in path_iter:
  File "/usr/lib/python2.7/dist-packages/duplicity/patchdir.py", line 121, in difftar2path_iter
    tarinfo_list = [tar_iter.next()]
  File "/usr/lib/python2.7/dist-packages/duplicity/patchdir.py", line 339, in next
    self.set_tarfile()
  File "/usr/lib/python2.7/dist-packages/duplicity/patchdir.py", line 333, in set_tarfile
    self.current_fp = self.fileobj_iter.next()
  File "/usr/bin/duplicity", line 765, in get_fileobj_iter
    backup_set.volume_name_dict[vol_num],
KeyError: 19

A: This could be caused by a cache corruption. We should file a bug with duplicity to clean up the error message, but in the meantime, clear the cache:
rm -r ~/.cache/duplicity


text:
Q: Multiple a nested list cloumn by a value and then adding across the nested list column by a grouping variable I have a large tibble with one nested list column. Each element of the nested list column has 10,000 iterations and i would like to apply a function to these elements and then sum across the elements by group.
I have created a minimal reproducible example below
tibble(a = list(c(1,2),c(3,4), c(5,6), c(7,8)),
   b = c(2,3, 4, 2),
   c = c(1,1, 2, 2))

I would first like to multiple each element in x$a with x$b. This should give me
tibble(a = list(c(2,4), c(9,12), c(20,24), c(14,16)),
   b = c(2,3, 4, 2),
   c = c(1,1,2,2))

Finally, i would like to group by x$c and then add across the values of the element of that group. This should give the following output
tibble(a = list(c(11,16), c(34,40)),
   c = c(1,2))

As you can see the first element of x$a is the sum of iterations where x$C==1 i.e. the sum of vector c(2,4) and c(9,12) giving c(11,14)
I think the purrr::map function can do this but struggling with the syntax here
Any help greatly appreciated

A: We could convert to 'long' format by unnesting the column 'a', do the multiplication and then summarise to get the sum
library(dplyr)
library(tidyr)
library(data.table)
dat2 <- dat %>%
          mutate(rn = row_number()) %>%
          unnest(c(a)) %>%
          group_by(rn) %>%
          mutate(a1 = c(first(a) * first(b), last(a) * last(b))) %>%
          group_by(c, grp = rowid(rn)) %>%
          summarise(a = sum(a1))  %>%
          group_by(c) %>%
          summarise(a = list(a))
# A tibble: 2 x 2
#      c a
#   <dbl> <list>
#1     1 <dbl [2]>
#2     2 <dbl [2]>

Or another option is to convert to wide format columns and then do the multiplication
dat %>%
    unnest_wider(c(a)) %>%
    group_by(c)  %>%
    summarise_at(vars(starts_with('..')), ~ sum(. * b))

Or in the devel version of dplyr
dat2 <- dat %>%
          unnest_wider(c(a)) %>%
          group_by(c)  %>%
          condense(a = across(starts_with('..'), ~ sum(. * b),
              names = "a{col}") %>% unlist(use.names = FALSE))

dat2
# A tibble: 2 x 2
# Rowwise:  c
#      c a
#  <dbl> <list>
#1     1 <dbl [2]>
#2     2 <dbl [2]>

dat2$a
#[[1]]
#[1] 11 16

#[[2]]
#[1] 34 40

In base R we can do
stack(lapply(split(Map(`*`, dat$a, dat$b), dat$c),
       function(x) do.call(`+`, x)))
#  values ind
#1     11   1
#2     16   1
#3     34   2
#4     40   2

A: One option involving dplyr and purrr could be:
df %>%
 mutate(a = map2(.x = a,
                 .y = b,
                 ~ .x * .y)) %>%
 group_by(c) %>%
 summarise(a = list(reduce(a, `+`)))

      c a
  <dbl> <list>
1     1 <dbl [2]>
2     2 <dbl [2]>

A: And another option, using tidyverse:
library(tidyverse)

df <- tibble(a = list(c(1,2),c(3,4), c(5,6), c(7,8)),
       b = c(2,3, 4, 2),
       c = c(1,1, 2, 2)) %>%
      unnest() %>%
      mutate(a = a*b) %>%
      group_by(c) %>%
      mutate(a = c(rep(nth(a,1) + nth(a,3), 2), rep(nth(a,2) + nth(a,4),2))) %>%
      unique() %>%
      summarize(a = list(a))

>       df
# A tibble: 2 x 2
      c a
  <dbl> <list>
1     1 <dbl [2]>
2     2 <dbl [2]>


text:
Q: Does page-fault occur when Operating System reads a file for the first time? Hello OS experts from Stackoverflow.
I have been struggling to find out whether the page-fault occurs when the OS reads a file for the first time in Intel architecture x86.
I am curious about how the Operating system will handle after the userspace application calls the read syscall after the open syscall.
For my understanding...

*

*After the read system call, the kernel accesses an invalid page of the page table that is not currently mapped by the memory management unit and raises the page-fault.

*The page fault will call for demand paging. The Kernel looks up the disk address of the desired page and schedules disk operation (I/O scheduling).
However, I received a tip from my advisor that the page-fault does not occur when the file is opened and read for the first time.
Is this true? I've been searching all over to find a clear answer to this without any success. Would it be possible to explain whether the page-fault happens or not at the first file read?

A: It depends upon how the file is being read. If the file is being read as a memory mapped file, it is close to a certainty that a page fault will occur.
If being read through a buffer, its is likely the system will require the buffer to be locked in memory. However, there could be a page file when transferring the data to a user buffer.


text:
Q: Have HTTP/2 push in Wordpress I search to have my images pushed via HTTP/2 on my Wordpress websites, one is Linorhiati.ch for exemple I am about to finish.
The hoster, I have a cloud subscription at TMDHosting, offers HTTP/2 and also Cloudflare I am using.
I read this article from them about this topic: https://blog.cloudflare.com/using-http-2-server-push-with-php/
So I wonder how to implement these codes in Wordpress in order to have such Link headers in the HTTP response.


text:
Q: struggling with class, extends and implements I'm really struggling with classes, extend and implement.
Well at android I want to create a preference screen and check the user input.
I can use therefore a file named preferences.class and do everything I need with the following class:
        public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {

        @Override
protected void onCreate(Bundle savedInstanceState) {
}

      @Override
      public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
    }
}

But isn't it better to split this up in different classes? and if yes how?

A: You can have a PreferenceChangeListener which implements OnSharedPreferenceChangeListener and your Preference class will have a PrefernceChangeListener
public class Preference extends PreferenceActivity {

   private PrefernceChangeListener prefernceChangeListener;

   public void addPreferenceChangeListener(PrefernceChangeListener prefernceChangeListener){
     this.prefernceChangeListener = prefernceChangeListener;
   }

   public PrefernceChangeListener getPrefernceChangeListener(){
     return this.prefernceChangeListener;
   }
}

On a general note if your class has a property which can be externalized you should try to use HAS A relationship, you will use IS A relationship when your class provides functionality on top of inherited values.
Most of the cases IS A can be avoided, unless your class doesnt has a meaning without inheritance favor HAS A over IS A relationship.
Prefer composition over inheritance


text:
Q: How to combine a computed type with additional properties in TypeScript? I'm trying to create typing for an object that has a structure like this:
{
  "1bcc10d3-425e-4a91-9a90-d7f2969986f9": {
    result: {
      key: "value"
    }
  },
  another_key: ["test", "12345"]
}

In the example above, "1bcc10d3-425e-4a91-9a90-d7f2969986f9" is an arbitrary UUID that is being used as a key. My object can have one or more such records, indexed by a UUID, and it also has a few other keys of various types.
I have tried a few different representations, none of which have worked. The most obvious would be something like this:
interface MyResultType {
  [uuid: string]: {
    result: {
      key: string;
    }
  };
  another_key: string[];
}

That doesn't work however, as I get the following error:
Property 'another_key' of type 'string[]' is not assignable to 'string' index type '{ result: { key: string; }; }'.ts(2411)

My understanding is that the problem here is that [uuid: string] matches any key of type string, so it's trying to assign another_key to the {result: {key: string;}} type.
So I tried using an intersection type:
type MyResultType = {
  [uuid: string]: {
    result: {
      key: string;
    };
  };
} & {
  another_key: string[];
};

This time, the declaration works fine, but it fails when I try to use it:
const result: MyResultType = {
  '1bcc10d3-425e-4a91-9a90-d7f2969986f9': {
    result: {
      key: 'value',
    },
  },
  another_key: ['test', '12345'],
};

Results in this error:
Type '{ '1bcc10d3-425e-4a91-9a90-d7f2969986f9': { result: { key: string; }; }; another_key: string[]; }' is not assignable to type 'MyResultType'.
  Type '{ '1bcc10d3-425e-4a91-9a90-d7f2969986f9': { result: { key: string; }; }; another_key: string[]; }' is not assignable to type '{ [uuid: string]: { result: any; }; }'.
    Property 'another_key' is incompatible with index signature.
      Property 'result' is missing in type 'string[]' but required in type '{ result: any; }'.ts(2322)

I tried rephrasing it like this:
type MyResultType = {
  [uuid: Omit<string, 'another_key'>]: {
    result: any;
  };
} & {
  another_key: string[];
};

But that still doesn't work:
An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type.ts(1268)

Is there any way to do what I'm trying to do?

A: Just define index type as an intersection of all possible value types
interface Field {
    value: unknown
    lastUpdateAt: number
}

interface User {
    [key: string]: Field | string[]
    extra: string[]
}

const person: User = {
    firstName: {
        value: 'Billy',
        lastUpdateAt: 6,
    },
    lastName: {
        value: 'Herrington',
        lastUpdateAt: 9,
    },
    extra: ['sex']
}

A: Based on feedback from answers to this other question, I tried the following:

interface Result {
  another_key: any[];
}
interface ExtendedResult {
  result: {
    key: string;
  };
}
export type PolicyCheckResult = {
  [y: string]: ExtendedResult;
} & Result;

type VerifyT<T> = {
  [K in keyof T]: K extends keyof Result ? Result[K] : ExtendedResult;
};
export const asPolicyCheckResult = <T extends VerifyT<T>>(t: T) => t;
asPolicyCheckResult({
  test: {
    result: {
      key: 'value'
    },
  },
  another_key: [],
});

That works, but unfortunately, it doesn't solve my problem, because in my case, the key we're indexing on is unknown, so I would have to write something like this, where test is a variable of type string:
asPolicyCheckResult({
  [test]: {
    result: {
      key: 'value'
    },
  },
  another_key: [],
});

And that fails again:
Argument of type '{ [x: string]: string | never[] | { result: { final_action: string; header: string[]; remediation: [{ suggestions: [{ message: string; preferred: true; }]; triggerIds: string[]; }]; row_count: number; rows: [(string | boolean)[], (string | boolean)[]]; }; }; policy_data: never[]; policy_name: string; whitelist_data:...' is not assignable to parameter of type 'VerifyT<{ [x: string]: string | never[] | { result: { final_action: string; header: string[]; remediation: { suggestions: { message: string; preferred: boolean; }[]; triggerIds: string[]; }[]; row_count: number; rows: (string | boolean)[][]; }; }; policy_data: never[]; policy_name: string; whitelist_data: never[]; w...'.
  'string' index signatures are incompatible.
    Type 'string | never[] | { result: { final_action: string; header: string[]; remediation: [{ suggestions: [{ message: string; preferred: true; }]; triggerIds: string[]; }]; row_count: number; rows: [(string | boolean)[], (string | boolean)[]]; }; }' is not assignable to type 'ExtendedResult'.
      Type 'string' is not assignable to type 'ExtendedResult'.ts(2345)

I realize that the real solution here would be to restructure the data to avoid mixing unknown types with known keys, but that's unfortunately not possible for me because I'm trying to add types to an existing API that is currently untyped and that I have no control over. So I need some way to provide information about the expected shape of what I get from the API...
So for now, my solution is to keep the types as above but making the additional properties (another_key) optional. I then use my literal without those extra properties, and add them back in using Object.assign. It's not pretty, but it's better than having no typing at all.


text:
Q: distribution of primes with reference to last digit Any prime greater than 5 shall have 1,3,7 or 9 as last digit. Are the primes  equally distributed among the above four last digits or any  bias for  any particular last digit say  up to 10 to the power  12 or higher. I have recently read an article in Scientific American that adjacent primes are unlikely to share the same last digit. Is it possible to predict the distribution among the last digits as we go higher?

A: For every integer $m\ge 2$ and for every positive integer $n<m$ coprime to $m$ the proportion of primes $p$ of the form $p\equiv n\ (\ mod\ m\ )$ is $\frac{1}{\phi(m)}$, in other words, in the long run, the primes are evenly distributed among the possible classes.
But there is a phenomen called Chebychev's bias, that the classes with a quadratic non-residue-remainder typically have more elements than those with a quadratic residue-remainder, even if many primes are considered.
I think, it is impossible to "predict" the "residue-sequence".