If funciona mas o Else não

Question: Então, o código abaixo (está completo no https://codepen.io/RaoniSousa/pen/Zpkxbb), o if funciona mas esse else não, o que está errado?
Gostaria que ele funcionasse como esse aqui, no input "NAME" rolando a barra (https://codepen.io/freeCodeCamp/pen/YqLyXB). Quando preencher o input o label aparece e sobe, quando limpar o input o label desce e depois some. To apanhando pro js ainda.
Agradeço a quem puder ajudar.
var z = document.getElementById('name');//input com ID name
var x = document.getElementById('label');//label com ID label

z.addEventListener("keypress", function () {

'use strict';
if (typeof z.value !== "") {
    x.style.opacity = '1';
    x.style.bottom = '4em';
    x.style.color = '#722872';
} else {
    x.style.opacity = '0';
    x.style.bottom = '1.5em';
}
seBlur();
seFocus();
});

Comment: O problema do primeiro link que enviaste é que no teu if: `if (typeof z.value !== "") {...`, retira o `typeof` é já fica tudo bem. E Tal como na resposta em baixo, keyup resulta melhor
Comment: mas o else é uma condição que só executa quando o if é falso...ou seja se o if é true ele executa as informações do bloco if, se não(else) ele executa o bloco do else
Comment: @MagicHat a não ser que ele tenha dito que nunca entra no `else` :P
Comment: @MarceloBoni só não vai entrar no else se if for true, caso contrário tem de entrar...
Comment: Então, pensei assim: se há caractere no input (if), x.style... caso contrário (se input vazio é o (else))...
Answer: mude keypress para keyup
e remova typeof
exemplo:

var z = document.getElementById('name');//input com ID name
var x = document.getElementById('label');//label com ID label

z.addEventListener("keyup", function () {

'use strict';
if (z.value !== "") {
    x.style.opacity = '1';
    x.style.bottom = '4em';
    x.style.color = '#722872';
} else {
     x.style.opacity = "0";
     x.style.bottom = '1.5em';
}
seBlur();
seFocus();
});

function seBlur() {
    'use strict';
    z.addEventListener("blur", function () {
        x.style.color = "#A2A2A2";
    });
}

function seFocus() {
    'use strict';
    z.addEventListener("focus", function () {
        x.style.color = "#722872";
    });
}
* {
    font-family: sans-serif;
    margin: 0 auto;
    box-shadow: border-box;
    position: relative;
}

body {
    left: 0;
    right: 0;
    margin: 0;
    background: #898989;
}

#container {
    width: 1030px;
}

a {
    text-decoration: none;
    outline: 0!important;
    border: 0!important
}

a:hover {
    text-decoration: none;
    outline: 0!important;
    border: 0!important
}

li {
    list-style: none
}

img {
    left: 0;
    width: 100%;
    height: auto
}

#menuFix {
    top: 0;
    position: fixed;
    display: flex!important;
    background: #722872;
    width: 100%;
    right: 0;
    height: 70px;
    line-height: 70px
}

#menuFix ul {
    margin: 0 auto;
    left: 0;
    right: 0;
}

#menuFix li {
}

#menuFix li a{
}

#menuFix li a{
    background-color: transparent;
    color: #7b776f;
    top: 1.8em;
    font-weight: 700;
    top: 10px
}

#menuFix a li:hover {
    text-decoration: none;
}

#menuFix li a span {
    padding: 12px 20px;
}

#menuFix img {
    width: 3%;
    height: 60%;
    top: 12px;
}

.navbar-nav>.active>a span,
 .navbar-nav>.active>a span:focus,
 .navbar-nav>.active>a span:hover{
    background-color: #f2f2f2!important;
}

#myDescript {
    margin-top: 0px;
    width: 100%;
    top: 0;
    padding: 140px 50px 50px;
    display: flex;
    background: #b5b5b5;
    color: #fff;
    font-size: 1.55em;
    text-align: center
}

#myDescript p {
    width: 660px;
}

#myDescript p:nth-of-type(2) {
    position: relative;
    width: 100%;

}

#myDescript img {
    width: 26%;
    top: -40px;
    height: 26%;
    border-radius: 150%
}

#myDescript hr {
    width: 60%;
    font-weight: 900;
}

#sec1 {
    padding: 10px 0 30px;
    text-align: center;
    background: #edecec
}

#sec1 img {
    width: 40%;
    height: auto;
    margin: 20px;
}

#sec1 h2 {
    color: #9b9b9b;
    font-weight: 700
}

#contact {
    border-top: 2px solid rgba( 132, 132, 132, 0.247 );
    padding: 10px;
    text-align: center;
    background: #edecec
}

#contact h2 {
    text-align: center;
    font-family: sans-serif;
    color: #7a7a7a;
}

.hr1 {
    margin: 40px 1.8% 30px 3.8%!important;
    padding: 0;
    left: 4.3em;
    width: 60%!important;
    border-bottom: 4px solid #fff!important;
    color: transparent!important;
    border-bottom: solid 5px #898989;
    text-align: center;
    white-space: nowrap;
}

.hr1::after {
    content: '\f121';
    font-family: FontAwesome;
    position: relative;
    color: #fff!important;
    top: -.7em;
    left: 67.2%;
    font-size: 2em;
    font-weight: 500;
    white-space: nowrap;
}

.div1 {
  display: flex
}

.hr {
    margin: 40px 3.8% 30px;
    padding: 0;
    float: left;
    left: 15.25em;
    max-width: 272px;
    width: 22%;
    border: 0;
    border-bottom: solid 5px #898989;
    text-align: center;
}

.hr-NotAfter::after {
    content: '\f121';
    font-family: FontAwesome;
    float: right;
    margin: -.7em -1.42em 0 0;
    color: #7a7a7a;
    font-size: 3em;
    font-weight: 500;
}

#contact {
    padding-bottom: 80px
}

form {
    width: 40%;
    margin-left: 60px;
}

form .row:first-child .form-item {
    border-top: 1px solid #fff;
}

.form-item {
    position: relative;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #bbb;
}

.form-item input,
.form-item textarea {
    z-index: 1;
    position: relative;
    padding-right: 0;
    padding-left: 0;
    border: 0;
    border-radius: 0;
    font-size: 2.2em;
    background: 0 0;
    box-shadow: none!important;
    resize: none;
    width: 100%;
}

.form-item input:focus,
.form-item textarea:focus {
    outline: 0
}

label {
    display: inline-block;
    z-index: 2;
    position: relative;
    bottom: 1em;
    margin: 0;
 padding: 0;
 left: -8.3975em;
 right: 0;
    font-size: 1.5em!important;
    line-height: 1.764705882em;
    font-weight: 700;
    vertical-align: baseline;
    color: #722872;
    opacity: 0;
    -webkit-transition: bottom .4s ease, opacity .7s ease;
    transition: bottom .4s ease, opacity .7s ease;
}

.form-item-filled label {
    top: -30px;
    opacity: 1;
    color: #aaa;
}

#contactFlex {
    display: flex;
    top: 50px
}

#contactFlex > div {
    width: 40%;
    font-size: 1.5em;
    color: #686868;
    text-align: left
}

form button {
    bottom: 20px;
    padding: 2px 8px;
    font-weight: 700;
    font-size: 1.3em;
    color: #7a7a7a
}

#contact > p {
    text-align: right;
    right: 7.5%;
    font-size: 1.4em;
    font-weight: 500;
    color: #7e7b7b
}

footer {
    width: 100%;
    height: 13em;
    background-color: #a8a8a8;
    text-align: center;
    font-size: 1.4em;
    font-weight: 700;
    color: #e0e0e0
}

#footFlex {
    width: 80%;
    display: flex;
}

#footFlex > div:not(p){
    margin-top: 6%!important
}

#footFlex ul {
    display: flex;
    margin-right: 40px;
    width: 100%;
}

#footFlex li {
    border: 2px solid #fff;
    border-radius: 50%;
    padding: 10px;
    margin: 2px;
    cursor: pointer;
    transition: all .5s;
}

#footFlex li:hover{
    background-color: #fff;
}

#footFlex li:hover i{
    color: #722872;
}

#footFlex li i:hover{
    background-color: transparent;
}

#footFlex li i{
    transition: all .5s;
    color: #fff
}

#footFlex div:first-child p:nth-child(2){
    width: 65%;
    left: 17.5%
}

#footFlex div p:nth-child(1){
    font-size: 1.3em
}

#footFlex div:first-child p:nth-child(2) a{
    color: #722872;
    font-weight: 400;
}

#footFlex div:first-child p:nth-child(2) a:hover {
    border-bottom: 2px solid #722872!important
}

#footFlex div:first-child p:first-child, #footFlex div:nth-child(2) p:first-child {
    margin-bottom: 1em
}

footer + div {
    height: 5.6em;
    background-color: #722872;
    font-size: 1.4em;
    font-weight: 700;
    color: #e0e0e0;
    line-height: 5.6em;
    text-align: center
}

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet prefetch" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="FreeCodeCamp.css">

<form id="contactForm" novalidate="">

        <input class="name" id="name" type="text"placeholder="Name"           required=""/>

        Name
</form>

If funciona mas o Else não


What is the meaning of a quantile regression model that predicts the conditional mean?

Question: What does that phrase "quantile regression model that predicts the conditional mean"  mean? How to interpret that?
I found it in Liu et al. (2020).
The authors have compared the results of linear regression, QRF conditional mean, QRF conditional median, QRF conditional first quantile, and QRF conditional third quantile. What confuses me is that for my little understanding, QRF predicting the conditional mean is exactly the same as Random forest, and the results for both should be identical, which is not the case in that paper! Note: the authors use R packages randomForest, and quantregForest.
Comment: This does not seem to make sense. The mean is not a quantile. (The *median* is, maybe it's a simple typo?) Where did you find this phrase?
Comment: @ahmedabdrahiem, the link does not work. It seems to be not just the access to the article. Also the main domain can not be retrieved. Could you update your question with more information about the context. The mean and the median are not the same thing (although they may have for some distributions the same value), so whatever the sentence means, a typo, an error, or maybe there is some logic behind it, must be seen from the context.
Comment: Welcome to Cross Validated! Count me as another voice for getting a reference. A conditional median makes sense, but mean makes less sense. // What do you understand about the idea of linear regression predicting the conditional mean?
Comment: @AhmedAbdalrahiem your post does not contain a lot of information that helps to interpret the phrase. The mean is not a quantile, so it is difficult to say what that phrase means.
Comment: @Stephan Kolassa and Dave
 I found this phrase in a paper that uses QRF. The authors have compared the results of linear regression, QRF conditional mean, QRF conditional median, QRF conditional first quantile, and QRF conditional third quantile.
What confuses me is that for my little understanding, QRF predicting the conditional mean is exactly the same as Random forest, and the results for both should be identical, which is not the case in that paper!
Note: the authors use R packages randomForest, and quantregForest.
Comment: Hm. Can you add a link to the paper?
Comment: It must be this PLoS One paper: [A quantile regression forest based method to predict drug response and assess prediction reliability](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6173405/). They "make a small change to the right side of formula for the median" to estimate the mean.
Comment: @Stephan Kolassa Here  is a link to that paper
https://asmedigitalcollection.asme.org/computingengineering/article-abstract/20/3/031003/1073961/A-Predictive-Analytics-Tool-to-Provide-Visibility?redirectedFrom=fulltext
Comment: @dipetkov
With their change to the right side formula, i believe this is the exact formula used in Random Forest model to predict the conditional mean E(Y|X=x)
Comment: Thanks. I took the liberty of adding the link into your question. I don't have access to the paper, unfortunately. You could quote the relevant section.
Comment: @Sextus Empiricus, i have already modified the post.
Answer: The article "A predictive analytics tool to provide visibility
into completion of work orders in supply chain
systems" that you refer to is not very clear about it.
At some point they actually say the following

As a generalization of Random Forest, Quantile Regression Forest predicts the conditional quantiles instead of the
conditional mean

So it is a bit odd that they speak about QRF predicting the conditional mean.
But indeed, in the results section of the article they suddenly introduce 'QRF conditional mean'. They only use this term in four places (only in the results) and do not explain it.

A wild guess might be that it relates to how they perform the bagging in the random forests algorithm.
They explain how they obtain several regression tree estimates $\hat{y}_m$ and as a final result use the average of $M$ trees
$$\hat{y}(\mathbf{x}^\prime) = \frac{1}{M} \sum_{m=1}^M \hat{y}_m(\mathbf{x}^\prime)$$
Then they explain quantile regression forest as using a different cost function (the absolute error). But in addition it seems that they also use a different bagging method with an additional equation. If we fill in their equation 6 into equation 3, then we get
$$Q_\alpha(\mathbf{x}) = \text{inf}\left\{ y: \frac{1}{M} \sum_{m=1}^M \mathbf{1}_{\hat{y}_m(\mathbf{x}^\prime)\leq y} \geq \alpha \right\}  $$
It could be that their 'QRF conditional mean', 'QRF conditional median', 'QRF conditional 1st quantile' and 'QRF conditional 3rd quantile', relate to the different bagging methods.
So it could be that this 'quantile regression model that predicts the conditional mean' relates to something like median of means or mean of medians.


Issue with date in oracle

Question: I am trying to pull date from one table which is in ISO format and then store it in US date format?
Trunc(cast(to_timestamp(ATTRIBUTE_39,'yyyy-mm-dd"T"hh24:mi:ss.ff3"Z"')as date))

Actual output:
4/11/2018  12:00:00 AM

expected output:
4/11/2018

Comment: What are the datatypes?
Comment: Without knowing exactly what you mean by "a date in ISO format" or "a date in US date format" I don't think anyone can answer this question.Is `ATTRIBUTE_39` a `date`, a `timestamp` or a `varchar2`? What is the type of the column you are inserting into?
Answer:
I am trying to pull date from one table which is in ISO format and then store it in US date format?

Dates (and timestamps) do not have a format - they are represented in a table by 7 bytes for a date or 20 bytes for a timestamp.
You can get the value as a DATE data type using TO_TIMESTAMP_TZ and either the TZR or TZH:THM format models to match the time zone region/offset (they will both work with the Zulu time zone region)
SELECT CAST(
         TO_TIMESTAMP_TZ(
           ATTRIBUTE_39,
           'yyyy-mm-dd"T"hh24:mi:ss.ff3TZH:TZM'
         ) AT TIME ZONE 'UTC'               -- Convert to a common time zone
         AS DATE
       )
FROM   your_table;

When you select from the table then whatever client program you are using (typically) will implicitly convert the 7-bytes it uses internally to something you, the user, can read - a string. SQL/Plus and SQL Developer use the NLS_DATE_FORMAT session parameter as the format model when they perform this implicit conversion.
So your query is effectively converted to:
SELECT TO_CHAR(
         CAST(
           TO_TIMESTAMP_TZ(
             ATTRIBUTE_39,
             'yyyy-mm-dd"T"hh24:mi:ss.ff3TZR'
           ) AT TIME ZONE 'UTC'
           AS DATE
         ),
         (
           SELECT VALUE
           FROM   NLS_SESSION_PARAMETERS
           WHERE  PARAMETER = 'NLS_DATE_FORMAT'
         )
       )
FROM   your_table;

If you want to format a date or a timestamp then you will have to explicitly convert it to a string using TO_CHAR():
SELECT TO_CHAR(
         CAST(
           TO_TIMESTAMP_TZ(
             ATTRIBUTE_39,
             'yyyy-mm-dd"T"hh24:mi:ss.ff3TZR'
           ) AT TIME ZONE 'UTC'
           AS DATE
         ),
         'MM/DD/YYYY'
       )
FROM   your_table;

Or by altering the NLS_DATE_FORMAT session parameter:
ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';

(Be aware that this will only change the format in the current session and will not change it for any other sessions/users.)
Answer: Try this:
select to_char(Trunc(cast(to_timestamp('2016-06-29T13:13:00.123','yyyy-mm-dd"T"hh24:mi:ss.ff3"Z"')as date)),'MM/DD/YYYY') from dual

the default date/time formatting depends on your NLS_DATE_FORMAT setting.

Issue with date in oracle


Python xlsxwriter is converting date to number while writing xlsx

Question: I've to export the database table to Excel (xlsx) format.
I came to know that Python is very fast in file processing.
I've installed python 3.6.1, XlsxWriter-1.0.2 and cx_Oracle-5.3-12c
But I saw the date field from the database was getting converted to the number.
To resolve this, I made a check if a list value \ (cell) value is date time, if yes then formatted the value to date type which resolves my problem
But, I am now running into performance issue with this extra check any suggestion how to gain performance
Below python function is used to generate excel xlsx from the database cursor
<code>#Function to write excel from Oracle Cursor
def writeToExcel(cur_sor, targetDir, export_file_name):
    Actual_Path = os.path.join(targetDir, export_file_name)

    #Array to capture Date type columns
    DateTimeColumns = []

    print('\t\t\t  writing: '+export_file_name+'\t\t\t\t'+str(datetime.datetime.now()))
    workbook = xlsxwriter.Workbook(Actual_Path)  # Create Excel Object for new workbook
    worksheet = workbook.add_worksheet(sourceSYS)  # Add a New Worksheet Name - scott_schema
    row = 0
    col = 0

    for i in range(len(cur_sor.description)):
        desc = cur_sor.description[i]

        #Only Data Type column will be capture
        if format(desc[1])== "<class 'cx_Oracle.TIMESTAMP'>":
            DateTimeColumns.append(i)

        bold = workbook.add_format({'bold': True})
        date_format = workbook.add_format({'num_format': 'dd/mm/yy'})
        worksheet.write(row, (col + i), format(desc[0]), bold)  # Iterate for column headers

    date_format = workbook.add_format({'num_format': 'dd/mm/yy'})
    color_format = workbook.add_format()
    color_format.set_font_color('red')
    row = row + 1

    #Loop for each row, return by database cursor
    for tupple_row in cur_sor:
        col = 0
        #Loop for each column, for particular row open in level-up cursor
        for list_item in tupple_row:

            #If column position matches with datetype column position
            if col in DateTimeColumns:
                #Check if the cell value is date type, additional check to handle "None" (blank date cell)
                if isinstance(list_item, datetime.date) or isinstance(list_item, datetime.datetime) \
                    or isinstance(list_item, datetime.time) or isinstance(list_item, datetime.timedelta):
                    #Format the date, inorder to save as date rather number
                    worksheet.write(row, col, list_item.strftime("%Y-%b-%d %H:%M:%S.%f"))
            else:
                worksheet.write(row, col, list_item)

            col = col + 1
        row = row + 1

    workbook.close()
</code>
Comment: Welcome to SO. To help us understand your problem, please supply a [mcve].
Comment: I've updated the original post and posted the excel generation piece.
Answer: You should read the  docs http://xlsxwriter.readthedocs.io/working_with_dates_and_time.html

Working with Dates and Time
  Dates and times in Excel are represented by real numbers, for example "Jan 1 2013 12:00 PM" is represented by the number 41275.5.
The integer part of the number stores the number of days since the epoch and the fractional part stores the percentage of the day.
A date or time in Excel is just like any other number. To display the number as a date you must apply an Excel number format to it

Can you share some code so I can be of better help with your performance problem?
Comment: I've updated the original post with excel writing function


Newton's method convergence criteria

Question: To use Newton's method on interval $[a,b]$ we need to guarantee that

$f(a)f(b)<0$ on the interval which is true for $[0,1]$.
$f'(x)$ and $f''(x)$ are continuous on the interval $[a,b]$ (which they are)
$f'(x) \neq 0$ on $[a,b]$ and $f''(x)$ does not change signs on $[a,b]$

Then if $f(x_{0})f''(x_{0})>0$ the method will converge.
I have the following exercise in my textbook and I don't understand a part of the solution:
Using Newton's method and starting approximation $x_{0} = 1$ find the root of the equation $$f(x)=e^{x}-\sin(x)-1.5$$
Given solution:
$$f'(x) = e^{x}-\cos(x)$$
$$f''(x) = e^{x}+\sin(x)$$
$f'(x)$ and $f''(x)$ are both positive on the given interval, we can therefore use it.
We verify that $f(0)f''(0)>0$ and then start the algorithm itself.
My questions for this part of the solution:

How can I determine what are the function values for a function like $f'(x)$ or $f''(x)$? Is it possible to graph them by hand?
$f'(x)=0$ for $x=0$ which seems to be in contradiction with the convergence criteria. Is the solution right?

Thanks.
Answer: I don't understand what you mean by your first question. If you know the explicit form, simply compute it. Otherwise, note that $e^x > 1$ for $x > 0$ and observe that $\cos x$ is bounded above by $1$. Therefore, $f'(x)$ must be positive over the positive reals. The same argument holds for $f''(x)$.
For your second question, since $f(0) = -0.5$, and $f(x)$ is continuous, we know that there is a neighborhood around $0$ where $f$ does not have a root. So consider an interval $[\epsilon, 1]$. That elides the problem in your first derivative criterion.
Answer: For your first question, you will certainly need (for your particular functions) some method to numerically approximate the values of $f'$ and $f''$ at the intermediate values --- a calculator or computer algebra system.
For your second question, all that is really required for guaranteed convergence is that $f'(x)\ne 0$ in some neighborhood of the root; in your case, since $f(0) \ne 0$ and $f$ is continuous, that is guaranteed because $f'(x) \ne 0$ in $(0,1]$.

Newton's method convergence criteria


Como usar um simulador de iOS em um ambiente Windows 10 para um projeto Xamarin.Forms iOS

Question: O que eu preciso instalar para publicar um projeto Xamarin.Forms.iOS em um simulador de iOS?
Estou usando uma maquina com:
Windows 10
Visual Studio 2015
Sempre que eu tento rodar algum projeto de Xamarin.Forms.iOS aparece uma mensagem de: No remotely accessible Macs were detected on your network. For more information, click Where's my Mac?
Comment: Penso que seja necessário rodar o simulador em uma máquina com OSX ou no mínimo, como o erro informa, uma máquina com OSX (Macs) na rede pra executar remotamente.
Comment: Você precisará de um Mac mesmo. Você até encontrar algumas maneiras de virtualizar o Mac no Windows, mas essa prática é ilegal.
Answer: Para realizar a compilação e simulação de uma aplicação iOS no Windows, infelizmente, você necessitará de um computador da Apple conectado na rede, pois, a Apple exige que as suas aplicações somente sejam compiladas em seus dispositivos(computadores), mais uma evidencia que o Xamarin é realmente nativo ;).
Como bem sabemos um computador da Apple não é nada barato, porém, existem soluções legais que podem te auxiliar neste sentido, que é o aluguel de maquinas Apple, com elas será possível conectar nelas e realizar a compilação e simulação.
Segue alguns links que oferecem este serviço:
http://www.macincloud.com/
https://xcloud.me/
Comment: Além disso é necessário ter a versão Enterprise do Visual Studio!


Application of Liouville's Theorem

Question: Let $f$ : C → C be an entire function such that $2f(1) = f(0)$. What can you say about $f$?
Since $f(1) - f(0) =-f(1)$, My intuition says to define a new function $g(z)$ such that:
$g(z) =
 \begin{cases}
      f'(0) & z= 0 \\
      f(z)-f(0) &  z\neq 0
   \end{cases}
$.
But this is not helping me anyway to prove that $f$ is constant.
Edit: $f$ need not be constant as $f(z) = z(z-1)$ act as a counter example.
Comment: $2f(1)=f(0)$ certainly does not imply $f$ is constant. The trivial example: $f(z) =z(z-1)$.
Comment: Are you sure this is the full problem?
Comment: Also $f(z)=2^{-z}$.
Comment: $2^{-z}= e^{-z\ln{2}}$
Answer: Since $f$ is entire has everywhere (absolutly) convergent power series representation$f(z)=a_0+a_1z+a_2z^2+\cdots.$ According to your given condition $a_0=2(a_0+a_1+a_2+\cdots).$ Therefore $$f(z)=a_1(z-2)+a_2(z^2-2)+a_3(z^3-2)+\cdots.$$
For example:
$a_1=1-, a_2=1$ and $a_3=a_4=\cdots=0$ gives the function $z(z-1).$
$a_n=\left(\dfrac{\ln(1/2)}{n!}\right)^n\,\,\,\,\forall n=1,2,\cdots$ gives us the function $2^{-z}.$

In fact for any entire function $F,$ $$f(z)=F(z)-2F(1)+F(0)$$ has this property.
Comment: Again: $f(z)=2^{-z}$
Comment: Just a small correction: $f(z) = a_{1}(z-2) + a_{2}(z^2-2)+...$.
Comment: @Delsilon: Thank you very much for pointing out my mistake. I'll edit accordingly.

Application of Liouville’s Theorem


Maximize function involving $\textrm{erf}(\cdot)$

Question: I want to maximize the following function in $x$ subject to $0<x<\sqrt{2}$:
$$f(x) = \frac{x^2}{2}\left[1 - \textrm{erf}\left(\frac{cx^2}{\sqrt{2}}\right)\right],$$
where $c$ is a constant.  Is there someway i can obtain an explicit or approximate solution to the problem in terms of $c$. I know that $\textrm{erf()}$ is not a convex function, so i don't know what to do in this case.
Answer: This is a non-convex (and non-concave) optimization problem, for which I think the only reliable way of getting a solution fr positive $c$ is by applying a "rigorous" global optimization solver, such as a branch and bound solver, to numerically perform the optimization.
Here is a program in YALMIP, using its BMIBNB global optimizer, and using default optimality gap tolerance (which could be tightened) and the results for integer values of c from -3 to 50. The columns are $c$, optimal x, maximum f(x)
<code>for c=-3:50
  x=sdpvar;
  Obj=x^2/2*(1-erf(c*x^2/sqrt(2)));
  optimize(0<=x<=sqrt(2),-Obj,sdpsettings('solver','bmibnb','verbose',0));
  disp([c value(x) value(Obj)])
end

  -3.000000000000000   1.414213279530439   1.999999198027036
  -2.000000000000000   1.414212148864674   1.999932657499150
  -1.000000000000000   1.414213301744288   1.954498936103806
                   0   1.414213562373095   1.000000000000000
   1.000000000000000   0.867059142975441   0.169971207479903
   2.000000000000000   0.613103429828933   0.084985603739951
   3.000000000000000   0.500596885362942   0.056657069159965
   4.000000000000000   0.433529645616029   0.042492801869971
   5.000000000000000   0.387760726093716   0.033994241495975
   6.000000000000000   0.353975515355711   0.028328534579976
   7.000000000000000   0.327717666322975   0.024281601068548
   8.000000000000000   0.306551884044641   0.021246400934964
   9.000000000000000   0.289022540669026   0.018885689714784
  10.000000000000000   0.274191185122473   0.016997120742092
  11.000000000000000   0.261431349745961   0.015451927946127
  12.000000000000000   0.250301760512696   0.014164267282706
  13.000000000000000   0.240482440814156   0.013074708259702
  14.000000000000000   0.231734956159698   0.012140800525598
  15.000000000000000   0.223877505563722   0.011331413822613
  16.000000000000000   0.216768722902053   0.010623200457413
  17.000000000000000   0.210296803436546   0.009998306311564
  18.000000000000000   0.204372003123553   0.009442844848508
  19.000000000000000   0.198921302275294   0.008945853013279
  20.000000000000000   0.193884772553261   0.008498560361099
  21.000000000000000   0.189212391598071   0.008093867009250
  22.000000000000000   0.184862315924978   0.007725963962091
  23.000000000000000   0.180799133705201   0.007390052484125
  24.000000000000000   0.176992623454012   0.007082133629286
  25.000000000000000   0.173416854904914   0.006798848282781
  26.000000000000000   0.170049415549653   0.006537354116760
  27.000000000000000   0.166870841765926   0.006295229888879
  28.000000000000000   0.163864081217455   0.006070400248855
  29.000000000000000   0.161014276311922   0.005861076100803
  30.000000000000000   0.158308151504580   0.005665706896100
  31.000000000000000   0.155734050840069   0.005482942156170
  32.000000000000000   0.153281577031039   0.005311600212442
  33.000000000000000   0.150941306558982   0.005150642629926
  34.000000000000000   0.148705329731572   0.004999153138461
  35.000000000000000   0.146565749246576   0.004856320190295
  36.000000000000000   0.144515951270381   0.004721422405878
  37.000000000000000   0.142549827445021   0.004593816393553
  38.000000000000000   0.140661835789860   0.004472926487103
  39.000000000000000   0.138846945426578   0.004358236062914
  40.000000000000000   0.137100541299260   0.004249280159953
  41.000000000000000   0.135418421333310   0.004145639179110
  42.000000000000000   0.133796753606340   0.004046933482941
  43.000000000000000   0.132231975304239   0.003952818749491
  44.000000000000000   0.130720857494969   0.003862981958388
  45.000000000000000   0.129260417037842   0.003777137913339
  46.000000000000000   0.127847847435310   0.003695026218188
  47.000000000000000   0.126480605044799   0.003616408637691
  48.000000000000000   0.125156315554814   0.003541066789692
  49.000000000000000   0.123872778099728   0.003468800119121
  50.000000000000000   0.122627942825427   0.003399424115350
</code>
As can be seen, for any $c \le 0$, the optimal value of $x = \sqrt{2}$. That is because, in that case, both $x^2/2$ and $(1-\text{erf}(cx^2/\sqrt{2}))$ are individually maximized and nonnegative at $x = \sqrt{2}$, and therefore their product must be maximized at $x = \sqrt{2}$.
Answer: $\newcommand{gae}[1]{\newcommand{#1}{\operatorname{#1}}}\gae{maximize}\gae{erf}\newcommand{subj}{\text{subject to}}\gae{erfc}$I'll call $\erfc(x)=1-\erf(x)$ to save notation length. If $c=0$, the maximum is clearly $1$. I agree with user MarkL.Stone that you should work with $0\le x\le \sqrt2$. If $c\ne0$, make the substitution $t=\frac{\lvert c\rvert x^2}{\sqrt 2}$, so that your original problem $(A_c)$ becomes equivalent to:

if $c>0$,  \begin{align}\maximize&\quad  \frac{t}{\lvert c\rvert\sqrt2}\erfc (t)&(B_c)\\\subj&\quad0\le t\le \lvert c\rvert\sqrt2\end{align}

if $c<0$,  \begin{align}\maximize&\quad  \frac{t}{\lvert c\rvert\sqrt2}\erfc (-t)&(D_c)\\\subj&\quad0\le t\le \lvert c\rvert\sqrt2\end{align}

Now, $(D_c)$ is easy to evaluate because $t\erfc(-t)$ is increasing on $[0,\infty)$ and therefore the maximum is for $t=\lvert c\rvert\sqrt2$. Hence the solution is $\erfc(-\lvert c\rvert\sqrt2)=\erfc(c\sqrt2)$.
$(B_c)$ is essentially an evaluation of what and where the maximum of $t\erfc( t)$ on $[0,\infty)$ is, and whether or not it is in the interval $[0,\lvert c\rvert\sqrt2]$. It turns out that the maximum of $t\erfc( t)$ is at $t=\alpha\approx 0.531597$ and that the value is $L=\alpha\erfc(\alpha)\approx 0.240376$: however, given the fact that $t\erfc( t)$ is $0$ in $t=0$, it increases for a while and then it decreases to $0$, approximating $\alpha$ and $L$ should not be a challenge. The bottom line is that the solution to $(B_c)$ ends up being $\erfc(c\sqrt 2)$ if $0<c\le\frac\alpha{\sqrt2}$, and $\frac{L}{c\sqrt2}$ if $c>\frac\alpha{\sqrt2}$.
Putting it all together the "exact" solution to $(A_c)$ is:

$\erfc\left(c\sqrt 2\right)$ if $c\le\frac\alpha{\sqrt2}$; this maximum is attained at $x=\sqrt2$.

$\frac{L}{c\sqrt2}$ if $c>\frac\alpha{\sqrt2}$; this maximum is attained at $x=\sqrt{\frac{\sqrt2\alpha}{c}}$.

Where $\alpha=\operatorname{argmax}_{x\ge0} x\erfc (x)$ and $L=\max_{x\ge 0}x\erfc (x)$.


Puppeteer: Chromium instances remain active in the background after browser.disconnect

Question: My environment

Puppeteer version: 3.1.0
Platform / OS version: Windows 10
Node.js version: 12.16.1

My problem is:
I have a for...of loop to visit 3000+ urls with puppeteer. I use puppeteer.connect to wsEndpoint so I can reuse one browser instance. I disconnect after each visit and close the tab.

first 100 urls page.goto's open the urls immediately,
above 100 page.goto uses 2-3 retries per url,
above 300 page.goto uses 5-8 retries per url,
above 500 I get TimeoutError: Navigation timeout of 30000 ms exceeded all the time.

I checked the Windows Task Manager and I realized hundreds of Chromium instances running in the background and using 80-90MB of memory each and 1-2% of CPU as well.
Question
How can I kill the Chromium instances I've already disconnected with browser.disconnect for real?
Example script
const puppeteer = require('puppeteer')
const urlArray = require('./urls.json') // contains 3000+ urls in an array

async function fn() {
  const browser = await puppeteer.launch({ headless: true })
  const browserWSEndpoint = await browser.wsEndpoint()

  for (const url of urlArray) {
    try {
      const browser2 = await puppeteer.connect({ browserWSEndpoint })
      const page = await browser2.newPage()
      await page.goto(url) // in my original code it's also wrapped in a retry function

      // doing cool things with the DOM

      await page.goto('about:blank') // because of you: https://github.com/puppeteer/puppeteer/issues/1490
      await page.close()
      await browser2.disconnect()
    } catch (e) {
      console.error(e)
    }
  }
  await browser.close()
}
fn()

The error
The usual puppeteer timeout error.
TimeoutError: Navigation timeout of 30000 ms exceeded
    at C:\[...]\node_modules\puppeteer\lib\LifecycleWatcher.js:100:111
  -- ASYNC --
    at Frame.<anonymous> (C:\[...]\node_modules\puppeteer\lib\helper.js:94:19)
    at Page.goto (C:\[...]\node_modules\puppeteer\lib\Page.js:476:53)
    at Page.<anonymous> (C:\[...]\node_modules\puppeteer\lib\helper.js:95:27)
    at example (C:\[...]\example.js:13:18)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  name: 'TimeoutError'
}

Answer: Finally I was able to achieve the desired result by adding --single-process and --no-zygote args at launch (+ --no-sandbox is required with them).
The number of running Chromium processes aren't growing exponentially anymore, but only two instances remain active: one of them is the usual empty tab in the first position, the second is reused correctly by puppeteer.connect({ browserWSEndpoint }).
[...]
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--single-process', '--no-zygote', '--no-sandbox']
  })
  const browserWSEndpoint = await browser.wsEndpoint()
[...]

--single-process: Runs the renderer and plugins in the same process as the browser [source]
--no-zygote: Disables the use of a zygote process for forking child processes. Instead, child processes will be forked and exec'd directly. Note that --no-sandbox should also be used together with this flag because the sandbox needs the zygote to work. [source]
Comment: Works for me - 1000+ urls and many chromium background processes hanging around. Only needed args:  '--no-zygote', '--no-sandbox'] (in fact --single-process caused an error) and the background processes disappeared.
Comment: Make sure your node does not error out at all. So it actually gets to the browser.close() section. Otherwise it'll never get the chance to close chromium.
Comment: Any idea, on how to scrape capterra review? I have 200+ URLs. On a single URL request, it works fine. But when I start it in a loop, capterra page shows the captcha code. I tried with a timeout, but still, it didn't work.
Answer: I run puppeteer inside docker (with docker-compose). Adding --single-process and --no-zygote did not stop zombie processes being created. What worked for me is adding init: true in the docker-compose.yml file in the service where puppeteer was run.
services:
  web:
    image: alpine:latest
    init: true

References

https://pptr.dev/troubleshooting#running-puppeteer-in-docker
https://stackoverflow.com/a/64394969/3775598
https://docs.docker.com/compose/compose-file/compose-file-v2/#init


Calculating list size from original and altered average when x is removed.

Question: The average of x number of values is 66, and when a certain 77 is removed from these values, the average drops to 62. Find x, or the number of values that when averaged give 66, and when 77 is removed from the list x, the new average is 62. What is x, no need to find the values.
Comment: Hint: how do you find averages?
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Answer: Let the sum of $x$ values be $S$. Then the average is
$$\frac{S}{x} = 66.$$
That if $77$ is deducted the new average is $62$ means
$$\frac{S-77}{x-1} = 62.$$
Combining these two equations yields
$$\frac{4x-15}{x-1}=0.$$
From here we can say that $x\neq 1$ and $x$ is not an integer.


How do I report progress while executing a LINQ expression on a large-ish data set

Question: If I need generate a fairly large dataset using LINQ and it may take a while (say a few seconds) and I need to (would like to) generate feedback to the use as to %'age done, is there an easy/ preferred way to do this?
Example, say I have list A with 1000 cars and list B with 1000 trucks and I want to select all possible ordered (car, truck) pairs where car.color == truck.color link this:
var pairs = from car in A
            from truck in B
            where car.color==truck.color
            select new {car, truck};

Now at some point this will be evaluated as a set of nested foreach loops.  I would like to be able to report %'age complete as it interates and ideally update a progressbar or something.
EDIT: Just after my query, I store the result in a member variable as a list like this (which forces the query to execute):
mPairs = pairs.ToList();

I do this because I am executing this in a background worker thread as I do not want the UI thread to freeze up as it evaluates the LINQ expression on demand on the UI thread (this is in Silverlight BTW).  Hence why I would like to report progress.  The UX is basically this:

A user drags an item onto the workspace
The engine then kicks up on a background thread to determine the (many) connection possibilities to all of the other items on the workspace.
While the engine is calculating the UI does not allow new connections AND reports progress to indicate when the new item will be "connectable" to the other items (all the possible connection paths not already in use have been determined via LINQ).
When the engine completes the calculation (query), the item is connectable in the UI and the possible connection paths are stored in a local variable for future use (e.g. when the user clicks to connect the item all the possible paths will be highlighted based upon what was calculated when it was added)

(a similar process must happen on deletion of an item)
Comment: Related: [How can I report progress from a PLINQ query?](https://stackoverflow.com/questions/55584078/how-can-i-report-progress-from-a-plinq-query)
Answer: EDIT: This doesn't currently work because query expressions don't allow braces. Editing...
You could always add a "no-op" select or where clause which showed progress:
public class ProgressCounter
{
    private readonly int total;
    private int count;
    private int lastPercentage;

    public ProgressCounter(int total)
    {
        this.total = total;
    }

    public void Update()
    {
        count++;
        int currentPercentage = (count * 100) / total;
        if (currentPercentage != lastPercentage)
        {
            Console.WriteLine("Done {0}%", currentPercentage);
            lastPercentage = currentPercentage;
        }
        return true;
    }
}

...

var progressCounter = new ProgressCounter(A.Count * B.Count);

var pairs = from car in A
            from truck in B
            where progressCounter.Update()
            where car.color==truck.color
            select new {car, truck};

Note the use of side-effects, which is always nasty. I hope you'd use a join if this were really the query, btw :)
We've been thinking of adding a sort of operator like this to MoreLINQ - called Pipe, Apply, Via, or something like that.
Answer: Something I used that worked well was an adapter for the DataContext that returned a count of the number of items it's yielded.
public class ProgressArgs : EventArgs
{
    public ProgressArgs(int count)
    {
        this.Count = count;
    }

    public int Count { get; private set; }
}

public class ProgressContext<T> : IEnumerable<T>
{
    private IEnumerable<T> source;

    public ProgressContext(IEnumerable<T> source)
    {
        this.source = source;
    }

    public event EventHandler<ProgressArgs> UpdateProgress;

    protected virtual void OnUpdateProgress(int count)
    {
        EventHandler<ProgressArgs> handler = this.UpdateProgress;
        if (handler != null)
            handler(this, new ProgressArgs(count));
    }

    public IEnumerator<T> GetEnumerator()
    {
        int count = 0;
        foreach (var item in source)
        {
            // The yield holds execution until the next iteration,
            // so trigger the update event first.
            OnUpdateProgress(++count);
            yield return item;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Usage
var context = new ProgressContext(
    from car in A
    from truck in B
    select new {car, truck};
);
context.UpdateProgress += (sender, e) =>
{
    // Do your update here
};

var query = from item in context
            where item.car.color==item.truck.color;

// This will trigger the updates
query.ToArray();

The only issue is you can't easily do a percentage unless you know the total count. To do a total count often requires processing the entire list, which can be costly. If you do know the total count beforehand then you can work out a percentage in the UpdateProgress event handler.
Comment: I really like this approach.  My LINQ expression consists of several nested from's - I could put this around the outer-most list to at least get a gross progress indicator (which is probably all I need anyway as I do not want to incur the overhead of updating too frequently.)
Answer: Most of Linq is done using lazy evaluation. So the query is actually not executed until you foreach over the result. Every time you 'pull' a result from pairs a piece of the query is evaluated.
That means you can just display progres in the foreach loop that iterates over the result.  The downside is that you dont know in advance how big the result-set is going to be, counting the size of the result-set will also iterate over the results and execute the query.
Answer: Well mine was similar to Jon's although I'm sure his approach would be much more concise.  You can hack something together along the same means..
var pairs = from car in A
            from truck in B
            let myProgress = UpdateProgress(...)
            where car.color == truck.color
            select new { car, truck };

private int UpdateProgress(...)
{
    Console.WriteLine("Updating Progress...");
    return -1;
}

Although as mentioned the query won't be executed until it is iterated over.
This also as the added disadvantage of creating a new scope variable inside the query.


Mongoose group by lookup field

Question: I'm new at NodeJS and Mongoose and I'm trying to do some advanced queries.
I have three documents (Category, Subcategory and Product)
Category.js
var mongoose = require('mongoose');
var CategorySchema = new mongoose.Schema({
    name: { type: String, required: true }
});

mongoose.model('Category', CategorySchema);
module.exports = mongoose.model('Category');

Subcategory.js
var mongoose = require('mongoose');
var SubcategorySchema = new mongoose.Schema({
    name: { type: String, required: true },
    image: { type: Buffer, contentType: String },
    idcategory: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' }
});

mongoose.model('Subcategory', SubcategorySchema);
module.exports = mongoose.model('Subcategory');

Product.js
var mongoose = require('mongoose');
var ProductSchema = new mongoose.Schema({
    name: { type: String, required: true },
    idsubcategory: { type: mongoose.Schema.Types.ObjectId, ref: 'Subcategory', required: true },
    price: { type: Number, required: true }
});

mongoose.model('Product', ProductSchema);
module.exports = mongoose.model('Product');

So, a Product has a Subcategory which has a Category.
Since I have this structure I wanna count my products by categories. i.g.
[
  { "categoryName": "cat1": quantity: 10 },
  { "categoryName": "cat2": quantity: 5 },
  { "categoryName": "cat3": quantity: 2 }
]

I already tried a $lookup with $group without success since I dont understand the aggregate at all.
Mongoose: "4.11.6"
Answer: Try this
CategoryModel.aggregate([
    // stage 1: join subcategories
    {
        $lookup: {
            from: 'subcategories',      // collection to join
            localField: '_id',          // field from categories collection
            foreignField: 'idcategory', // field from subcategories collection
            as: 'subcategory'
        }
    },
    // at this point, each document will have an additional subcategory array with all the "joined" documents from subcategories collection
    // stage 2: we need to "unwind" the subcategory array in order to join the products
    // when you unwind an array, it's like making each element in the array have its own document
    {
        $unwind: '$subcategory'
    },
    // stage 3: join products
    {
        $lookup: {
            from: 'products',               // collection to join
            localField: 'subcategory._id',  // field from our updated collection
            foreignField: 'idsubcategory',  // field from products collection
            as: 'products'
        }
    },

    // EDIT

    // stage 4: strip out all fields except _id, category name, and quantity (number of products)
    {
        $project: {
            name: true,
            quantity: { $size: '$products' }
        }
    },
    // stage 5: group by category ID
    {
        $group: {
            _id: '$_id',                        // group by category ID
            categoryName: { $first: '$name' },  // get category name
            quantity: { $sum: '$quantity' },    // sum the quantities
        }
    }
]).exec(...);

Comment: Thanks a lot @mikey. But there is a little issue in this code. The problem is the _$first_. This _$first_ is showing the fisrt group with the **category.id**. But when I have two **subcategories** for the same category, it doesn't works. I tried to use _$sum_ instead but it doesn't works as well.
Comment: @brunnogrillo Maybe try flipping stage 4 and 5. Basically, after stage 3, we'll have all the necessary info we need. Then in stage 4, take out relevant fields including getting the quantity for each category+subcategory document. Then stage 5, group by category where we sum the quantities.
Comment: Actually, after your edit, it works. Thanks @mickey it was very helpful

Mongoose group by lookup field


Erro ao comparar senha MD5 em PHP

Question: Estou com um problema em um form de login, abaixo segue os códigos atuais.
Estou utilizando o método via POST, o que ocorre é que ele não esta enviando o post em MD5 para que seja feita a comparação no DB.
No banco de dados já esta registrado a senha em MD5, porém ao enviar os dados por esse form para ele concluir o login ele não converte a senha.
Alguém sabe onde esta o erro?
form login
<form id="1" name="1" action="pass.php" method="post">

      <input placeholder="Usuário" type="text" id="username" size="25" name="name" />

      <input placeholder="Senha" id="pass" type="password" size="25" name="pass" />

      <input type="submit" name="_2" value="Login" />
      <input type="hidden" name="ed_type" value="" />
      <input type="hidden" name="redirect" value="<? echo $redirect;?>" />

</form>

pass.php
<?php
session_start();
$usuario_admin = isset($_SESSION['1x11']) ? $_SESSION['1x11'] : '';

include("conf.inc.php");
include("conectar.php");

$query = "select * from admin where username='" . $_POST["name"] . "' and pass=MD5('" . $_POST["pass"] . "')";
$result = mysql_query($query, $db);
$row = mysql_fetch_array($result);
$total = mysql_num_rows($result);
$name = $_POST['name'];
$pass = $_POST['pass'];
$ADMIN_USERNAME = $row["username"];
$ADMIN_PASSWORD = $row["pass"];

if ($total > 0) {
    if ($name == $ADMIN_USERNAME && $pass == $ADMIN_PASSWORD) {
        if ($usuario_admin != '')
            $_SESSION['1x11'] = "";
        $_SESSION["1x11"] = $name;
        $_SESSION['logedin'] = true;
        $_SESSION["type"] = $row["type"];
        $_SESSION["usrname"] = $name;
        $_SESSION["logid"] = $row["id"];
        header("Location:index2.php");
    }
} else {
    header("Location:index.php?id=1");
}
?>

Informações do post enviado utilizando TAMPER DATA:
Host=dominio.com
User-Agent=Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0
Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language=pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding=gzip, deflate
Referer=http://dominio.com/admin/index.php?id=1
Cookie=PHPSESSID=1d5d5r8hlp6hnebv9pa115d8r
Connection=keep-alive
Upgrade-Insecure-Requests=1
Content-Type=application/x-www-form-urlencoded
Content-Length=59
POSTDATA=name=admin&pass=admin&_2=Login&ed_type=&redirect=

NOVO ERRO:
Notice: date_default_timezone_set() [function.date-default-timezone-set]: Timezone ID '-03:00' is invalid in /home/user/public_html/admin/adm.config.inc.php on line 15

Notice: date_default_timezone_set() [function.date-default-timezone-set]: Timezone ID '-03:00' is invalid in /home/user/public_html/admin/conf.inc.php on line 3

Notice: Undefined variable: timezone_set in /home/user/public_html/admin/conectar.php on line 9

Notice: Use of undefined constant hora - assumed 'hora' in /home/user/public_html/admin/conectar.php on line 14

conectar.php
<?php
    include_once("conf.inc.php");

    $db=mysql_connect($DBSERVER, $USERNAME, $PASSWORD);
    if (!$db) die('Não foi possivel conectar: ' . mysql_error());
    mysql_select_db($DATABASENAME,$db);

    if ($timezone_set=="")$timezone_set="America/Sao_Paulo";
    $sql = mysql_query("Set @@global.timezone = '".$timezone_set."';");

    $sql = mysql_query("Select Now() as hora");
    $dados=mysql_fetch_array($sql);
    $Hora_Servidor_MySQL = date('Y/m/d H:i:s',strtotime($dados[hora]));
?>

Answer: seu erro esta na sua query
a correta deveria ser
$query = "select * from admin where username='" . $_POST["name"] . "' and pass='" . MD5($_POST["pass"]) . "'";

Comment: rss agora é outro problema vc tem q revisar seu script. habilita a exibição de erros do php e posta o erro.
Comment: Já tinha tentado dessa forma e ele não funciona de jeito nenhum... :(
Comment: faz um favor, vc esta passando para o seu sistema a senha admin , copia la no seu db como ela esta e posta aqui. ( o hash md5 dela )
Comment: Segue: `21232f297a57a5a743894a0e4a801f`
Comment: ta ai seu problema o md5 de admin é 21232f297a57a5a743894a0e4a801fc3 provavelmente seu campo no mysql d senha esta limitado aumente o varchar para 50 q resolve
Comment: Nossa realmente, que mancada! rsrs

Mas agora deu outro problema, ele fica com a tela em branco quando loga. Redireciona para pass.php e fica a tela branca.
Comment: Atualizei a pergunta, pode dar uma olhada? Estranho esses erros por que se eu não usar MD5 ele faz o login normalmente, e usando MD5 ocorre esses erros. Por que será?
Comment: da onde vc recebe o $dados[hora]? e sobre o default time zone leia isto http://php.net/manual/pt_BR/function.date-default-timezone-set.php
Comment: seria algo assim date_default_timezone_set('America/Sao_Paulo');
Comment: Já corrigir nesses dois aquivos, agora só ficou o erro no arquivo conectar.php, atualizei a pergunta com o código completo desse arquivo... Na verdade esses $dados[hora] não sei da onde recebe, pois naõ tem nenhuma referência nos arquivos, nem no conectar nem no conf.inc, estranho...
Comment: entao deveria ser assim $Hora_Servidor_MySQL = date('Y/m/d H:i:s');
Comment: Ta complicado fazer funcionar, sumiu todos os erros porém ainda fica com a tela branca e não redireciona para a página inicial.
Comment: faz um redirecionamento por meta e nao por header pois vc pode ta tendo algum output anets dessa header echo"";
Comment: Não funcionou também, continua tela branca. oO
Comment: estranho m add no skype eu t ajudo por teamviewer -> jasaroc

Erro ao comparar senha MD5 em PHP


How to Print and style Profile2 fields?

Question: I created a profiles type called: Game Player Profile (Machine name: game_player_profile). This contains : field_firstname, field_lastname, field_profilephoto, field_zipcode.....
How do I print and style these fields to create a page with a list of the 'Game Players' First Names + Last Names + Photo.....
Thanks
J.
Answer: Take a look at the Views Module.  It is the primary module used to select fields and display them. You can find out just about everything you need to know about using the module in this Video series

How to Print and style Profile2 fields?


How to connect ZKTeco attendance to google sheet or online php server

Question: I don't have any idea of it how can i get attendance data directly to google sheet from ZKTeco attendance device. I searched many way to connect to php server but there is no clear information, how can I get access to the device attendance log. There also no HTTP request from the device also. So can any share there experience and how can I solve that issue ? I am using ZKTeco K40 and F18
Answer: You need to develop a program that calls the ZKTeco web API and have an available server that post your users' data.
After you have the data available in JSON, you can use the URL Fetch Service you can call in Apps Script within your Google Sheets to display the information in a spreadsheet in this way
<code>var response = UrlFetchApp.fetch(url)
var content = response.getContentText()
var json = JSON.parse(content)
</code>


Format double value to 2 decimal points and get comma separated currency format in Java

Question: I'm working on project where I have to display price in following format.
250  -> 250.00
2500 -> 2,500.00
260500.33 -> 260,500.33

I though following approach gonna make this work but It's not working.
    double price = 2500;
    DecimalFormat df = new DecimalFormat("#.00");

    String format1 = df.format(price);
    System.out.println(format1); //250.00

    String format2 = NumberFormat.getNumberInstance(Locale.US).format(format1);// Exception "Cannot format given Object as a Number"
    System.out.println(format2); //excepted 2,500.00

What am i doing wrong ?
Answer: DecimalFormat and NumberFormat objects expect their objects to format to be some kind of number, not a string such as format1, so an IllegalArgumentException is thrown.
You've passed an already formatted string format1 to format instead of a number.  Pass price to format as you already did the first time you called it.
But the US locale NumberFormat won't give you any digits beyond the decimal point; you will see 2,500 printed.  If you want those 2 decimal digits, you can specify that format explicitly, similar to how you constructed df.
String format2 = new DecimalFormat("#,###.00").format(price);

Comment: Can you not use `DecimalFormat.setMinimumFractionDigits(2)` to ensure there's always two decimal places displayed?
Comment: Yes, using `NumberFormat`'s `setMinimumFractionDigits` will work.
Answer: This is how to set two decimal points and comma separated.
NumberFormat.getCurrencyInstance().format(price);

Comment: It may return the currency code as part of the formatted results which can be very misleading if the same data is being viewed in different locales


How to model a bounded lognormal dependent variable with many zeros

Question: I try to analyze firms´ investment decisions.
In my dataset 70% of the firms choose to invest 0 $ .
30% invest more than 0. (continuous variable).
The data of the 30 % is log normally distributed.
Which model is recommended for such data structure? OLS, tobit or glm model? Or even something else?
First I thought a Tobit model would be appropriate but I then I gave up this idea due to the log 0 problem.
Comment: You might want to mention that you're working with panel data, if that is still the case. This both complicates the problem, but may allow you to estimate this.
Answer: You could model this as a zero inflated gamma (or zero inflated log normal), where you assume two process - one that generates zero with a certain probability (those that dont invest) and for those that do, a process that follows a gamma (or could use log normal).
I have used this model several times, writing contrast statements as Dale shows in the link below for E(Y). It is very useful. I wont go into more detail because the link sums up most of the salient points.
Here is a link to the code for fitting this model in SAS. The question was posed on this site about converting to R, without a definitive answer, but I am sure it is possible.
Another option is to use two separate models P(Y=0) and E(Y | y>0) and make inference about E(Y) with simulation (page of 150 of Gelman, Hill 2007).


Coloring the grid points with three colors

Question: About half a year ago I posted a problem: "Coloring grid points with two colors" (The problem)
I found it really interesting, so I thought I make some research. Now I need help with my following question. I am thankful for every idea, hint and solution.
Let $S$ be a set of finite many grid points (points in the coordinate system with integer coordinates).
Is it always possible to color them with three colors, red, green and blue , such that in each vertical and horizontal line the following statements is true:
if there are $R$ number of red, $G$ number of green and $B$ number of blue points, than $|R-G|\leq 1, \ |G-B|\leq 1 \ |B-R|\leq 1$?
Answer: Yes, this can always be done.

Lemma. This can be done when every vertical and horizontal line with points on it contains exactly $3$ points.

Proof. In this case, all three points on a line must receive different colors.
We can think of this problem as  a graph theory problem. Consider the bipartite graph with vertices on one side corresponding to the horizontal lines, and vertices on the other side corresponding to the vertical lines. Put an edge between two vertices when the corresponding lines intersect.
This is a regular graph, since every vertex has three edges out of it. Every regular bipartite graph has a perfect matching (this can be proven using Hall's theorem, for example here): a set of edges covering each vertex exactly once. Back in the grid, this corresponds to a set of points such that every line (vertical or horizontal) contains exactly one of them.
Color this set of points red, and remove the corresponding edges from the graph. The remainder is still regular and bipartite (every vertex has two edges left coming out of it), so there is another perfect matching, giving us another set of points with this property.
Color this second set of points green, and the leftover points blue. Now every line has exactly one red, blue, and green point on it.

In general, we can reduce the problem for an arbitrary grid to an instance of the lemma above.
First of all, we can get rid of horizontal lines with more than $3$ points on them. If a line has $k>3$ points, split it up into $\lfloor \frac k3\rfloor$ lines with $3$ points on them, and maybe a leftover line with $1$ or $2$ points. To do this, move the points so that they still have their old $x$-coordinates (and therefore lie on their old vertical lines) but instead of all having the same $y$-coordinate, only share $y$-coordinates in groups of $3$ or less.
If we can color the new arrangement of points, we could color the old arrangement. On each line with $3$ points, each color is used once; if there is a leftover line of $1$ or $2$ points, no color repeats on it. So each color is used at least $\lfloor \frac k3\rfloor $ times, with $1$ or $2$ colors possibly used $\lfloor \frac k3\rfloor + 1$  times, which still satisfies the conditions.
Then do the same thing for the vertical lines.
Second, we can get rid of horizontal lines with $1$ or $2$ points on them. On every such line, add new points to get up to $3$, making sure not to reuse $x$-coordinates (so that every point added lies on a new vertical line). The condition on the resulting line is that all $3$ points must be different colors, so if we get rid of the new points, the old line still satisfies the coloring condition.
Then do the same thing for the vertical lines. Now all vertical lines have exactly $3$ points on them, but there are some horizontal lines with $1$ point on them (the rest have $3$).
The total number of points must be a multiple of $3$ now. So the number of horizontal lines with $1$ point on them is also a multiple of $3$. Group them up in threes, and for every three points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3,y_3)$ we group together, add more points $(x_4,y_1)$, $(x_4,y_2)$, $(x_4,y_3)$ and $(x_5,y_1)$, $(x_5,y_2)$, $(x_5,y_3)$. This creates two new vertical lines with $3$ points on them, and fills the horizontal lines with $1$ point up to $3$.
Now we are in the case of the lemma, and so we can color the points in a way that satisfies the condition. Undo everything we've done (deleting points we added, and merging together lines we split up) and we get a coloring of the original grid.
Comment: Your argument works as far as I can tell.
Comment: Thank you! ........


RecursiveDirectoryIterator to list directories

Question: I want to use the RecursiveDirectoryIterator to list files and directories recursively. Below is my code.
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(".", RecursiveDirectoryIterator::SKIP_DOTS));

foreach ($rii as $file){
    if ($file->isDir()) {
        echo "D ".$file->getPathName();
    } else {
        echo "F ".$file->getPathName();
    }
    echo "
\n";
}

The problem is that it does not return directories at all. Only files are listed. When I omit the SKIP_DOTS flag, I do get directories but in the form of dir/. and dir/.. which is obviously not what I want.
Now I could of course strip the trailing dots myself, but I wonder if there's a better builtin method I'm not aware of?
Answer: $rdi = new RecursiveDirectoryIterator('.', RecursiveDirectoryIterator::KEY_AS_PATHNAME | RecursiveDirectoryIterator::SKIP_DOTS);
foreach (new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST) as $file => $info) {
    echo $file."\n";
}

Example files/directory structure
.
|-- a
|   `-- x
|       |-- hbye.txt
|       `-- hello.txt
|-- b
|   `-- a
`-- script.php

4 directories, 3 files

Script output:
./a
./a/x
./a/x/hbye.txt
./a/x/hello.txt
./script.php
./b
./b/a


create a google map marker containing price

Question: I am creating a real estate website with a map showing houses with their price. I need a marker like the marker used on airbnb.com. How can I do it? I am using  this:

I need something like this:
Comment: Cool story. What have you tried and what's actually wrong with your code? (assuming you have even attempted this yourself)
Comment: Please post your code. But first, see [How to complete a Minimal, Complete, and Verifiable Example](/help/mcve).
Comment: the image i post is what i want to have, i am using now a normal marker i use this code:
 marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i][3],
con: (on) ? 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=V|EC2A8C|000000' :      'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=L|BDD73C|000000'
        });
Comment: Although not sure if it will solve your problem.but just for try. https://developers.google.com/maps/documentation/javascript/custom-markers
Answer: You can create a custom icon, like the one below - use another image URL for your needs.
var image = {
          url: 'http://www.homedepot.com/catalog/swatchImages/35/04/04a604de-8b52-4cd8-a394-6286f00b438d_35.jpg',
          // This marker is 35 pixels wide by 35 pixels high.
          size: new google.maps.Size(35, 35),
          // The origin for this image is (0, 0).
          origin: new google.maps.Point(0, 0),
          // The anchor for this image is the base of the flagpole at (0, 32).
          anchor: new google.maps.Point(0, 35)
        };

Then when creating the marker, use the image object as the icon property. For more information see the maps API documentation for complex icons.
See it in action in the snippet below:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(41.385932, 2.178678),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var image = {
          url: 'http://www.homedepot.com/catalog/swatchImages/35/04/04a604de-8b52-4cd8-a394-6286f00b438d_35.jpg',
          // This marker is 35 pixels wide by 35 pixels high.
          size: new google.maps.Size(35, 35),
          // The origin for this image is (0, 0).
          origin: new google.maps.Point(0, 0),
          // The anchor for this image is the base of the flagpole at (0, 32).
          anchor: new google.maps.Point(0, 35)
        };
  var clickMarker = new google.maps.Marker({
    position: map.getCenter(),
    map: map,
    draggable: true,
    icon: image,
    label: {
      text: "50€",
      color: 'white',
      fontSize: '15px',
      fontWeight: 'bold'
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

Answer: Use google maps built in info window. Here is an example in jQuery:
var infoContent = "
Your Detailed Information Here
";

var infoWindow = new google.maps.InfoWindow({
    content: infoContent
});

marker.addListener('click', function () {
    infoWindow.open(map, marker);
});

You can then style the info window how you like with CSS
Comment: yes i am using that, but what i need is price in the marker not when clicking on it
Comment: Will a title work for you next to the marker? See example here:  map.addMarker(new MarkerOptions().title("$27.56")); If not then you will have to replace the image dynamically with SVG.
Comment: i have title for marker, i need like image i post so how can i do it?
Comment: I assume you do not have a bunch or pre built images, correct? so you wan to "make them and inject them dynamically, right?"
Comment: now i am showing a simple marker with only one letter, i want to show a marker with text only this
Comment: Check out answer 1 on this thread, that should get you where you are trying to go: http://stackoverflow.com/questions/33321440/google-maps-api-add-custom-svg-marker-with-label


DevExpress ASPxPivotGrid.CustomCellStyle Event: Change a cell's style based on values of other cells

Question: I need to change the background of a cell based on values of multiple cells. Example in Pseudo Code:
Percentage = Actual Value / Target Value

IF (Percentage < 33)
 Cell Color = Red
ELSE IF (Percentage < 66)
 Cell Color = Orange
ELSE
 Cell Color = Green

I found this:
http://documentation.devexpress.com/#AspNet/DevExpressWebASPxPivotGridASPxPivotGrid_CustomCellStyletopic
That's nice, but it doesn't show an example of getting a value from another cell in the same row. I need an example and the above link does say it is possible:
"...allows you to customize the appearance of cells dynamically (depending on their
contents, position, values of other cells, etc..."
Answer: Got it:
decimal target = Convert.ToDecimal(e.GetFieldValue(fieldTarget));
decimal value = Convert.ToDecimal(e.Value);
decimal percent = (value / target) * 100;

where fieldTarget is an instance of a DevExpress.Web.ASPxPivotGrid.PivotGridField
and then use that value to set the background color..


Android Navigation Drawer Popup SubMenu

Question: I am testing on the navigation drawer, and it works great by following the document provided by google developer console. For now, I wanted to implement a submenu inside the drawer, I have been searching around and I can found the expandable list view solution, but what if I want to implement something like the image below. By the way, is there a name for this? or is it popup listing?
Navigation Drawer pop up submenu http://s23.postimg.org/u1ssfpaef/android.jpg
I know I must do some customization base on the sample from google, I am thinking if the pop up menu should be another list view activity?
Answer: you can use Android's default Popup Menu for it. you will find more about menus on this linkAndroid Developer Guide for Menus
But as per Android UI Guidelines and User Experience you should not use multiple overlapping popups. That's why GMail and Play-store Apps use collapsible list item for sub-menu content.
To add a popup menu on button click you can use following code:
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        openOptionsMenu();
    }
});

or else set android:onClick="myOnClickMethod" on your Button in xml and then have:
public myOnClickMethod(View v) {
    openOptionsMenu();
}

in your activity.
Hope you got your answer.
Comment: Could you please elaborate more your answer adding a little more description about the solution you provide?
Comment: Say you want to open your submenu on the button click of a Navigation Drawer, for the you can use following code
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        openOptionsMenu();
    }
});

or else set android:onClick="myOnClickMethod" on your Button in xml and then have:

public myOnClickMethod(View v) {
    openOptionsMenu();
}
in your activity.

Android Navigation Drawer Popup SubMenu


evaluating 'equalness' of matrices. What function to use?

Question: I'm working on my a research project at university which is about a convolutional neural network.
I have neurons/filters which are described by 5x5 matrices with numbers from 0 to 1.
In the very beginning, the filters are initialised with random values, which all come from the same distribution (gaussian, same mean and variance). As time goes on, I expect these filters to change, so that they each have areas with high and low values.
I want to compare these matrices statistically. My thinking is, that in the very beginning one can show that these matrices were generated using the same distribution. What function would describe this? Covariance/Corellation?
When the filters specify/change, they should be less equal regarding the distribution of high and low values inside the matrix so the value of the function should go down.
When I have a certain number of filters > 2, should I compare them pairwise or could I also compare the 'equalness' of the whole set at once?
Thanks in advance.
Edit: I have to mention, that the position of values is important for the analysis.
I have pictures to visualize my filters right now and I'm sifting through them in order to see which parameters produced good and which produced bad filters. That's what I want to do with a mathmatical model instead.
Here are some pictures (yellow is high, purple low values)
This is a pretty much unlearned filter
Green values indicate that the values are somewhere near the mean.
This is an upper edge detector
You see, that values are near 1 in the top and near 0 in the bottom picture.
bottom edge
This is something in the making
My thinking was, that I could show that the first and last filter have some statistical value in common. Something that decreases when filters start to change. I'd argue that filters which don't 'correlate' with the gaussian distribution are better filters and that filter sets that don't 'correlate' with each other are better filters. What statistical property could I use?
Comment: So if I understand correctly each entry in each matrix is initially sampled from the same gaussian distribution? If this is so you could compare a histogram of binned values as observed in a matrix with a histogram over the same bins for a different matrix using https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test. Or you could compare it with a simulated histogram generated from the original gaussian distribution, as an external validation.
Answer: I will try a practical example, I might be misunderstanding (so please let me know if I'm making incorrect assumptions here), but I assume we start with two $5 \times 5$ matrices with entries sampled from the same Gaussian distribution...I will just use the standard normal with mean 0 and standard deviation 1. So using python to generate two such matrices:
A = np.random.normal(size=(5,5))
B = np.random.normal(size=(5,5))

I will not display the result here to save space. So then I calculate a histogram with 6 bins for the first matrix:
np.histogram(A.flatten(),bins=6)

For me this resulted in
(array([1, 1, 5, 6, 9, 3]),
 array([-2.74347505, -2.1026386 , -1.46180215, -0.82096569, -0.18012924,
         0.46070721,  1.10154366]))

The first array in the result is the count in each bin, the second indicates the bin edges. Now I calculate a histogram for $B$ with the same bins:
    np.histogram(B.flatten(),bins=[-2.74347505, -2.1026386 , -1.46180215,-0.82096569, -0.18012924,
0.46070721,  1.10154366])

For my $B$ matrix the result was then
(array([0, 0, 3, 8, 8, 5]),
 array([-2.74347505, -2.1026386 , -1.46180215, -0.82096569, -0.18012924,
         0.46070721,  1.10154366]))

Now I want to apply a statistical test to see if [1, 1, 5, 6, 9, 3] and [0, 0, 3, 8, 8, 5] approximates the same distribution. I have developed a simple distance-based metric that can do this: it requires one to normalize the histograms to essentially become frequency functions, calculating the $l_1$ distance between these frequency functions, and then using a CDF function to convert the distance to a probability score. So normalizing and calculating the distance
a = [x/sum([1, 1, 5, 6, 9, 3]) for x in [1, 1, 5, 6, 9, 3]]
b = [x/sum([0, 0, 3, 8, 8, 5]) for x in [0, 0, 3, 8, 8, 5]]
dist = sum([abs(x-y) for (x,y) in zip(a,b)])

so just to print these results for me
a= [0.04, 0.04, 0.2, 0.24, 0.36, 0.12]
b= [0.0, 0.0, 0.125, 0.3333333333333333, 0.3333333333333333, 0.20833333333333334]
dist= 0.3633333333333334

Now I run it through my CDF for dimension 6:
cdf_6 = joblib.load('repos/bias_distance/cdf/l_1_lin_interp_dim_6.joblib')
cdf_6(dist)

which results in p-value array(0.08840493).
Now for comparison let's say I change $B$ to B = np.random.uniform(-2,2,size=(5,5)), which results in the following histogram counts for the same bins as before: [0, 4, 1, 4, 7, 5]. If I then repeat the procedure and calculate the distance I get
dist= 0.5371428571428571
print(cdf_6(dist))

array(0.33260882)

and there is obviously more "bias" between $A$ and $B$ now.
You would have to decide on reasonable cut-offs for considering two matrices as "the same"...for this metric the closer the value is to zero the more alike the samples are.
At first, as I mentioned in the comments, I thought about just using Pearson's chi-squared test, but at least 5 observations in each bin is required for this test, so for the size matrices you have this won't work. To read more about the distance-based bias metric I am using here please see this preprint. If you want to use it, I can supply you with the (python sklearn based) CDF functions you will need to convert the distances to probability scores.


Shouldn't a weighted t-test and a weighted linear regression yield the same standard error on the estimated mean?

Question: I have a vector of values and a vector of the reciprocal of their standard error. I'd like to estimate their mean and the standard error on the mean.
At first I used linear regression using the lm() function. Later I found out that the weights library provided a wtd.t.test() function for doing t-tests on weighted data. One side-effect of the test is an estimate of the mean of the data, with a standard error.
I expected both approaches to yield the same result, but they don't.
Here is a short but complete example:
library(weights)
test <- c(1,1,1,1,1,1,2,2,2,3,3,3,4,4)
weight <- c(.5,.5,.5,.5,.5,1,1,1,1,2,2,2,2,2)
wtd.t.test(test, weight=weight)
summary(lm(test~1, weights=weight))

The weighted t-test yields 2.64 +/- 0.27, whereas the linear regression yields 2.64 +/- 0.30. Which is correct (if any)?
Comment: I wonder if the regression is using sampling weights (weights that denote the inverse of the probability that the observation is included because of the sampling design) and the t-test is using importance weights. That is what I get with Stata using your data.
Answer: Probably because the weight in wtd.t.test is treated as a frequency weight but in lm it is treated as an analytical/proportion weight.
If you try multiply the variable weight by 2 or 3 and refit the t-test and regression, you'll find that the SE of the regression model does not change, while the degrees of freedom in wtd.t.test keeps increasing (and SE shrinking.)
So, I think it's natural that they don't agree.
Answer: It is not clear what wtd.t.test really does when you give it only one set of data.  The help page and the output indicates that it is doing a 2 sample test (with a default value of 0 for y).  So it is really not doing the same test as lm.
I would expect more similarity if you do a 2 sample test for both.  But there is still possibility of difference if wtd.t.test does not use a pooled variance (I could not find anything in the documentation that says whether it assumes equal variance or not, the lm approach does fit a pooled variance).


Limit of the sequence $\lim_{n\rightarrow \infty}n\left ( 1-\sqrt{1-\frac{5}{n}} \right )$, strange result

Question:
$\lim_{n\rightarrow \infty}n\left ( 1-\sqrt{1-\frac{5}{n}} \right )$

$\lim_{n\rightarrow \infty} n *\lim_{n\rightarrow \infty}\left ( 1-\sqrt{1-\frac{5}{n}} \right ) = \infty * \left ( 1-\sqrt{1-0} \right ) = \infty * 0 = 0$
Did I do it correctly?
Problem is when I use my calculator and put big values for $n$, I get $2,5$ as result (if I take very very big values, it's $0$ :D).
Anyway, this made me feel a bit insecure and that's why I'm asking if I did it right.
Answer: In short: no, you did not do it correctly. The reason is that $\infty\cdot 0$ is one of the indeterminate forms, you cannot conclude it's equal to zero.
The rationale being: it can be anything. For instance, $$\begin{align}
\underbrace{n}_{\to \infty}\cdot \underbrace{\frac{1}{n}}_{\to 0} &\xrightarrow[n\to\infty]{} 1\\
\underbrace{n^2}_{\to \infty}\cdot \underbrace{\frac{1}{n}}_{\to 0} &\xrightarrow[n\to\infty]{} \infty\\
\underbrace{n}_{\to \infty}\cdot \underbrace{\frac{1}{n^2}}_{\to 0} &\xrightarrow[n\to\infty]{} 0\\
\underbrace{n}_{\to \infty}\cdot \underbrace{\frac{\cos n}{n}}_{\to 0} &\xrightarrow[n\to\infty]{} \text{ nothing (no limit)}
\end{align}$$
To solve your indeterminate form, you have to use other techniques to "remove" that issue. Taylor expansions, multiplication by a conjugate, L'Hôpital rule... there are known and systematic methods to do so.

E.g., with Taylor expansions: when $u\to 0$,
$$
\sqrt{1-5u} = 1-\frac{5}{2}u + o(u)
$$
so applying it with $u\stackrel{\rm def}{=}\frac{1}{n}\xrightarrow[n\to\infty]{}0$,
$$\begin{align}
n\left(1- \sqrt{1-\frac{5}{n}}\right)
&= \frac{1}{u}\left(1- \sqrt{1-5u}\right)
= \frac{1}{u}\left(1- 1 + \frac{5}{2}u + o(u)\right)
= \frac{1}{u}\left(\frac{5}{2}u + o(u)\right)\\
&= \frac{5}{2} + o(1) \xrightarrow[n\to\infty]{}\frac{5}{2}.
\end{align}$$

Addendum: why does your calculator do that? The correct answer is indeed $\frac{5}{2}=2.5$. Yet, for "very big $n$", your calculator will return $0$ instead... and that boils down to machine precision. I assume it starts by computing the term $\sqrt{1-\frac{5}{n}}$, then plugs in the result to get $1-\sqrt{1-\frac{5}{n}}$, and finally multiplies what remains by $n$ and outputs the value. But for very large $n$, due to machine precision and rounding errors, the first step will be so close to $1$ that the calculator will just compute $1$ instead of $\sqrt{1-\frac{5}{n}}\approx 1 - \frac{5}{2n}$. So then, $1-1=0$, and no matter what the last step should do, it returns $n\cdot 0=0$.
Comment: Very well explained.  +1
Comment: Glad i could help! If you feel more comfortable with this, you can also see your limit as computing a derivative. Set $$f(x) = \sqrt{1-5x}$$ for $x\in[-1,1]$ and look at $\frac{f(x)-f(0)}{x-0} = \frac{\sqrt{1-5x}-1}{x}$. The limit at $0$ will be $f'(0)$... but does the expression ring a bell (e.g., considering $x=\frac{1}{n}$)?
Comment: Wow thanks a lot for your answer man! Taylor polynoms, I heard of these but nothing else so far. Then I should learn them to understand your post completely and to solve tasks like that.
I have just tried to solve it with L'Hôpital (good to know you can use it for multiplications as well, thought it was only made for fractions). But I always end up with $0 * \infty$...Never mind that.
And thank you very much for the clarification with the calculator ^.^
Answer: $$n-n\sqrt{1-\frac{5}{n}}=\frac{(n-n\sqrt{1-\frac{5}{n}})(n+n\sqrt{1-\frac{5}{n}})}{n+n\sqrt{1-\frac{5}{n}}}=\frac{5}{1+\sqrt{1-\frac{5}{n}}}\rightarrow \frac{5}{2}, \space \text{as} \space \space n \rightarrow \infty.$$
Comment: Damn it I haven't thought about that, using the binomial formula! >.<
Thanks so much for this!
Comment: @cnmesr This is not really an application of the Binomial formula, rather an instance of "rationalizing the numerator."
Comment: But what he used is the 3th binomial formula, isn't it?
$(a+b)*(a-b)$
Ok I think we may call basic idea is binomial formula, not sure.. :D
But now I understood both of your answers and I'm so happy I did, now I can relax and continue learning tomorrow.
Thanks a lot again to both of you! :)
Answer: No, you can't do it like that: when you have a product where one factor has limit $\infty$ and the other has limit $0$, you cannot apply a theorem on products of limits.
The theorem helps when both limits are finite and you just multiply them; it also works when one limit is $\infty$ (or $-\infty$) and the other one is either infinite or *finite and not $0$". Also in this case you can "multiply": the limit will be either $\infty$ or $-\infty$, depending on the signs of the factors.
Instead of the sequence (which is implied by the use of $n$), try and find the limit of the function:
$$
\lim_{x\to\infty}x\left(1-\sqrt{1-\frac{5}{x}}\right)=
\lim_{t\to0^+}\frac{1-\sqrt{1-5t}}{t}
$$
with the substitution $x=1/t$. This limit is much easier to manage; if it exists, then the sequence will have the same limit. Note however that the limit of the function may not exist whereas the limit of the sequence exists. Not in this case: take your pick below.
1. Rationalization
$$
\lim_{t\to0^+}\frac{1-\sqrt{1-5t}}{t}
=
\lim_{t\to0^+}\frac{1-(1-5t)}{t(1+\sqrt{1-5t})}=
\lim_{t\to0^+}\frac{5)}{1+\sqrt{1-5t}}=\frac{5}{2}
$$
2. Taylor expansion
$$
\lim_{t\to0^+}\frac{1-\sqrt{1-5t}}{t}
=
\lim_{t\to0^+}\frac{1-(1-\frac{5}{2}t+o(t))}{t}
=
\lim_{t\to0^+}\left(\frac{5}{2}+o(1)\right)=\frac{5}{2}
$$
3. Derivative
The limit is the derivative at $0$ of $f(t)=1-\sqrt{1-5t}$ and
$$
f'(t)=\frac{5}{2\sqrt{1-5t}}
$$
so
$$
f'(0)=\frac{5}{2}
$$


Get Array values using a class in c#

Question: i have declared 2 string values eg: ChName1, ChName2 and 2 int values eg: Delay1, Delay2 in the settings.
i would like to implement an array in class so life will be more easier. can somebody correct my code with necessary explanations
public class GetDefaultValues
    {
        public string Name[int i]
        {
            get
            {
                switch (i)
                {
                    case 0:
                        return Name.Properties.Settings.Default.ChName1;
                    case 1:
                        return Name.Properties.Settings.Default.ChName2;
                    default:
                        return "Not Implemented";
                }
            }

            set
            {
                switch (i)
                {
                    case 0:
                        {
                            Name.Properties.Settings.Default.ChName1 = value;
                            break;
                        }
                    case 1:
                        {
                            Name.Properties.Settings.Default.ChName2 = value;
                            break;
                        }
                }

                Name.Properties.Settings.Default.Save();
            }
        }

        public int Value[int i]
        {
            get
            {
                switch (i)
                {
                    case 0:
                        return Name.Properties.Settings.Default.Delay1;
                    case 1:
                        return Name.Properties.Settings.Default.Delay2;
                    default:
                        return 0;
                }
            }

            set
            {
                switch (i)
                {
                    case 0:
                        {
                            Name.Properties.Settings.Default.Delay1 = value;
                            break;
                        }
                    case 1:
                        {
                            Name.Properties.Settings.Default.Delay2 = value;
                            break;
                        }
                }

                Name.Properties.Settings.Default.Save();
            }
        }
    }

then in my main code i could do like this
GetDefaultValues Vlues = new GetDefaultValues();
Vlues.Name[0] = "SomeName";
string SomeString = Vlues.Name[1];

Vlues.Value[0] = 125;
int SomeInt = Vlues.Value[1];

this code is generating errors in my code.

Error 2 Bad array declarator: To declare a managed array the rank
  specifier precedes the variable's identifier. To declare a fixed size
  buffer field, use the fixed keyword before the field type

will be happy if i could know why??
please help!!
Comment: *this code is generating errors in my code* Which errors?
You realy should use methods instead of properties for this...
Comment: In addition to the error you should also say where the error happened. I am confident that you were told exactly which line the problem was on so you should not leave us guessing....
Comment: Error 2 Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type
Answer: I would recommend not to use properties for this because properties should not have that logic. You should use methods instead.
This could be look like this for example (just added the name as a sample).
public class GetDefaultValues
{
    public bool SetName(int i, string value)
    {
        switch (i)
        {
            case 0:
                {
                    Name.Properties.Settings.Default.ChName1 = value;
                    break;
                }
            case 1:
                {
                    Name.Properties.Settings.Default.ChName2 = value;
                    break;
                }
            default:
                return false;
        }

        Name.Properties.Settings.Default.Save();
        return true;
    }

    public string GetName(int i)
    {
        switch (i)
        {
            case 0:
                return Name.Properties.Settings.Default.ChName1;
            case 1:
                return Name.Properties.Settings.Default.ChName2;
            default:
                return "Not Implemented";
        }
    }
}

This would be called like this
GetDefaultValues Vlues = new GetDefaultValues();
bool success = Vlues.SetName(0, "SomeName");
string SomeString = Vlues.Name(1);

You can make the SetName method a void method if you don't want to have the info if it worked or not.
Comment: thanks for reply. this is how i am currently implementing. but would like to know if properties could be used some how??
Comment: @joshinjoy As far as I know there is no way doing it with properties. And if there is one I would still recommend not putting this much logic in a property.

Get Array values using a class in c#


Is it possible to restrict the site search module to specific nodes?

Question: I am trying to figure out a way to provide a search for a specific set of nodes. Currently it seems that the site search is not configurable in this way. Is there any way to change this functionality, or other modules that provide a search for a defined group of pages/nodes?
Thanks!
Answer: You can use one of these 2 modules, Custom search Or Search restrict. Both these modules allow you to restrict the search on specific content types


How to make a change that affect several site at once?

Question: We have two Drupal 7 and two Drupal 8 website for an airline company. We want the staff at the airport to upload a flight schedule in such a way that it will get displayed in all the four sites at once. How can I achieve this?
Comment: You'll need to use the [RESTful Web Services](https://www.drupal.org/project/restws) module for D7. In D8 this module already comes with D8 Core.
Comment: I actually get it to work with RSS feed. This should be a better approached, will definitely try it out. thanks.
Answer: You should be able to do this by uploading the schedule to one site and then exposing an RSS feed for the other sites to pull it down.
Comment: Sorry for the late reply but this works great for me, thanks.


Initialize from row - Birt

Question: I want to take the value from the dataset and split it and each cell in the row I want to set the parallel information from the split string.
Is it possible?
var aud=this.getRowData().getColumnValue("someString").toString().split(",");

for (var i=0;i<this.getRowData().getColumnCount();i++)
{
HERE I WANT TO SET SOMESTRING[0]
}

Answer: No, this is not possible this way. But you can do it in a different way.
Your "Table" needs enough columns to hold all values.
For each cell in the detail row, add a "Dynamic Text" item. The value is a Javascript expression. Use an expression like this:
getColValue(row, 1)

Replace the number 1 with the corresponding column number in every cell.
Define a function (in the initialize event of the report) like this:
function getColValue(row, col) {
    // Handle undefined, empty or null strings gracefully.
    if (!row["someString"]) {
        return null;
    }
    var aud=row["someString"].toString().split(",");
    if (col <= aud.length) {
        return aud[col-1];
    } else {
        return null;
    }
}

You might also pass row["someString"] to your function in the "Dynamic Text" expression instead of passing row and getting row["someString"] inside the function.
In a similar way you could style your cells depending on the data: Use the onCreate event of the item (either the cell itself or an item inside the cell depending on what you want to do) and enter a script like this:
styleCell(this, row, 1);

Again, replace the number 1 with the corresponding column number.
The function styleCell could then be defined as (untested, but you get the point):
function styleCell(item, row, col) {
    var style = item.getStyle();
    var cond = someFunction(row, col);
    // The columns of row   ^^^ can be accessed as row["ColName"] here
    if (cond) {
        style.backgroundColor = "yellow";
    }
}

Comment: Thanks. this was helpful.
Is there a way to copy & paste the dynamic text boxes from xml source tab?
I saw that each element has an id so I don't know how to increment it.
Have any idea?
Comment: You can copy the item into each cell with the layout editor. Then siwtch to the XML source and increment the value.
Comment: the option of using "row["someString"]" syntax in initialize is not working for me.

Initialize from row - Birt


android: google glass custom(unlisted) voice command

Question: I am trying to use custom(Unlisted) voice commands on google-glass but for some reason it doesn't want to work. The keyword I am trying to use is "NEXT", it was working before, I am not sure what has changed.The command is supposed to navigate to the next Card view. please see the xml below.
declaration
<string name="glass_voice_trigger">next</string>

Manifest
     <uses-permission android:name="com.google.android.glass.permission.DEVELOPMENT"/>
    <uses-permission android:name="android.permission.INTERNET" />

<activity
            android:name="info.androidhive.glassmenu.scroll"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.google.android.glass.action.VOICE_TRIGGER" />
            </intent-filter>
            <meta-data
                android:name="com.google.android.glass.app.VoiceTriggers"
                android:resource="@xml/voice_trigger_start" />
        </activity>

voiceTrigger.xml
 <?xml version="1.0" encoding="utf-8"?>
<trigger keyword="@string/glass_voice_trigger">
</trigger>

Answer: Works fine for me. Here is the value of my trigger keyword:
<string name="next_trigger">next</string>


Magento 2 questions tagged beta, alpha, pre-alpha etc. - quo vadis?

Question: There are lots of Magento 2 questions from the pre-release era and I was wondering what to do with them.
Many technical details have changed since then and nobody uses these versions anymore, so the tags have at most historical relevance.
So here's my proposal:

Re-tag questions where the answers are still valid in Magento 2.0 (remove the old version tag, add magento-2.0
close questions where the answers are only valid for pre-release versions. We did the same with Magento Go questions when the service was discontinued
additionally, if the question has high views, try to find one on the topic that's up to date and link it

Thoughts?
Comment: Sounds good to me. Let's go for it.
Comment: Seconded. I'm in favor.
Comment: @RaphaelatDigitalPianism. I did something better. I closed that question.
Comment: I'm in too, let's do this
Comment: Hmmmm should we go for [tag:magento-2.0] or [tag:magento2] ?
Comment: Also @Marius you should probably update this one: http://meta.magento.stackexchange.com/questions/79/are-magento-2-0-questions-allowed
Comment: Same attempt for third party tags: http://meta.magento.stackexchange.com/q/905/3326
Answer: Great, approved by 2/3 mods.
So if anybody wants to actively help out, these are the tags that I could find:

magento2-pre-alpha
magento2-alpha
magento2-alpha93
magento2-alpha96
magento2-alpha105
magento2-dev-beta
magento2-merchant-beta
magento2-rc
188.8.131.52-dev55
Answer: I've done my share on a few tags. I have also removed the tags from closed questions because if you are tagging your question and type "magento2-" you still see them appearing in the suggestions with a >0 count.
Only magento2-dev-beta is still left with a large number of questions.

magento2-pre-alpha > 0 questions
magento2-alpha > 0 questions
magento2-alpha93 > 0 questions
magento2-alpha96 > 0 questions
magento2-alpha105 > 0 questions
magento2-dev-beta > 148 questions
magento2-merchant-beta > 0 questions
magento2-rc > 0 questions
126.96.36.199-dev55 > 0 questions
Comment: yes I've done some questions as well, I'll get back to it re: the dev-beta tag
Answer: Also, maybe we should create tag synonyms for those tags so no one use them in the future.