text:
Q: Representation of a C* algebra Let $A$ be a $C^*$- algebra. Let $\pi$ be a representation of $A$ on a Hilbert space $H$. Let $p \in A$ be a projection. Consider the $C^*$- algebra $pAp$. Let $P=\pi(p)$. I want to represent $pAp$ in $PH$. Is it correct if I define $\tilde \pi: pAp \to B(PH)$ by $\tilde \pi(pap)=P\pi(a)P$?

A: Yes, but written like that you make things unnecessarily complicated as you need to look whether your $\tilde\pi$ is well-defined. You simply need to define
$$
\tilde\pi(pap)=\pi(pap)|_{PH}.
$$

A: Martin's answer is  impecable but it might be interesting to analyze the meaning of the "restriction to $PH$"
mentioned there.
By $π(pap)|_{PH}$ he  certainly  means the operator from $PH$ to itself given by $ξ↦π(pap)ξ$,  for all $ξ$ in $PH$.
In this interpretation it is implicit that the co-domain has also been restricted,  since otherwise   $π(pap)|_{PH}$ might be seen as being an operator from $PH$ to $H$, rather
than to $PH$.
The goal here is simply to describe
a slick algebraic way to deal with the restriction question.  The crucial ingredient  is to consider the  inclusion of
$P(H)$ into $H$,  which we will denote by.
$$
  j:P(H) \to  H.
  $$
The adjoint of $j$ then turns out to be the orthogonal projection from $H$ to $P(H)$ but, technically speaking, $P\neq
j^*$, because the co-domain of $P$ is $H$, while the co-domain of $j^*$ is $P(H)$.  In other words, $P\in B(H,H)$, while
$j^*\in B(H,P(H))$.
Moreover  $j^*j=I_{P(H)}$ (because $j$ is an isometry), while  $jj^*$ coincides
with $P$ in all respects, co-domain included!
This said, the desired representation $\tilde \pi $ may be defined by
$$
  \tilde \pi (b) = j^*\pi (b)j, \quad \forall b\in pAp.
  $$
It is a lot of fun to prove  that   $\tilde \pi $ is multiplicative: for $b,c\in pAp$, we have
$$
  \tilde \pi (b)  \tilde \pi (c) =
  j^*\pi (b)j j^*\pi (c)j =
  j^*\pi (b)P\pi (c)j {\buildrel (*) \over =} $$$$ =
  j^*P\pi (b)\pi (c)j =
  j^*jj^*\pi (bc)j =
  j^*\pi (bc)j =
  \tilde \pi (bc).
  $$
The main fact supporting this calculation is that $P$ commutes with $\pi (b)$ (see (*) above), so the same argument
would still yield a representation should we just assume that $P$ lies in the commutant of our representation.


text:
Q: Java function to preserve the granularity I need to keep the granularity in a fuzzy job so I made a function which receives as parameters:

*

*the granularity (a double between 0 and 1, 0 not included)

*the value to transform, if necessary (it's a double greater than 0)

And returns a new value with the correct granularity.
This is the function I have:
public static double preserveGranularity(double granul, double value){
    double integerValue= (double)(int)value;
    if(granul == 1)
        return integerValue;
    double decimal = value - integerValue;
    long factor = Math.round(decimal/granul);
    return integerValue + granul*factor;
}

Examples:

*

*preserveGranularity(0.25, 7.7) should return 7.75

*preserveGranularity(0.01, 0.009) should return 0.01

It runs good for most of values, but it doesn't for all (e.g.: preserveGranularity(0.2, 0.57)=0.6000000000000001, it should return 0.6)
Regards
P.S. Sorry for any mistake I made in this question, it's my first one here

A: You cannot achieve this with double - since it is not exact enough.
doubles are not real numbers. There are only finite number of bits to represent them - while there are infinite number of real (or even rational) numbers out there, so these rounding errors are expected.
I think you are looking for BigDecimal, which lets you control the granularity, as you want, for example with its round() method.

A: Floating point calculations are not exact (the computer can only represent so much digits).  This means that somewhere in your division/multiplication/rounding/subtraction/addition operations you lose precision.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to interrogate a suspect a second time? I went and interrogated one of my suspects before having all of the facts available to me, so missed out on a couple of questions that may or may not crack this case wide open.
In this instance, I'm on the White Shoe Slaying case and the person I am wanting to re-interrogate is James Jessop. During my first interrogation, I returned straight to Central before following up on the Yellow Taxi lead, which reduced the number of questions that I could ask him and means I possibly missed some important information.
After finding the Yellow Taxi, I went back to the holding cells but he won't talk to me.
Is it possible to interrogate a suspect a second time?

A: It depends on the suspect and the plot. You can't re-ask the same question again, but if you don't ask all the questions, you can sometimes leave and come back to the same suspect to finish the interrogation. This will depend on the specific person and the specific case. Unfortunately, there's not really a general rule on whether this will be possible or not. It's usually a good idea to finish interrogating someone once you start.
Additionally, you will sometimes interrogate the same person multiple times through the course of a single case, after you find new evidence or new events transpire. I don't think this is what you're going for, though.


text:
Q: Is it possible to deliver more than one pass in a .PKPASS file? use case:
A customer bought a flight for his family.
Now he wants to download all boarding passes for his flight at once and store it in passbook.
How can I solve this problem?
Can I add more than one pass descriptions in a pass.json?
Or is it possible to reference more than one pass.json files in the manifest.json?

A: Short answer is No.  You cannot include more than one pass in the pass.json or add a reference that will be recognised by Passbook.
Long answer is that there are a number of things that you could do to make it easier for the user.  These include:

*

*Send all the passes in a single confirmation email as attachments

*Include links on the back of the passes to the other passes in the same booking

*Include a single link on all passes and in any confirmation mesage / email to a page with links where each pass can be downloaded

*Deliver the passes via an app

The last option would provide you access to PKAddPassesViewController class, which if used with the addPasses:withCompletionHandler: of the PKPassLibrary class, would allow for multiple passes to be added.


text:
Q: Are unique prime ideal factorization domains noetherian? Let $A$ be a domain satisfying the following condition:
If $\mathfrak p_1,\dots,\mathfrak p_k$ are distinct nonzero prime ideals of $A$, and if $m$ and $n$ are distinct elements of $\mathbb N^k$, then we have
$$
\mathfrak p_1^{m_1}\cdots\mathfrak p_k^{m_k}\ne\mathfrak p_1^{n_1}\cdots\mathfrak p_k^{n_k}.
$$

Is $A$ necessarily noetherian?

This question is motivated by these outstanding answers of user26857 and Julian Rosen.
user26857's answer shows that noetherian domains do satisfy the above condition, whereas Julian's answer shows that many non-noetherian domains do not satisfy it.

A: Let's call domains having this property $UPIF$-domains, as in your first post.
Observe that a domain which is locally $UPIF$ is $UPIF$.
Indeed, given $$\mathfrak p_1^{m_1}\cdots\mathfrak p_k^{m_k}=\mathfrak p_1^{n_1}\cdots\mathfrak p_k^{n_k}$$
we can localize at each of the $\mathfrak{p_i}$ one at a time and use the assumption that $D_{\mathfrak{p_i}}$ is $UPIF$ to deduce that $m_i = n_i$.
From your linked Questions/Answers, we thus have that a locally Noetherian domain is locally UPIF, hence

A locally Noetherian domain is $UPIF$.

However, there are locally Noetherian domains that are not Noetherian.
A classic reference for such examples is section 2 of this paper of Heinzer and Ohm.
For a more recent reference, I'd suggest Loper's article on Almost Dedekind Domains Which Are Not Dedekind.  In section 3, he discusses five distinct techniques for producing examples of non-Noetherian domains which are locally discrete valuation rings.


text:
Q: Display result of multi index array groupby in pandas dataframe I have a data frame which looks like:
        D        Type    Value
0       1        A          2
1       1        B          4
2       2        C          1
3       1        A          1

I want to group by D and Type and sum the values.
data=df.groupby(['D','Type']).sum()

print(data)

Which gives me this result:
D      Type               Value
1       A                    3
        B                    4
2       C                    3

But I want it in this format:
D      A         B        C
1      3         4        Nan
2      Nan       Nan      3

A: UPDATE:
r = df.pivot_table(index=['D'], columns='Type', aggfunc='sum').reset_index()
r.columns = [tup[1] if tup[1] else tup[0] for tup in r.columns]
r.to_csv('c:/temp/out.csv', index=False)

Result:
D,A,B,C
1,3.0,4.0,
2,,,1.0

Original answer:
you can use pivot_table() method:
In [7]: df.pivot_table(index=['D'], columns='Type', aggfunc='sum', fill_value=0)
Out[7]:
     Value
Type     A  B  C
D
1        3  4  0
2        0  0  1

or with NaN's:
In [8]: df.pivot_table(index=['D'], columns='Type', aggfunc='sum')
Out[8]:
     Value
Type     A    B    C
D
1      3.0  4.0  NaN
2      NaN  NaN  1.0

PS i think you have a typo in your groupby... section:
In [10]: df.groupby(['D','Type']).sum()
Out[10]:
        Value
D Type
1 A         3
  B         4
2 C         1

there should be C --> 1 instead of C --> 3


text:
Q: JSTL tag  doesn't evaluate in pentaho 7.1 I have an issue with the evaluation of ${varName} in JSTL tags in pentaho 7.1
This is the jsp:
 <c:url value="../STPivot" var="mdxURL">
    <c:param name="pivotId" value="${param.pivotId}" />
    <c:param name="pivotPart" value="mdx" />
 </c:url>
 <%
  System.out.println("mdxUrl ->" + pageContext.findAttribute("mdxURL"));
 %>

And this the output of println in pentaho 6.1 and 7.1:
6.1
../STPivot?pivotId=95d6c6e6-6ba1-4e07-94a9-9ea1c2721974&pivotPart=mdx
7.1
../STPivot?pivotId=%24%7Bparam.pivotId%7D&pivotPart=mdx
As you can see there is not evaluation for ${param.pivotId} in pentaho 7.1
Any suggestions?

A: The solution I found was to set the attribute isELIgnored to false...
<%@ page session="true" contentType="text/html;" isELIgnored="false" %>

...and change the uri of c tag to...
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Instead of http://java.sun.com/jstl/core


text:
Q: Kelly Criterion, Taylor Expansion and Edward Thorpe I was trying to read the following paper by Professor Edward Thorpe on Kelly Criterion:
http://www.eecs.harvard.edu/cs286r/courses/fall12/papers/Thorpe_KellyCriterion2007.pdf
On p.22, $n$ independent random variables $X_i, i=1,\cdots,n$ are defined such that
$P(X_i=m/n+s/n^{-1/2})=P(X_i=m/n-s/n^{-1/2})=1/2$ for all $i$
and $$g(f)=E \ln \prod_{i=1}^n (1+(1-f)r+fX_i).$$
Then he claimed that $g(f)$ is equal to (equation (7.1))
$$g(f)=r+f(m-r)-\frac{s^2f^2}{2}+O(n^{-1/2}).$$
Here $m,s$ and $r$ are all constants. I was trying to derive equation 7.1 myself but I couldn't.
I found that
$$g(0)=n\ln (1+r)$$
$$g'(0)=\frac{m-nr}{1+r}$$
and hence the coefficients in the taylor expansion don't match to that of equation 7.1. Any help is greatly appreciated, thanks.
Edit: The derivation of $g(0)$ is straight forward, just substitute $f=0$, for $g'(0)$:
I just use the fact that $\frac{d}{dx}\ln h(x) = \frac{h'(x)}{h(x)}.$

A: "I was trying to read the following paper..."  - my experience, too. I've come to the conclusion that the equations simply don't make sense. The expression for the maximum, $f^*$, given on line 26, $f^* = (m-r)/s^2$, is false. For example, for $r=0,\ m=.10,\ s=.2$, the formula gives 2.5 times the total wealth in the portfolio as the optimal position size. If one were to lever a portfolio that much, a $60\%$ investment loss would cause it to blow up, and wipe out, not only any and all gains, but the entire initial investment. That is not the mark of an optimal strategy.


text:
Q: A problem related to number theory How can I find out the number of multiples of a number in a given range. For example, if the range is $1$ to $15$, then the number of multiples of $2$, $3$, and $5$ are $7$, $5$, and $3$, respectively.
$M_2=\{2,4,6,8,10,12,14\}$
$M_3=\{3,6,9,12,15\}$
$M_5=\{5,10,15\}$
Is it possible to find out the number of multiples of a number without finding out all multiples in a given range? Is there any efficient method? If so, I need to know it and the reasoning behind it.

A: Let $n$ and $k$ be positive integers. We want to find the number of multiples of $k$ that are in the interval from $1$ to $n$. Imagine dividing $n$ by $k$.  There are integers $q$ and $r$, with $0\le r\le k-1$, such that $n=qk+r$.
The required number is $q$, since $qk\le n$ while $(q+1)k\gt n$. So $k,2k,\dots,qk$ are all the multiples of $k$ that are between $1$ and $n$, and there are $q$ of them.
Note that $q=\left\lfloor \frac{n}{k}\right\rfloor$, where $\lfloor x\rfloor$ is the "floor" function. In general, $\lfloor x\rfloor$ is the greatest integer which is $\le x$. For example, $\lfloor 3.14\rfloor=3$.
On a calculator, we find $\frac{n}{k}$ and throw away the part after the decimal point. For example, let us find the number of multiples of $7$ in the interval from $1$ to $1000$. The calculator gives, approximately, $\frac{1000}{7}\approx 142.85714$, so in this case $q=142$.


text:
Q: how to edit $woo_options['woo_featured_height' I have a old wordpress site that is defining some CSS using this code:
$fixed_height = ' style="height: ' . $woo_options['woo_featured_height'] . 'px;"';
<div class="slide <?php echo $css_class; ?>"<?php echo $fixed_height; ?>>

I cannot figure out where the $woo_options['woo_featured_height'] is defined. I have searched the entire codebase and there is no such value.

A: That's a woocommerce options array and most likely the option you are looking for comes from a database table and won't exists in your codebase.  See this link for more information.


text:
Q: Coverting php array to radio button in HTML? I want to create a survey using HTML, PHP, Javascript. So I have my question and answers in a csv file(eventually will be in a SQL server). What I need help is with how can i make my answers radio button(type) so the user can select one of them and I can process it later. The reason i am not hardcoding the questions is because i want to be able to edit them from a file(eventually server).
I have csv file that looks like this:
Question 1,Answer1 A,Answer1 B,Answer1 C,Answer1 D
Question 2,Answer2 A,Answer2 B,Answer2 C,Answer2 D

Now processing it with php the output looks like this:
1. Question 1
Answer1 A
Answer1 B
Answer1 C
Answer1 D
2. Question 2
Answer2 A
Answer2 B
Answer2 C
Answer2 D

The code i used for php is:

        <meta charset="UTF-8">
        <title></title>

        <?php
        $file = fopen('test.csv','r');
        while(($line = fgetcsv($file)) !== FALSE)
        {
            list($questions[], $optionA[], $optionB[], $optionC[], $optionD[]) = $line;
            //  print_r($line);
        }
        fclose($file);
        $lengthquestion = count($questions);
        $lengthoptionA = count($optionA);
        $lengthoptionB = count($optionB);
        $lengthoptionC = count($optionC);
        $lengthoptionD = count($optionD);

        echo '
';
        for($i=0; $i<$lengthquestion; $i++)
        {
            echo '

';
            echo $questions[$i] . '
';
                echo $optionA[$i] . '
';
                echo $optionB[$i] . '
';
                echo $optionC[$i] . '
';
                echo $optionD[$i] . '
';
            echo '

';
        }
        echo '
';
        ?>

The output i want is, of course radio button on the left
 A) Answer1 A
 B) Answer1 B
 C) Answer1 C
 D) Answer1 D

Update to main question:
Addition to the main question which is answered by @maytham:
On my top block of code i added this after php.
<form name="next" action="submit.php" method="post" id='1'>
    <input type="submit" value="Submit"/>
</form>

My real question is what should be in brackets ([]). Also can I call length question like that. Here is what i think code will look like:
Here is sumbit.php
<?php
session_start();
$file="FILE.csv";
$fp = fopen($file, "a") or die("could not open");
for($i=0; $i<$lenghtquestion; $i++)
{ $_SESSION["answer' . $i'"] = $_POST["answer' . $i'"];
  $data.=$_SESSION["answer' . $i'"].",";
  fwrite($fp,$data) or die("could not write"); }
fclose($fp);

This doesn't work though

A: You can do Radio buttons as group in your for loop:
for ($i = 0; $i < $lengthquestion; $i ++)
{
    echo '

';
    echo $questions[$i] . '
';
    echo '<input type="radio" name="group' . $i . '" value="' . $optionA[$i] . '">' . $optionA[$i] . '
';
    echo '<input type="radio" name="group' . $i . '" value="' . $optionB[$i] . '">' . $optionB[$i] . '
';
    echo '<input type="radio" name="group' . $i . '" value="' . $optionC[$i] . '">' . $optionC[$i] . '
';
    echo '<input type="radio" name="group' . $i . '" value="' . $optionD[$i] . '">' . $optionD[$i] . '
';
    echo '

';
}

Here how it looks like:


text:
Q: Why does dG delete only one line of text in VIM? Instead delete text to end of file, d + G delete only one line of text in VIM on my computer.
What might go wrong?

A: You can quickly execute the command without mappings via :normal! (note the !):
:normal! dG

If that works (it should), the culprit is a mapping. You can check via
:verbose nmap d
:verbose omap G

(d is invoked from normal mode and this enters operator-pending mode.)
The command will also tell you where the bad mapping is defined, so that you can remove / correct it.


text:
Q: Error when sending email from localhost using php I'm trying to send some email from localhost XAMPP to outlook mail but it only display "Error" message. My code is working properly in web server side.
I'm using 64 bit. I follow the instruction properly, how to set up sending email using XAMPP.
Sometimes the email sent but mostly it's not and always "connection timeout". Even if it display email "sent", i didn't receive any email.
How to fix this?
Here's the php.ini
 SMTP = smtp.live.com
 smtp_port = 587
 sendmail_from = same email as sendmail.ini
 sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

sendmail.ini
 smtp_server=smtp.live.com
 smtp_port=587
 auth_username=outlook email
 auth_password=********
 force_sender=outlook email

My email php
error_reporting(E_ALL);
ini_set('display_errors', 1);

/* Email Detials */

$mail_to      = "email";
$from_mail    = "email";
$from_name    = "title";
$reply_to     = "";
$subject      = "subj...";
$message_body = "";

/* Attachment File
Attachment location */

$file_name = "filename.xml";
$path = "C:/xampp/htdocs/Email/";

// Read the file content

$file      = $path . $file_name;
$file_size = filesize($file);
$handle    = fopen($file, "r");
$content   = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));

/* Set the email header
Generate a boundary */

$boundary = md5(uniqid(time()));

// Email header

$header = "From: " . $from_mail . " \r\n";
$header .= "Reply-To: " . $reply_to . "\r\n";
$header .= "MIME-Version: 1.0\r\n";

// Multipart wraps the Email Content and Attachment
$header .= "Content-Type: multipart/mixed;\r\n";
$header .= " boundary=\"" . $boundary . "\"";

$message_body .= "This is a multi-part message in MIME format.\r\n\r\n";
$message_body .= "--" . $boundary . "\r\n";

/* Email content
Content-type can be text/plain or text/html */

$message_body .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message_body .= "Content-Transfer-Encoding: 7bit\r\n";
$message_body .= "\r\n";
$message_body .= "$message_body\r\n";
$message_body .= "--" . $boundary . "\r\n";

/* Attachment
Edit content type for different file extensions */

$message_body .= "Content-Type: application/xml;\r\n";
$message_body .= " name=\"" . $file_name . "\"\r\n";
$message_body .= "Content-Transfer-Encoding: base64\r\n";
$message_body .= "Content-Disposition: attachment;\r\n";
$message_body .= " filename=\"" . $file_name . "\"\r\n";
$message_body .= "\r\n" . $content . "\r\n";
$message_body .= "--" . $boundary . "--\r\n";

// Send email
if (mail($mail_to, $subject, $message_body, $header)) {
    echo "Sent";
} else {
    echo "Error";
}

A: Does your machine has access to port 587 ?. (you can try with telnet or putty). If the port is closed you should take a look at your firewall or your router.


text:
Q: php, phpMyAdmin - dropdown values not inserting into database I'm trying to add the values, that I pick from the dropdown menus (see HTML), to a database table.
Yet this is not working out like I planned.
I'm I doing something wrong?
At the moment the columns for the dropdown values are set as INT in the table of the database.
Code below:
HTML:

    <meta charset ="UTF-8">
    <title>El Gusto - Sigaren toevoegen</title>

    <form action="handler.php" method="post">

        Sensatie in de mond:

                Lip:
                    <select>
                        <option value="1" name="sensatie_lip_1">1</option>
                        <option value="2" name="sensatie_lip_2">2</option>
                        <option value="3" name="sensatie_lip_3">3</option>
                        <option value="4" name="sensatie_lip_4">4</option>
                    </select>

                Tong:
                    <select>
                        <option value="1" name="sensatie_tong_1">1</option>
                        <option value="2" name="sensatie_tong_2">2</option>
                        <option value="3" name="sensatie_tong_3">3</option>
                        <option value="4" name="sensatie_tong_4">4</option>
                    </select>

                Wangen:
                    <select>
                        <option value="1" name="sensatie_wangen_1">1</option>
                        <option value="2" name="sensatie_wangen_2">2</option>
                        <option value="3" name="sensatie_wangen_3">3</option>
                        <option value="4" name="sensatie_wangen_4">4</option>
                    </select>

                Keel:
                    <select>
                        <option value="1" name="sensatie_keel_1">1</option>
                        <option value="2" name="sensatie_keel_2">2</option>
                        <option value="3" name="sensatie_keel_3">3</option>
                        <option value="4" name="sensatie_keel_4">4</option>
                    </select>

    PRESENTATIE (SIGARENBAND, DOOS, ...)

        <select>
            <option value="1" name="presentatie_1">1</option>
            <option value="2" name="presentatie_2">2</option>
            <option value="3" name="presentatie_3">3</option>
            <option value="4" name="presentatie_4">4</option>
            <option value="5" name="presentatie_5">5</option>
        </select>

    KWOTERING

        <select>
            <option value="1" name="kwotering_1">1</option>
            <option value="2" name="kwotering_2">2</option>
            <option value="3" name="kwotering_3">3</option>
            <option value="4" name="kwotering_4">4</option>
            <option value="5" name="kwotering_5">5</option>
        </select>

    <input type='submit' name="Toevoegen" value='Toevoegen'>

    </form>

PHP:
//WARM - SENSATIE IN DE MOND (DROPDOWN)
    //LIP
    $sensatie_lip_1 = isset($_POST['sensatie_lip_1']);
    $sensatie_lip_2 = isset($_POST['sensatie_lip_2']);
    $sensatie_lip_3 = isset($_POST['sensatie_lip_3']);
    $sensatie_lip_4 = isset($_POST['sensatie_lip_4']);

    //TONG:
    $sensatie_tong_1 = $_POST['sensatie_tong_1'];
    $sensatie_tong_2 = $_POST['sensatie_tong_2'];
    $sensatie_tong_3 = $_POST['sensatie_tong_3'];
    $sensatie_tong_4 = $_POST['sensatie_tong_4'];

    //WANGEN:
    $sensatie_wangen_1 = $_POST['sensatie_wangen_1'];
    $sensatie_wangen_2 = $_POST['sensatie_wangen_2'];
    $sensatie_wangen_3 = $_POST['sensatie_wangen_3'];
    $sensatie_wangen_4 = $_POST['sensatie_wangen_4'];

    //KEEL:
    $sensatie_keel_1 = $_POST['sensatie_keel_1'];
    $sensatie_keel_2 = $_POST['sensatie_keel_2'];
    $sensatie_keel_3 = $_POST['sensatie_keel_3'];
    $sensatie_keel_4 = $_POST['sensatie_keel_4'];

//PRESENATIE (DROPDOWN)
$presentatie_1 = $_POST['presentatie_1'];
$presentatie_2 = $_POST['presentatie_2'];
$presentatie_3 = $_POST['presentatie_3'];
$presentatie_4 = $_POST['presentatie_4'];
$presentatie_5 = $_POST['presentatie_5'];

//KWOTERING (DROPDOWN)
$kwotering_1 = $_POST['kwotering_1'];
$kwotering_2 = $_POST['kwotering_2'];
$kwotering_3 = $_POST['kwotering_3'];
$kwotering_4 = $_POST['kwotering_4'];
$kwotering_5 = $_POST['kwotering_5'];

//DATABASE
$connect = mysql_connect("localhost", "root", "") or die ("Couldn't connect to the database!");
mysql_select_db("el_gusto") or die ("Couldn't find db!");

$query = mysql_query("INSERT INTO sigaren(sensatie_lip_1, sensatie_lip_2, sensatie_lip_3, sensatie_lip_4, sensatie_tong_1, sensatie_tong_2, sensatie_tong_3, sensatie_tong_4, sensatie_wangen_1, sensatie_wangen_2, sensatie_wangen_3, sensatie_wangen_4, sensatie_keel_1, sensatie_keel_2, sensatie_keel_3, sensatie_keel_4, presentatie_1, presentatie_2, presentatie_3, presentatie_4, presentatie_5, kwotering_1, kwotering_2, kwotering_3, kwotering_4, kwotering_5) VALUES
('$sensatie_lip_1',
'$sensatie_lip_2',
'$sensatie_lip_3',
'$sensatie_lip_4',
'$sensatie_tong_1',
'$sensatie_tong_2',
'$sensatie_tong_3',
'$sensatie_tong_1',
'$sensatie_wangen_1',
'$sensatie_wangen_2',
'$sensatie_wangen_3',
'$sensatie_wangen_4',
'$sensatie_keel_1',
'$sensatie_keel_2',
'$sensatie_keel_3',
'$sensatie_keel_4',
'$presentatie_1',
'$presentatie_2',
'$presentatie_3',
'$presentatie_4',
'$presentatie_5',
'$kwotering_1',
'$kwotering_2',
'$kwotering_3',
'$kwotering_4',
'$kwotering_5')");

if($query) {
    echo "Toevoeging gelukt!";
}
else{
    echo mysql_error();
}

?>

A: instead of giving name to option tag give name to select tag.
Currently you are not getting the values of dropdown after submitting the form

A: HTML:
<select name="sensatie_lip">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

PHP:
$sensatie_lip = $_POST['sensatie_lip']; // you will get your selected value

A: Rightly said by Disha and Jasbir,Select way used is incorrect and try changing it as suggested and see that to work
 <select name="sensatie" >
                    <option value="1">sensatie_wangen_1</option>
                    <option value="2">sensatie_wangen_2</option>
 </select>

So it will display 2 drop down as sesatie_wangen_1, 2 and on save db will have value 1, or 2. It is a hint and you need to adjust code to make it work based on this


text:
Q: Is a nested loop always reset after its last iteration? When the nested loop is done looping, is the variable j going to be reset back to zero? I assume it is, because we start from the beginning again, but I want to make sure that all you experts out there agree with me. Also, where can I find the answer to this in textbooks and not here?
const userTextInput = "Hello my name is Luka";
const vowels = ["a", "e", "u", "e", "i"];

for(let i = 0; i <= userTextInput.length; i = i + 1){
  for(let j = 0; j <= vowels.length; j = j + 1){
    if(userTextInput[i] === vowels[j]){
      console.log(vowels[j]);
    }
  }
}

A: Technically, not quite. When the nested lop finishes, j will not be defined. Only when it starts again (for the next iteration of i), will j then be reset.
For example, the below will give you a j is not defined error.

for (let j = 0; j < 5; j++)
  ;
console.log(j);

A: The following steps may help you to understand the code:

*

*The variable j is only present inside the the nested loop.

*When the nested loop ends means j <= vowels.length becomes false the code exits the loop.

*At this point there is no j. j is destroyed.

*Now the outer for loop in continued again and i is incremented.

*This time a new variable j is again created and initialized to 0.

*This happens while i <= userTextInput.length; is true

A: Just to be clear, the loop isn't doing anything special here. You are resetting the variable every time you enter the loop.
A for loop has 3 parts (for (1; 2; 3) {}):

*

*Run once before starting the loop

*Condition to check if the loop body should be executed

*Code to execute after each iteration

So, when you are doing this:
for (let j = 0; j < 5; j++) {}

You are declaring and j and setting it to 0. This always happens before you enter the loop. Then, the loop body is executed while j is less than 5, and after every iteration j is incremented by 1.
Because you declared j in the for statement, it only exists within the for loop. When you exit the loop, the variable is gone.
However, even if the variable would still exist outside the loop, you would reset it the next time you enter the loop again, because you're doing j = 0.
In this example I'm declaring the variable outside the for loop, so it still exists outside the loop:
let j = 0;

for (let i = 0; i < 5; i++) {
    for (; j < 5; j++) {
        console.log(`iteration ${j}`);
    }
}

console.log(i);
console.log(j);

// Prints:
// iteration 0
// iteration 1
// iteration 2
// iteration 3
// iteration 4
// undefined
// 4

I've omitted the first part of the for loop, so j is never reset. This causes the inner loop to only run 5 times, which would be 25 times if the variable would be reset every time.

A: Yes it is set back to the value you initialized it, everytime the loop starts. For your case, yes it is 0.


text:
Q: How to change my class render based on Props? I am currently creating a form. There is a textInput. I want to show a disabled dropdown select if the user write a incorrect postcode. If the user writes a correct postcode, the dropdown will be enabled and request data from a restful API.
The problem is: I am sending a props "disabled", but apparently it is not working.
class SelectJob extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            jobList:[],
            selectedJob:'default',
            loading:false,
            disabled:true
        }
        this.getJobs = this.getJobs.bind(this);
        this.jobHandler = this.jobHandler.bind(this);

    }

.
.
.

componentDidMount(){
            this.getJobs();
            this.setState({disabled:this.props.disabled});
};

render(){
        return(
            <MDBRow>
                <MDBCol sm="2">
                    {this.state.loading && <FontAwesomeIcon className="align-middle" spin icon={faSpinner}/>}
                </MDBCol>
                <MDBCol>
                    <select
                        disabled={this.state.disabled == true ? true : false}
                        id="jobId"
                        className="browser-default custom-select"
                        onChange={this.jobHandler}
                        value={this.state.selectedJob}>

                        <option disabled value="default">Profissão</option>
                        {!this.state.loading && this.state.jobList.map(
                            (job) => <option value={job.code} key={job.code}>{job.desc}</option>)
                        }
                    </select>
                </MDBCol>
            </MDBRow>
        )
    }

No errors, but disabled does not work.
It remains enabled.
render(){
        let selectJobAlias;

        if (this.state.setted === true){
            selectJobAlias = <SelectJob disabled="false" addressPostCode={this.state.addressPostCode}/>
        }
        else {
            selectJobAlias = <SelectJob disabled="true" addressPostCode={this.state.addressPostCode}/>
        }

A:     <select
 disabled={this.state.disabled ? true : null}
                            id="jobId"
                            className="browser-default custom-select"
                            onChange={this.jobHandler}
                            value={this.state.selectedJob}>

A: It would be much easier if you used the props directly than deriving a state for it.
<select
    disabled={this.props.disabled}
    id="jobId"
    className="browser-default custom-select"
    onChange={this.jobHandler}
    value={this.state.selectedJob}>

    <option disabled value="default">Profissão</option>
    {!this.state.loading && this.state.jobList.map(
        job => <option value={job.code} key={job.code}>{job.desc}</option>
    )}

</select>

and make sure you send boolean instead of string like this
<SelectJob disabled={false} addressPostCode={this.state.addressPostCode}/>

In case you do want to derive a state variable based on your props you should use getDerivedStateFromProps() lifecycle method.

A: There does not appear to be a need to maintain the state of disabled in your child component, which in this case is SelectJob. Rather, based on the code provided, it appears that whether the select is disabled can be handled using only props passed from your parent component (which is what I assume you are pointing to in the second render snippet).
    class ParentComponent extends React.Component {
        constructor(props) {
           this.state = { selectDisabled: true };
        }

        handlePostalCodeOnChange = e => {
          const isValid = // by your logic determine whether postal code is valid
          this.setState({ selectDisabled: !isValid });
        }

        render(){
            return (
               // Pass any other necessary props
               <SelectJob selectDisabled={this.state.selectedDisabled} />
            )
        }
    }

Then, in your child component -- SelectJob -- simply look to the passed prop of selectDisabled to determine whether the select should be disabled (Note: I've adopted selectDisabled for a bit of clarity in our naming conventions).
Passing new props in this instance should trigger a re-render. Generally, as a rule of thumb, if you can achieve your functionality without the need for maintaining separate or additional state, and can rely on props, you should do so (see Step 3 in 'Thinking in React').
    <select
        disabled={this.props.selectDisabled}
        // Remainder of your code here
    >
    ....
    </select>

Finally, without seeing additional code, your functionality would not qualify as one of the 'rare' instances where getDerivedStateFromProps should be implemented.


text:
Q: how to update an array from input box in php mysql This is my code:
$uid=$_POST['uid'];
$fields = '';
if($uid==1){
//having some error in this line
   foreach($query as $key => $value) {
    if ($i++ != 0) $fields .= ', ';
    $key = mysql_real_escape_string($key);
      $value = mysql_real_escape_string($value);
      $fields .= "$key = $value";
      }
$query = mysql_query("UPDATE 2mcom SET $fields");
   }

  echo "
" ;
$result = mysql_query("select * from 2mcom where roll_no='138218600004'");
$i=1;

while (false != ($data = mysql_fetch_array($result, MYSQL_ASSOC)))
  foreach ($data as $key => $value)
  //echo "$key: $value
";
  {
  echo "
";
    echo "$key: ";
  echo "	";
    echo '<form method="post" action="">';
    echo "";
    echo '<input type="text" name="fld'.$i.'" value="'.$value.'"/>';
    echo '<input type="hidden" name="uid" value="1"/>';
     $i++;
     echo "
";
  }
  echo "
";
   echo'<input type="submit" name="submit" value="submit"/>';

  echo "
	";
    echo'</form>
';

I want to update this table 2mcom from the input text-box. Here i am fetching the field-name along with their values in input field from table "2mcom" using array.. now i want to update the field after editing.it is for result correction .

A: This should give your text field a name, then you can do separate UPDATE queries to update each field individually.
UPDATE, consolidated version of previous code:
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
    foreach($row as $key => $value) {
        $name = 'field';
        $id = $row['id']; //rename this with your row id, this will give you identifiable input names
        echo '
';
        echo $key . ': ';
        echo '	';
        echo '<form method="POST">';
        echo '';
        echo '<input type="hidden" name="id[]" value="'. $row['id'] .'"/>';
        echo '<input type="hidden" name="column[]" value="'. $key .'"/>';
        echo '<input type="text" name="field[]" value="'. $value .'"/>';
        echo '
';
    }
    $i++;
}

UPDATE QUERY:
function update_table($table, $col, $value, $id) {

    global $link; //mysqli object

    //escape values
    $value = mysqli_real_escape_string($link, $value);
    $col = mysqli_real_escape_string($link, $col);

    //update the database field
    $query = "UPDATE `$table` SET `$col` = '$value' WHERE `roll_id` = '$id'";
    mysqli_query($link, $query) or die(mysqli_error($link));

    return true;

}

CONTROLLER:
if(isset($_POST['submit'])) {

    $col_count = count($_POST['column']);
    $field_count = count($_POST['field']);

    if($field_count == $col_count) {
    } else {
        trigger_error("Col - Field mismatch", E_USER_ERROR);
    }

    for($i=0; $i<count($_POST['column']); $i++) {
        if(!update_table($table, $_POST['column'][$i], $_POST['field'][$i], $_POST['id'][$i])) {
            trigger_error("Error updating field", E_USER_ERROR);
        }
    }

}

Try that.


text:
Q: ajax form select update not working with jNice being new to jquery and ajax, i have a small problem that i am sure has an easy fix! i have a form select updating from a DB call using jquery and ajax, when i wrap the form with jNice the ajax update stops working. I have searched around and found that using the $.jNice.SelectUpdate function should resolve the issue but have not be able to get it to work, any assistance would be appreciated.
Edited with code:
function getLocation() {
$.ajax({
    type:"POST",
    url: "formdata.asp",
    dataType: "application/x-www-form-urlencoded",
    data: "Action=GetLocation&Val=" + $("#area").val(),
    async: false,
    success: function(msg){
        $("label[id$=Two]").add("select[id$=Two]").remove();
        $("#loclist").append(msg);
    }
})
}

(without the jNice class the 2nd form select updates)
<form class="jNice" method="post" action="searchresults.asp">
<fieldset id="loclist">
<legend id="lgdloclist" title="Locations">Locations</legend>
Select an Option:
    <select id="area" style="width:175px; display:block;">
    <option value="">Choose..</option>
    <option value="hse">HSE</option>
    <option value="nvq">NVQ</option>
    <option value="made4">Made4</option>
</select>

</fieldset>
<input type="submit" name="submit" value="Search" />
</form>

A: You need to do two things in your ajax success method:
(1) Update the selects list of options using something like this (here's some useful information about updating selects:
var selectEl = $("#area").get(0);
select.options[selectEl.options.length] = new Option("1234", "1234");

You'll need to put the data from your $.ajax call in the Option constructor.
(2) Call jNice's SelectUpdate function:
$.jNice.SelectUpdate(selectEl);

Check out a simple example here (a new option is added when you click "search"): http://jsfiddle.net/andrewwhitaker/w5wwy/


text:
Q: I keep getting unitialized variable used for interestRate, numberOfPayments, and loanAmount Sarah Connors is fName and lName, 10000 is loanAmount 12 interestRate and 3 is the number of years for the loan, this is all located in "Lab4Data.txt"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    string fName, lName;

    double interestRate, loanAmount, monthlyPayment, totalPayed, interestAmount,

    double numberOfPayments

    ifstream input;

    ofstream output;

    input.open("Lab4Data.txt");
    output.open("Kirklandlab4results.txt");
    interestRate = interestRate / 12;
    interestRate = interestRate / 100;
    numberOfPayments = numberOfPayments * 12;

    monthlyPayment = loanAmount * interestRate
            * pow(loanAmount + interestRate, numberOfPayments)
            / pow(loanAmount + interestRate, numberOfPayments) - 1; //equation to get monthly payment
    totalPayed = monthlyPayment * numberOfPayments;
    interestAmount = interestRate * numberOfPayments;

    input >> fName >> lName;
    output << "Name:" << fName << " " << lName;

    input >> loanAmount;
    output << "Loan Amount:" << loanAmount << endl;

    input >> interestRate;
    output << "Monthly Intrest Rate:" << interestRate << endl;

    input >> numberOfPayments;
    output << "Number Of Payments:" << numberOfPayments << endl;

    output << "Monthly Payment:" << monthlyPayment << endl;
    output << "Total Amount Payed:" << totalPayed << endl;
    output << "Interest Amount:" << interestAmount << endl;

    output.close();

    return 0;
}

im trying to figure out why its telling me that im getting unitialized variable used for interestRate, numberOfPayments, and loanAmount. I am new to C++ and need help.

A: In these statements
interestRate = interestRate/12;
interestRate = interestRate / 100;
numberOfPayments = numberOfPayments * 12;
monthlyPayment = loanAmount * interestRate;

there are used uninitialized variables
double interestRate, loanAmount, monthlyPayment, totalPayed, interestAmount,

double numberOfPayments;

that invokes undefined behavior.
For example what is the value of the variable interestRate in this expression interestRate/12? As the variable was not initialized (neither value was assigned to it in its declaration) it contains some garbage.


text:
Q: Angular 2 tests karma. What exactly to test I am trying to learn how to create tests for angular 2 (typescript files) using karma-jasmine. My doubt is, to test the component.ts files, I only can test the methods that I call at HTML file or I can test all of then?
For example: I have this model file modal.nota.component.ts
    import { Component, Input, Output, EventEmitter } from '@angular/core';
    import { Nota } from './nota.model'

    @Component({
      moduleId: module.id,
      selector: 'modal-nota',
      templateUrl: 'modal.nota.component.html'
    })
    export class ModalNotaComponent {

      test : boolean = true;

      setFalse(test) {
        this.test = false;
        return test;
      }
  }

And I don't call the method 'setFalse' in my HTML file, but I want to test him. How can I call and test the method in my spec file?
modal.nota.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';

import { ModalNotaComponent } from '../modal.nota.component';

describe('Test of test variable', () => {

  let component: ModalNotaComponent;
  let fixture: ComponentFixture<ModalNotaComponent>;
  beforeEach(() => {
    TestBed.compileComponents(); // ModalNotaComponent test instance
    TestBed.configureTestingModule({
      declarations: [ ModalNotaComponent ], // declare the test component
    });

    fixture = TestBed.createComponent(ModalNotaComponent);
    component = fixture.componentInstance;
  });

  it('Should show that the value of test variable is true', () => {
    expect(component.test).toBe(true);
  });

  it('Should test setFalse method', () => {
    let r = null;
    let t = true;
    r = component.setFalse(t);
    expect(r).toBe(false);
  });

});

This test is not working. I am getting this errors
photo of the errors

A: After some search I found how to call methods and variables from component.ts file, (service, modal, whatever). All you have to do is instantiate the class in your test. Here is the new test file:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';

import { ModalNotaComponent } from '../modal.nota.component';

describe('Test of test variable', () => {

  beforeEach(() => {

    this.modalNota = new ModalNotaComponent();
  });

  it('Should show that the value of test variable is true', () => {
    expect(this.modalNota.test).toBeTruthy()
  });

  it('Should test setFalse method', () => {
    let r = null;
    let t = true;
    r = this.modalNota.setFalse(t);
    expect(r).toBeFalsy()
  });

});

Credits to: Live chat Developers Blog - Testing Angular 2 apps Part 2: Dependency Injection and Components

A: After scaffolding out a new Angular 2 project and fiddling with this a bit, I was able to get the test to run successfully. Here are a few things to check:
1. Check Zone.js Version
After the initial scaffold I would run the tests with your code, and I was getting a strange error:
TypeError: Cannot set property 'stack' of undefined

I was then able to fix this by upgrading zone.js from 0.7.2 to 0.7.4 like so:
npm install --save zone.js@0.7.4

2. Check Your Vars In The "setFalse" Method
After it compiled properly, I was still getting an error, "Expected false to be true". Take a look at your setFalse method:
setFalse(test) {
    this.test = false;
    return test;
}

Note that test and this.test are NOT referring to the same variable. When you say "this.test" it is referring to the class level variable test that is declared above this function. Keep in mind that scoping is different in TypeScript vs JavaScript.
Hopefully this helps. Good luck!


text:
Q: machine froze during upgrade to 12.04 I tried upgrading from 11.10 to 12.04.  It got to the point of installing packages then I stepped away.  When I got back the screen was black (possibly due to the screen saver).  I left it for about 8 hours and there was no change.  I then power-cycled and now it won't boot to a login screen.  I tried hitting <Esc> repeatedly while powering up (to get to the Grub menu) but that has no effect.
What should I do now?
EDIT:
I can see the files on the hard disk once I boot from a Live CD.  I saw some stuff online about using chroot and dpkg to continue an aborted upgrade from the command line.  Is there any comprehensive guide on this?

A: The original poster here, SplashHit, indicated in a comment that this question on SuperUser answered the question.

*

*In that question, the OP followed this "guide" posted on Launchpad (which is actually the original version of this bug report by TJ).

*rumtscho, the OP of that SuperUser question, had attempted to chroot into the installed system from a live CD system and run dpkg --configure -a, but there were lots of Permission denied error messages.

*The accepted answer (by Darth Android) was that the OP needed to mount the /proc and /dev filesystems in the chroot before running dpkg ....
It's unclear from SplashHit (the original poster here)'s comment whether the Launchpad "guide" was sufficient to solve this problem here, or if the answer to that question was also necessary.
In any case, it appears that this question is now effectively answered for the OP (and abandoned).
@SplashHit, if I am mistaken and you still need help with this problem, please let us know (you can post a comment here, and of course if there is additional information then you can add that to your question).

A: Try holding down Shift to get to the GRUB2 menu. If that works, see if you can boot any of the options. (You can then provide more information in your question.)
If that doesn't work, or you do get a GRUB2 menu but you can't boot into Ubuntu, try reinstalling the GRUB2 boot loader to your Master Boot Record (MBR), using any of these methods.
Once you've booted into Ubuntu, you can attempt to repair and finish the upgrade by running  sudo apt-get dist-upgrade.

A: About using chroot, you can take a look at this Gentoo guide:

*

*Chroot from a livecd
It says how you can reinstall grub, but you can run dpkg --configure -a instead of grub2-install.
The main idea of the chroot approach is to mount your original / partition on the live CD filesystem, probably on /mnt/mysystem, then chroot to /mnt/mysystem. After chrooting, your / will be actually /mnt/mysystem, your original /. It's like you CHanged your ROOT.


text:
Q: Destroying jQuery Flot Graph What is the correct way to destroy a jQuery flot graph in a way that will clean up all event handlers and not result in a memory leak?
It seems flot is leaving behind some zombies (aka Detached Dom Trees)

A: If you read the API docs, there is a shutdown method that cleans up for you
shutdown()

Cleans up any event handlers Flot has currently registered. This
is used internally.

eg.
var plot = $.plot($("#yourDiv"), options)

plot.shutdown()

A: For people who come here in the future, there is now a destroy function that calls shutdown and removes the canvas element. It's undocumented in the API for some reason, but is available in the code:
var flot = $("#FlotDiv").data('plot')
if (flot) // If it's destroyed, then data('plot') will be undefined
    flot.destroy();

A: if you want to remove event handlers then try jquery off method.
for to clear flot graph.  you can empty the div.
$('#yourFlotDiv').empty();

A: To remove the flot Graph
var placeholder = $("#FlotDiv");
placeholder.unbind(); //Remove a previously-attached event handler from the elements.
placeholder.empty();

Also in case you wish to unbind specific event this is the way to go :
$( "#foo").unbind( "click" );

For more info check this out.


text:
Q: ValidationException when using Table AggregateFunction and ResultTypeQueryable I'm using a local Flink 1.6 cluster configured to use the flink-table jar
(meaning my program's jar does not include flink-table).
With the following code
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.ResultTypeQueryable;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.java.BatchTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.types.Row;

import java.util.ArrayList;
import java.util.List;

public class JMain {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment execEnv = ExecutionEnvironment.getExecutionEnvironment();
        BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(execEnv);

        tableEnv.registerFunction("enlist", new Enlister());

        DataSource<Tuple2<String, String>> source = execEnv.fromElements(
                new Tuple2<>("a", "1"),
                new Tuple2<>("a", "2"),
                new Tuple2<>("b", "3")
        );

        Table table = tableEnv.fromDataSet(source, "a, b")
                .groupBy("a")
                .select("enlist(a, b)");

        tableEnv.toDataSet(table, Row.class)
                .print();
    }

    public static class Enlister
            extends AggregateFunction<List<String>, ArrayList<String>>
            implements ResultTypeQueryable<List<String>>
    {
        @Override
        public ArrayList<String> createAccumulator() {
            return new ArrayList<>();
        }

        @Override
        public List<String> getValue(ArrayList<String> acc) {
            return acc;
        }

        @SuppressWarnings("unused")
        public void accumulate(ArrayList<String> acc, String a, String b) {
            acc.add(a + ":" + b);
        }

        @SuppressWarnings("unused")
        public void merge(ArrayList<String> acc, Iterable<ArrayList<String>> it) {
            for (ArrayList<String> otherAcc : it) {
                acc.addAll(otherAcc);
            }
        }

        @SuppressWarnings("unused")
        public void resetAccumulator(ArrayList<String> acc) {
            acc.clear();
        }

        @Override
        public TypeInformation<List<String>> getProducedType() {
            return TypeInformation.of(new TypeHint<List<String>>(){});
        }
    }
}

I get this weird exception:
org.apache.flink.table.api.ValidationException: Expression Enlister(List('a, 'b)) failed on input check: Given parameters do not match any signature.
Actual: (java.lang.String, java.lang.String)
Expected: (java.lang.String, java.lang.String)

However, if I do not implement ResultTypeQueryable,
I get the expected output:
Starting execution of program
[b:3]
[a:1, a:2]
Program execution finished
Job with JobID 20497bd3efe44fab0092a05a8eb7d9de has finished.
Job Runtime: 270 ms
Accumulator Results:
- 56e0e5a9466b84ae44431c9c4b7aad71 (java.util.ArrayList) [2 elements]

My actual use case seems to require ResultTypeQueryable,
because otherwise I get this exception:
The return type of function ... could not be determined automatically,
due to type erasure. You can give type information hints by using the
returns(...) method on the result of the transformation call,
or by letting your function implement the 'ResultTypeQueryable' interface

Any way I can fix this?

A: Implementing ResultTypeQueryable is not correct in this case. The exception is misleading. Instead override getResultType() and getAccumulatorType(). The reason behind this is that generics usually cause problems (due to Java's type erasure) when generating the type information for serializers.

A: I tried to reproduce the problem in a small program but I couldn't,
it only happens in my larger project.
Unfortunately, overriding getResultType() and getAccumulatorType() didn't help either,
I got this exception in that case:
java.lang.IndexOutOfBoundsException
    at org.apache.flink.api.java.typeutils.TupleTypeInfoBase.getTypeAt(TupleTypeInfoBase.java:199)
    at org.apache.flink.api.java.typeutils.RowTypeInfo.getTypeAt(RowTypeInfo.java:179)
    at org.apache.flink.api.common.operators.Keys$ExpressionKeys.isSortKey(Keys.java:444)
    at org.apache.flink.api.java.operators.SortPartitionOperator.ensureSortableKey(SortPartitionOperator.java:150)
    at org.apache.flink.api.java.operators.SortPartitionOperator.<init>(SortPartitionOperator.java:75)
    at org.apache.flink.api.java.DataSet.sortPartition(DataSet.java:1414)

I actually also got that exception even without overriding.
The only thing that worked for me was essentially:
String[] fieldNames = new String[] {
        "result"
};
TypeInformation<?>[] types = new TypeInformation[] {
        TypeInformation.of(new TypeHint<List<String>>(){})
};

tableEnv.toDataSet(table, Types.ROW(fieldNames, types))...


text:
Q: Las flechas de incremento personalizadas en input no funcionan! ¿Cómo recoger el valor de entrada a través de botones? Al principio de mi aplicación, usando las flechas de entrada o el teclado, mis datos eran enviados sin ningún problema. Queriendo hacer la interfaz de usuario más amigable decidí ocultar las flechas del navegador e implementar botones para agregar y restar en el mismo input. Tengo en mi html los siguientes dos elementos. Uno es el input para determinar la unidad a añadir a un carro y el otro elemento es un botón que debe enviar esa información a otro componente

        -
        <input type='number' placeholder='0' [(ngModel)]='item.quantity' (change)='this.updateCart(item)' min='0'>
        +

        <button class='cart' (click)='addItem()'></button>

y esta es mi funcion
 updateCart(item, idProduct) {
    console.log(item);
    this.cart.updateItem(item);
    this.eCart.next(this.cart.getCart());
  }

Si modifico la cantidad del input con el teclado obtengo los datos sin ningún problema para mi función 'updateCart()'. Pero el problema viene con los botones 'plus' y 'minus' y el botón de clase 'cart', ya que no sé cómo hacer que recoja los datos de la misma manera
¿Alguien que pueda darme una idea de lo que debo hacer? Gracias de antemano.

A: Una manera de resolver esto puede ser asi:
Para el boton de menos:
(click)="item.quantity = item.quantity-1; this.updateCart(item)"

Para el boton de mas:
(click)="item.quantity = item.quantity+1; this.updateCart(item)"

Te dejo un ejemplo funcional aqui


text:
Q: run a script using windows cmd with predefiden stdinput at the time of execution Say I have a python script that is similar to following:
name = input("what is your name?")
age = input("what is your age?")
print name, age

How can we execute that from from windows cmd with predefined name and age as input?
I have tried following:
python t23.py > x.txt | echo "sadaf" & echo "12"

A: @ECHO OFF
SET /P name=Enter your name:
SET /P age=Please enter your age:
python t23.py name age 2>&1 | tee output_file.txt

I am not tested it before this code but i think you will get some clue on my code ....


text:
Q: How to stop page from reloding each time a dropdown menu is selected I am working on a website and I have a design issue coming up. I have a navigation bar where 3 dropdowns are present. Whenever I click on the dropdown and select an item, the page completely reloads and the whole structure of webpage fully refreshes and need to scroll down again and again for checking that clicked option. Is there something that can stop it from reloading each time and when a menu item is clicked the page stays right at there?

A: Don't use About
Use About
If you point the href to an html file then it will reload the page but if you use a section's id then it will go to that section of the page without reloading.


text:
Q: LMER: Error in model.frame.default… variable lengths differ (Without NA's) I've looked through a couple of other questions similar to mine, and the one most relevant wasn't answered, while the others all came down to missing data and data lengths.
I am trying to model compositional dissmiliarity after a disturbance through time. I sampled at discrete timepoints: 0, 3, 6, and 9 months. I am interested in the fixed effect of time on recovery, but at each point, season and other environmental variables changed and led to differing variability between 0, 3, 6, and 9 months, as reflected in the residuals in a normal linear model.
To incorporate the random variance differences, while still including the fixed effect, I ran this model using nlme:
mod1 <- lme(Resp ~ Temp + Time, random = (~1 | Dummy),
           weights = varIdent(form = ~1 | Time.f), data = recovery)

where Resp is my dissimilarity; Temp is a disturbance intensity (temperature), Time is 0, 3, 6, or 9 months; Dummy is a dummy random intercept (here just a vector filled with "D"); and Time.f is Time converted to a factor. I have 60 data points, 15 in each of the sampling times.
This ran fine. I want to extract conditional-R2 values, however, so tried it in lme4 using the lmer function:
mod2 <- lmer(Resp ~ Temp + Time + (1 | Dummy), weights = varIdent(form = ~1 | Time.f), data = recovery)

To run lmer, the dummy variables needs at least two categories, so I changed the first value to a "C" for the sake of trying to run it (see data below). I get the error:

Error in model.frame.default(data = recovery, weights = varIdent(form
  = ~1 |  :    variable lengths differ (found for '(weights)')

I'm new to variance structures and I'm not sure if it's a problem in the fundamental structure of this model. In this question, Alain Zuur implied that it is incorrect to use varIdent with binomial models, but I'm running this as a Gaussian (though I've also considered a Gamma).
Here is my data:
recovery <- data.frame(Resp = c(0.451342292, 0.518351745, 0.469268304,
 0.472750101, 0.498935251, 0.508081111, 0.490904624, 0.446764424, 0.536142651,
0.707955998, 0.403299657, 0.495046237, 0.630677117, 0.630420366, 0.511555117,
0.460977339, 0.313873121, 0.442930551, 0.504933216, 0.266894217, 0.461051448,
0.406211728, 0.500511806, 0.561122944, 0.490329006, 0.565621645, 0.612263178,
0.380895252, 0.358544132, 0.40361619, 0.296853964, 0.364686954, 0.299307408,
0.349446067, 0.288854758, 0.292265106, 0.37207794, 0.300760264, 0.387906769,
0.376203541, 0.433080559, 0.371204216, 0.341724067, 0.357920013, 0.396109361,
0.372228087, 0.282725524, 0.317789872, 0.244435419, 0.277035603, 0.272620508,
0.378162153, 0.267645891, 0.306363131, 0.353826191, 0.230613947, 0.445865256,
0.321665269, 0.324131469, 0.266275828), Temp = c(25.4, 22.9, 22.5, 20.5, 29,
25.2, 40.5, 23.9, 28.1, 33.2, 43, 34.5, 38.5, 42.4, 31.3, 27, 28.6, 22.4, 24.2,
21.4, 22.6, 36.6, 28.8, 24.9, 28.6, 41.2, 21.5, 33, 39.8, 30.8, 22.2, 29.5,
25.9, 26.6, 22.8, 27.7, 24.9, 22.9, 27.6, 29, 26.7, 29.4, 43.5, 28.8, 23.1,
26.1, 25.7, 23.4, 29.4, 29.6, 23.7, 26.6, 31.7, 28.3, 28.5, 20.5, 23, 35.3,
42.5, 26.8), Time = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9), Dummy = c("C", "D", "D", "D",
"D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D",
"D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D",
"D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D", "D",
"D", "D", "D", "D", "D", "D", "D", "D"), Time.f = c("a", "a", "a", "a", "a",
"a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "b",
 "b", "b", "b", "b", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c", "c",
"c", "c", "c", "c", "c", "c", "c", "c", "c", "d", "d", "d", "d", "d", "d", "d",
"d", "d", "d", "d", "d", "d", "d", "d"))

Like I said, I'm new to this and to posting. Any advice or suggestions would be wonderful!


text:
Q: Laravel cache files - how to change default permission? My Laravel application is running under a 'webapps' user on an Ubuntu server. The app generates the cache files with 644 permissions and www-data user an group, for example:
releases/20170108203853/storage/framework/cache/f2/10/f210226bdc5c0df206579b805291fd55

I deploy using Rocketeer and the problem is that when deploying a new release, Rocketeer can't delete the old releases because it doesn't have permissions to remove the cache files as they're under www-data and 664. My webapps user is in www-data group so it wouldn't be a problem if those files would be created with 664. When the old release fails to be removed, for some reason after deploying, I can't see the new deployed release live, I still see the old one even though the 'current' release is pointing to the new deploy.
How do I setup Laravel or on Ubuntu level to have those files generated with the 664 permissions?


text:
Q: TSQL how to use if else in Where clause I want to create a report, the report will have parameter for the user to select
-IsApprovedDate
-IsCatcheDate

I would like to know how to used the if else in the where clause.
Example if the user selects IsApprovedDate the report will lookup based on approved Date else will lookup based on catch date. In my query I will get top10 fish size base on award order weight here is my query.
  ;WITH CTE AS
    (
        select  Rank() OVER (PARTITION BY c.trophyCatchCertificateTypeId order by c.catchWeight desc ) as rnk
                ,c.id,c.customerId, Cust.firstName + ' '+Cust.lastName as CustomerName
                ,CAST(CONVERT(varchar(10),catchWeightPoundsComponent)+'.'+CONVERT(varchar(10),catchWeightOuncesComponent) as  numeric(6,2) ) WLBS
                ,c.catchGirth,c.catchLength,ct.description county
               ,t.description award--
               ,c.trophyCatchCertificateTypeId
               ,s.specificSpecies--
               ,c.speciesId

         from Catches c
         INNER JOIN TrophyCatchCertificateTypes t on c.trophyCatchCertificateTypeId = t.id
         INNER JOIN Species s on c.speciesId = s.id
         INNER JOIN Counties ct on c.countyId = ct.id
         INNER JOIN Customers Cust on c.customerId = cust.id
         Where c.bigCatchCertificateTypeId is not null
               and  c.catchStatusId =1
         and c.speciesId =1 and c.isTrophyCatch =1
         and c.catchDate >= @startDay and c.catchDate<=@endDay

     )
    Select * from CTE c1
     Where rnk <=10

A: Just use conditional logic for this:
where . . . and
      ((@IsApprovedDate = 1 and c.ApprovedDate >= @startDay and c.ApprovedDate <= @endDay) or
       (@IsCatchDate = 1 and c.catchDate >= @startDay and c.catchDate <= @endDay)
      )

EDIT:
I would actually write this as:
where . . . and
      ((@IsApprovedDate = 1 and c.ApprovedDate >= @startDay and c.ApprovedDate < dateadd(day, 1 @endDay) or
       (@IsCatchDate = 1 and c.catchDate >= @startDay and c.catchDate < dateadd(day, 1, @endDay))
      )

This is a safer construct because it work when the date values have times and when they do not.

A: Performance will be much better if you build the WHERE clause dynamically in your code and then execute it.


text:
Q: How Can I Install libcrypto++6 (or libcrypto++8) and default-jre-headless how can I install "libcrypto++6 (or libcrypto++8)" with yocto? Normally, I would add debian source.list after installation and install it with apt, but it causes many problems. Likewise, I want to install "default-jre-headless". I use Kirkstone. I was adding those that do not have such recipes from the source code, but the source code of these is difficult to find and I did not know how to make the recipes. Below is a recipe I found for libcrypto++6, but it doesn't work.
HOMEPAGE = "http://www.cryptopp.com/wiki/Main_Page"
BUGTRACKER = "http://sourceforge.net/apps/trac/cryptopp/"
SECTION = "libs"

LICENSE = "BSL-1.0"
LIC_FILES_CHKSUM = "file://License.txt;md5=deb6d182b0f7f8a866c42941b9f014c4"

BBCLASSEXTEND = "native nativesdk"

PR = "r1"

PVSHORT = "${@'${PV}'.replace('.','')}"
SRC_URI = " \
    https://sourceforge.net/projects/cryptopp/files/cryptopp/5.6.4/cryptopp564.zip;subdir=libcryptopp-${PV} \
    file://0001-Fix-cross-compilation.patch \
"
SRC_URI[md5sum] = "4ee7e5cdd4a45a14756c169eaf2a77fc"
SRC_URI[sha256sum] = "be430377b05c15971d5ccb6e44b4d95470f561024ed6d701fe3da3a188c84ad7"

inherit autotools-brokensep pkgconfig
EXTRA_OECONF = "--libdir=${base_libdir}"

#we want tegrarcm binary to run on a 32-bit architecture, on x86_64 this requires the 32-bit compatibility libs
EXTRA_OEMAKE_class-native = "CC='${CC} -m32' CXX='${CXX} -m32'"
do_compile() {
    sed -i -e 's/^CXXFLAGS/#CXXFLAGS/' GNUmakefile
    export CXXFLAGS="${CXXFLAGS} -DNDEBUG -fPIC"
    oe_runmake -f GNUmakefile
    oe_runmake libcryptopp.a
}

do_install:prepend() {
    export PREFIX=${prefix}
}

do_install:append() {
    if [ -f "${D}/usr/lib/libcryptopp.so" ] && [ ! -e "${D}/usr/lib/libcryptopp.so.${PV}" ]
    then
        mv ${D}/usr/lib/libcryptopp.so  ${D}/usr/lib/libcryptopp.so.${PV}
        ln -fs libcryptopp.so.${PV} ${D}/usr/lib/libcryptopp.so.5
        ln -fs libcryptopp.so.${PV} ${D}/usr/lib/libcryptopp.so
    fi
}


text:
Q: VM's IP address got changed. True? I just want to know whether a virtual machince IP address will change periodically. It was some xxx.xxx.xx.xx earlier and now after a month it is xxx.xxx.xx.xy. Is that possible?

A: it depends from your dhcp server:
if dhcp server configured for leasing ip from a range, you can see all leased ips in
dhcpd.leases file.
If you want to use static ip's you can reserve ip from range and configure client machine for static ip using.


text:
Q: Derived Functors Why do we say "This functor is left exact, but not right exact" instead of "This functor preserves limits, but not colimits".  It seems more natural to base the theory of derived functors on the second statement instead of the first.  I've never really understood what it meant to say that the global sections functor is left exact.  From looking at the definition on the wikipedia page, it says given an exact sequence $$0 \to A \to B \to C \to 0,$$ the functor is left exact when $$0 \to F(A) \to F(B) \to F(C)$$ is exact.  However, if you consider the category of open sets on a space $X$, do exact sequences make sense in this case?  $0$ is supposed to be a zero object, which means it is both initial and terminal.  I don't think the category of open sets has that.
Also, are the following equivalent?

*

*$F$ preserves limits/colimits

*$F$ is left exact/right exact

*$F$ is right adjoint/left adjoint

Edit Number One: I think I have a better understanding now.  I think has more to do with preserving arbitrary limits/colimits vs finite limits/colimits.  If a functor is right adjoint, then it preserves arbitrary limits.  From Goldbatt's Topoi book, I see that the definition of left exact is for the functor to preserve finite limits.  So, do we lose flavor of the theory of Derived Functors when we say the functor preserves arbitrary limits/colimits instead of the restricted finite limits/colimits?  What if we say that the functor is left adjoint/right adjoint?
Edit Number Two: Should the wiki article on Exact Functors be edited?  Comparing to the article given over at nlab, I think the wiki article does a poor job.  It seems to me that the wiki article gives the definition via short exact sequences, and then derives the "preserving limits/colimits" fact.  This approach however assumes that the category has a zero object, and the source of some of my confusion.  The nlab approach is better; it gives the definition of left exact functor as preserving finite limits.

A: The basic point here is that there are various ways of defining both exact sequences and left / right exact functors. These definitions are equivalent in abelian categories but inequivalent in general, so which one you want to take outside of the setting of abelian categories depends on what theorems you want to still be true.
As for your specific question: in an abelian category, "preserves finite limits" is equivalent to the usual definition of left exactness, and dually "preserves finite colimits" is equivalent to the usual definition of right exactness. Preserving finite limits is a strictly weaker condition than having a left adjoint, which requires at least that a functor preserves arbitrary limits.


text:
Q: Need help from CSS purist! I'm beginning to use CSS more and more but I'm not sure if I'm using it as intended in all cases.
I have classes named things like 'box' that will wrap the content inside it with a border, which seems like good CSS to me.
On the other hand I have classes like 'margin-right-5' and 'float-left' that sets the css to margin-right: 5px and float:left respectively. I'm wondering if this is good practice.
Then in my markup I'd do something like:

Sometimes I may want to float right or not have a margin at all and still use the 'box' class, so I use several classes in order to make the css more flexible.
Am I destroying the principles of CSS?

A: You should not have presentational class name values. The values should dictate the type of content that is there. .content-box for example. Use the most specific name you can, like warning or error-dialog or primary-content.
If you name something left-align and later on in the future you have this left-align class on 10-20 separate templates/include files, it won't be meaningful when the client decides to want to have that element right-aligned.
Just set whatever rules you need to, and you can make general rules for generic classes and override them if need be.
.content-box {
  float:left;
  margin:0 0 0 5px;
}

Using your way, you'd define a class for every property-value combination...

This is a mess. Avoid at all costs.

A: "Am I destroying the principles of CSS?"
Short answer:
Yes
Long answer:
At least you're checking your practice. Classes should be descriptive of the object and semantics, not of the style.
Here are some good classes:

*

*warning

*error

*sidebar

*box

*block

*name

*title

*song

Here are some bad classes:

*

*yellow

*left

*wide

*small

*clearfix†
†Edit to add a class that I no longer use as it's not necessary

A: I would suggest rethinking your naming conventions.
With the sample above you could end up with class="margin-right-[0 through 1000+].
It's better to describe what the item is versus attributes about it
ie.

Home

etc

 ...

And then add the padding/margin/etc as needed.
Remember to use proper html elements instead of making everything divs (a.k.a divitis).  Titles should use  tags, etc.


text:
Q: How to simulate a random walk to randomly generated particle to another particle fixed at the center of a grid? I am new in Mathematica, it is my first program. Many codes of diffusion-limited aggregation are available but, they are too difficult to understand.
 I basically want to create a simulation of the random walk demonstrating the Brownian motion in a visible grid. It is a regular lattice. It starts with a single seed particle at the origin of a lattice. A second particle (random walker), is added at some random site at a long distance from the origin. This particle walks randomly until it reaches a site adjacent to the seed and becomes part of the growing cluster. The particle jumps from the current site to one of their nearest lattice sites at each step until it hits and sticks to the cluster of fixed particles. A third, fourth and so on particles are introduced in the same way and they also join the growing cluster. If the particle reaches the boundaries of the lattice in its random walk, it is killed, and another introduced. The procedure is repeated until a cluster of sufficiently large size is formed.
The aggregation process is similar to the DLA model. The aggregation starts with a seed at the site which is nearest to the centre of the square. A particle is added at a random site at large distance from the seed. The particle chooses randomly a neighbour and walks on the geometric graph. When the particle reaches a site that is adjacent to the seed or the cluster, the particle becomes a part of the cluster. I want the end result of this type given in link -> aggregation model
Towards this end, I have created a grid and two particles. But, I am not able to move the particle. Below is my code:
Graphics[{PointSize[Large], Point[{{25/2, 25/2},
{RandomInteger [25], RandomInteger [25]}}]},
GridLines -> {Range[0, 25], Range[0, 25]},
PlotRange -> {{0, 25}, {0, 25}}, Axes -> True]

A: So, here is my reformulations of C.E.'s code.
What has changed:

*

*I use reservoirs rand and randpts of large random arrays; generating such arrays is much less expensive than generating every random number on its own.

*I use RegionMember and Nearest for the collision tests.
Implementation
getCluster[startcluster_, nparticles_, L_] := Module[{
    getStartpoint, getDirection,
    directions, cluster, nf, box, inboxQ, nrand, rand, nrandpts,
    randpts, iparticle, irand, irandpts, particle, inbox
    },

   getStartpoint[] := Block[{p},
     If[irandpts < nrandpts,
      irandpts++,
      irandpts = 1;
      randpts = RandomInteger[{-L, L}, {nrandpts, 2}];
      ];
     p = randpts[[irandpts]];
     While[
      Length[nf[p, {1, 0}]] > 0,
      If[irandpts < nrandpts,
       irandpts++,
       irandpts = 1;
       randpts = RandomInteger[{-L, L}, {nrandpts, 2}];
       ];
      p = randpts[[irandpts]];
      ];
     p
     ];

   getDirection[] := (
     If[irand < nrand,
      irand++,
      irand = 1;
      rand = RandomInteger[{1, 4}, nrand];
      ];
     directions[[rand[[irand]]]]
     );

   directions = Developer`ToPackedArray[{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}];

   (* set up a sufficiently large array to store the cluster in order to avoid the costly Append.*)
   cluster = Join[startcluster, ConstantArray[{0, 0}, {nparticles}]];
   nf = Nearest[cluster -> Automatic];

   (* define the box and a collision checker *)

   box = Rectangle[{-L, -L}, {L, L}];
   inboxQ = RegionMember[box];

   (* counters for the reservoirs for random numbers and points *)

   irand = nrand = 1000000;
   irandpts = nrandpts = 10000;

   iparticle = Length[startcluster];

   (* share some progress info with the user *)
   PrintTemporary[
    Dynamic[
     Grid@
      Transpose[{{"iparticle", "irand", "irandpts"}, {iparticle,
         irand, irandpts}}]
     ]
    ];
   While[iparticle < Length[cluster],
    Check[particle = getStartpoint[];, Print["!"]];
    inbox = True;
    While[inbox,
     Check[particle += getDirection[];, Print["?"]];
     inbox = inboxQ[particle];
     If[inbox,
      If[Length[nf[particle, {1, 1}]] > 0,
       Check[cluster[[iparticle]] = particle;, Print["."]];
       nf = Nearest[cluster -> Automatic];
       iparticle++;
       inbox = False
       ]
      ]
     ]
    ];
   Association[
    "Cluster" -> cluster,
    "Box" -> box,
    "N" -> nparticles
    ]
   ];

And here a function to plot the particles with color according to their age:
showCluster[a_Association] := With[{L = a[["Box", 2, 2]]},
   ArrayPlot[
    Transpose@SparseArray[
      (a[["Cluster"]] + (L + 1)) ->
       Rescale[Range[Length[a[["Cluster"]]]]],
      {2 L + 1, 2 L + 1},
      2.
      ],
    ColorFunction -> "DeepSeaColors",
    PlotRange -> {0, 1},
    ClippingStyle -> White,
    DataReversed -> {True, False}
    ]
   ];

Usage example
A test run with 2000 particles, a single condensation core at {0,0}, and a box of edgelength 101 = 2 * 50 + 1 (yes, this takes a bit):
data = getCluster[{{0, 0}}, 10000, 100]; // AbsoluteTiming // First

184.823

And here a plot of the result:
showCluster[data]

You can continue the simulation with
data2 = getCluster[data[["Cluster"]], 10000, 100]; // AbsoluteTiming // First
showCluster[data2]

28.3286

Surprisingly complex patterns!

A: This is like what you described, except that I also made sure that the particle didn't wander outside of the region $-100 \leq x, y \leq 100$ to ensure that convergence wouldn't take too long.
particles = {{0, 0}};
nf = Nearest[particles -> Automatic];
nextStep := RandomChoice[{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}];
nParticles = 100;
l = 100;

inBounds[{x_, y_}, l_] := -l < x < l && -l < y < l

Do[
  particle = RandomInteger[{-l, l}, 2];
  While[
   Length[nf[particle, {1, 1}]] == 0,
   particle = RandomInteger[{-l + 1, l - 1}, 2];
   ];
  step = nextStep;
  While[
   Length[nf[particle, {1, 1}]] == 0,
   particle += step;
   step = nextStep;
   While[
    ! inBounds[particle + step, l],
    step = nextStep;
    ]
   ];
  AppendTo[particles, particle];
  nf = Nearest[particles -> Automatic],
  {nParticles}
  ];

Graphics[{
  Point[particles]
  }]


text:
Q: Need to execute a function after returning the response in Flask For one request alone i need to execute a function after sending the response to the client. Because the function takes time and that ends up in connection timeout Socket error: [Errno 32] Broken pipe
Is there a way in  Flask to execute function after returning the request

A: There is no Flask-native way to accomplish this. after_request will still run before returning the response to the client, not after.
Here is a discussion of the problem and some solutions.

A: You can use the after_request decorator or customize to create a after_this_request which only works for that particular request.
Take a look at this snippet http://flask.pocoo.org/snippets/53/

A: I will expose my solution.
You can use threads to compute anything after returned something in your function called by a flask route.
import time
from threading import Thread
from flask import request, Flask
app = Flask(__name__)

class Compute(Thread):
    def __init__(self, request):
        Thread.__init__(self)
        self.request = request

    def run(self):
        print("start")
        time.sleep(5)
        print(self.request)
        print("done")

@app.route('/myfunc', methods=["GET", "POST"])
def myfunc():
        thread_a = Compute(request.__copy__())
        thread_a.start()
        return "Processing in background", 200

A: You can defer route specific actions with limited context by combining after_this_request and response.call_on_close.  Note that request and response context won't be available but the route function context remains available.  So you'll need to copy any request/reponse data you'll need into local variables for deferred access.
@app.route('/')
def index():
    # Do your pre-response work here
    msg = 'Hello World!'
    @flask.after_this_request
    def add_close_action(response):
        @response.call_on_close
        def process_after_request():
            # Do your post-response work here
            time.sleep(3.0)
            print('Delayed: ' + msg)
        return response
    return msg

A: You can try use streaming. See next example:
import time
from flask import Flask, Response

app = Flask(__name__)

@app.route('/')
def main():
    return '''
start

    '''

@app.route('/test')
def test():
    def generate():
        app.logger.info('request started')
        for i in range(5):
            time.sleep(1)
            yield str(i)
        app.logger.info('request finished')
        yield ''
    return Response(generate(), mimetype='text/plain')

if __name__ == '__main__':
    app.run('0.0.0.0', 8080, True)

All magic in this example in genarator where you can start response data, after do some staff and yield empty data to end your stream.
For ditails look at http://flask.pocoo.org/docs/patterns/streaming/.

A: A more general solution than the flask iterator solution is to write a WSGI middleware that adds a callback to the response close method. Here we use the werkzeug ClosingIterator helper and a flask app extension to achieve this:
import traceback
from werkzeug.wsgi import ClosingIterator

class AfterResponse:
    def __init__(self, app=None):
        self.callbacks = []
        if app:
            self.init_app(app)

    def __call__(self, callback):
        self.callbacks.append(callback)
        return callback

    def init_app(self, app):
        # install extension
        app.after_response = self

        # install middleware
        app.wsgi_app = AfterResponseMiddleware(app.wsgi_app, self)

    def flush(self):
        for fn in self.callbacks:
            try:
                fn()
            except Exception:
                traceback.print_exc()

class AfterResponseMiddleware:
    def __init__(self, application, after_response_ext):
        self.application = application
        self.after_response_ext = after_response_ext

    def __call__(self, environ, after_response):
        iterator = self.application(environ, after_response)
        try:
            return ClosingIterator(iterator, [self.after_response_ext.flush])
        except Exception:
            traceback.print_exc()
            return iterator

You can then use your after_response decorator like this:
import flask
import time
app = flask.Flask("after_response")
AfterResponse(app)

@app.after_response
def after():
    time.sleep(2)
    print("after_response")

@app.route("/")
def home():
    return "Success!\n"

When you curl this, you'll see that it responds immediately and curl closes, then 2s later your "after" message appears in the logs:
127.0.0.1 - - [25/Jun/2018 15:41:51] "GET / HTTP/1.1" 200 -
after_response

This answer is summarized from my answers here and here.


text:
Q: Play large video on Android without lagging I'm developing an AR game. In a particular situation, I want to play a video, which user selected from phone gallery, in a part of scene in unity(for example on a Plane).
I test unity Video Player, but that would lag so much when video size is more than 100 Mbyte and even textures doesn't display, just I can hear video sound.
What should I do now? Should I write a java native plugin which stream video in java and set textures in unity?
Thanks and Sorry for bad English.
    videoPlayer.playOnAwake = false;
    videoPlayer.source = VideoSource.Url;
    videoPlayer.url = url;
    videoPlayer.Prepare();

    //Wait until video is prepared
    while (!videoPlayer.isPrepared)
    {
        Debug.Log("Preparing Video");
        yield return null;
    }

    //Assign the Texture from Video to RawImage to be displayed
    image.texture = videoPlayer.texture;

    //Play Video
    videoPlayer.Play();

I also assigned AudioSource in editor.
All things works fine just if video size is lower than 10 Mbyte.

A: Unity's VideoPlayer seems to be lagging on some Android devices when the video file is big. One possible solution on the Android device is to read the video in chunks then host it on the Android device with HttpListener.
Connect to that host you created on the device with the VideoPlayer API by using VideoSource.Url; and setting the VideoPlayer.url to that host url on the local device then play the video.
Host the video with HttpListener(Must change filePath to point to the actual path of the video:
//Server url
string url = "http://127.0.0.1:8080/";

//Types of media supported(Can be extended)
private static IDictionary<string, string> mimeDic =
       new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
       {
            {".asf", "video/x-ms-asf"},
            {".asx", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".flv", "video/x-flv"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".mng", "video/x-mng"},
            {".mov", "video/quicktime"},
            {".mp3", "audio/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mp4", "video/mp4" },
            {".mpg", "video/mpeg"},
            {".ra", "audio/x-realaudio"},
            {".swf", "application/x-shockwave-flash"},
            {".wbmp", "image/vnd.wap.wbmp"},
            {".wmv", "video/x-ms-wmv"},
       };

List<HttpListenerResponse> httpResponses = new List<HttpListenerResponse>();
Thread listeningThread;

void Awake()
{
    Application.runInBackground = true;

    //Your Video Path
    string filePath = Path.Combine(Application.persistentDataPath, "Cater2U.mp4");

    Debug.Log(filePath.Replace("/", "\\"));

    //Create Server
    StartHttpServer(filePath);
}

void StartHttpServer(string dataPath)
{
    listeningThread = new Thread(new ParameterizedThreadStart(ListenToClient));
    listeningThread.IsBackground = true;
    listeningThread.Start(dataPath);
}

void StopHttpServer()
{
    //Stop thread
    if (listeningThread != null && listeningThread.IsAlive)
    {
        listeningThread.Abort();
        Debug.LogWarning("Listening Thread Stopped!");
    }
}

void DisconnectClients()
{
    //Disconnect from each connected client
    for (int i = 0; i < httpResponses.Count; i++)
    {
        if (httpResponses[i] != null)
        {
            httpResponses[i].StatusDescription = "Server done";
            httpResponses[i].OutputStream.Close();
            Debug.LogWarning("Disconnected Client!");
        }
    }
}

void ListenToClient(object path)
{
    //Get the param
    string dataPath = (string)path;

    HttpListener listener = new HttpListener();
    listener.Prefixes.Add(url);
    listener.Start();

    Debug.Log("Listening to Client");

    while (true)
    {
        HttpListenerContext context = listener.GetContext();
        Debug.LogWarning("New Client Connected: " + context.Request.RemoteEndPoint.ToString());

        //Construct param that will be sent to the Thread
        ServerParamData serverData = new ServerParamData(context, dataPath);
        ThreadPool.QueueUserWorkItem(new WaitCallback(RunInNewThread), serverData);
    }
}

private void RunInNewThread(object ctx)
{
    //Get the param
    ServerParamData serverData = (ServerParamData)ctx;

    //Open the file and start sending it to the client
    WriteFile(serverData.context, serverData.path);
}

void WriteFile(HttpListenerContext ctx, string path)
{
    HttpListenerResponse response = ctx.Response;
    httpResponses.Add(response);

    using (FileStream fs = File.OpenRead(path))
    {
        string filename = Path.GetFileName(path);
        string mime;

        //Set the type of media to play
        if (!mimeDic.TryGetValue(Path.GetExtension(filename), out mime))
            mime = "application/octet-stream";

        ctx.Response.ContentType = mime;
        response.ContentLength64 = fs.Length;

        //Stream the File
        response.SendChunked = true;

        //Enable Media Seek(Rewind/Fastforward)
        response.StatusCode = 206;
        response.AddHeader("Content-Range", "bytes 0-" + (fs.Length - 1) + "/" + fs.Length);
        //According to Content Range
        //https://greenbytes.de/tech/webdav/rfc7233.html#header.content-range

        //Send data to the connected client
        byte[] buffer = new byte[64 * 1024];
        int read;
        using (BinaryWriter bw = new BinaryWriter(response.OutputStream))
        {
            while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
            {
                bw.Write(buffer, 0, read);
                bw.Flush(); //seems to have no effect
            }
            bw.Close();
        }

        response.StatusCode = (int)HttpStatusCode.OK;
        response.StatusDescription = "OK";
        response.OutputStream.Close();
    }
}

void OnDisable()
{
    //Clean Up
    StopHttpServer();
    DisconnectClients();
}

//Holds multiple params sent to a function in another Thread
public class ServerParamData
{
    public HttpListenerContext context;
    public string path;

    public ServerParamData(HttpListenerContext context, string path)
    {
        this.context = context;
        this.path = path;
    }
}

Play the hosted video with VideoPlayer API (This is a minor modification of the code from this post) :
//Raw Image to Show Video Images [Assign from the Editor]
public RawImage image;

private VideoPlayer videoPlayer;
private VideoSource videoSource;

//Audio
private AudioSource audioSource;

//Server url
string url = "http://127.0.0.1:8080/";

// Use this for initialization
void Start()
{
    Application.runInBackground = true;
    StartCoroutine(playVideo());
}

IEnumerator playVideo()
{
    //Add VideoPlayer to the GameObject
    videoPlayer = gameObject.AddComponent<VideoPlayer>();

    //Add AudioSource
    audioSource = gameObject.AddComponent<AudioSource>();

    //Disable Play on Awake for both Video and Audio
    videoPlayer.playOnAwake = false;
    audioSource.playOnAwake = false;

    //We want to play from url
    videoPlayer.source = VideoSource.Url;
    videoPlayer.url = url;

    //Set Audio Output to AudioSource
    videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;

    //Assign the Audio from Video to AudioSource to be played
    videoPlayer.EnableAudioTrack(0, true);
    videoPlayer.SetTargetAudioSource(0, audioSource);

    //Prepare Audio to prevent Buffering
    videoPlayer.Prepare();

    //Wait until video is prepared
    while (!videoPlayer.isPrepared)
    {
        Debug.Log("Preparing Video");
        yield return null;
    }

    Debug.Log("Done Preparing Video");

    //Assign the Texture from Video to RawImage to be displayed
    image.texture = videoPlayer.texture;

    //Play Video
    videoPlayer.Play();

    //Play Sound
    audioSource.Play();

    Debug.Log("Playing Video");
    while (videoPlayer.isPlaying)
    {
        Debug.LogWarning("Video Time: " + Mathf.FloorToInt((float)videoPlayer.time));
        yield return null;
    }
    Debug.Log("Done Playing Video");
}

This works for me but may work on your device. If that's the case then you have to abandon the VideoPlayer API for now and use the MediaPlayer with OpenGL ES to make your own video player for Android. This and this posts should get you started on the plugin.


text:
Q: C# cannot dynamically generate this simple event handler I'm trying to learn a bit about dynamically generating event handlers and I'm having difficulty trying to recreate this simple situation:
public delegate void SomethingHappenedEventHandler(object sender, object args);
public event SomethingHappenedEventHandler SomethingHappened;

// This is the event handler that I want to create dynamically
public void DoSomething(object a, object b)
{
    DoSomethingElse(a, b);
}

public void DoSomethingElse(object a, object b)
{
    Console.WriteLine("Yay! " + a + " " + b);
}

I've used reflector to generate the IL for the DoSomething method, and it gives me:
.method public hidebysig instance void DoSomething(object a, object b) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldarg.1
    L_0002: ldarg.2
    L_0003: call instance void MyNamespace::DoSomethingElse(object, object)
    L_0008: ret
}

So, I've written the following code to dynamically generate and execute a method equivalent to DoSomething(...):
public void CreateDynamicHandler()
{
    var eventInfo = GetType().GetEvent("SomethingHappened");
    var eventHandlerType = eventInfo.EventHandlerType;

    var dynamicMethod = new DynamicMethod("DynamicMethod", null, new[] { typeof(object), typeof(object) }, GetType());
    var ilgen = dynamicMethod.GetILGenerator();
    ilgen.Emit(OpCodes.Ldarg_0);
    ilgen.Emit(OpCodes.Ldarg_1);
    ilgen.Emit(OpCodes.Ldarg_2);

    MethodInfo doSomethingElse = GetType().GetMethod("DoSomethingElse", new[] { typeof(object), typeof(object) });
    ilgen.Emit(OpCodes.Call, doSomethingElse);
    ilgen.Emit(OpCodes.Ret);

    Delegate emitted = dynamicMethod.CreateDelegate(eventHandlerType);
    emitted.DynamicInvoke("hello", "world");
}

However, when I run this I get an InvalidProgramException: JIT Compiler encountered an internal limitation.
Can anyone point out where I've gone wrong?
[EDIT] As several people have commented, the whole IL generation thing is unnecessary if I know all of the types involved. My reason for doing this is that this is the first step towards dynamically generating event handlers at runtime for events where I do not know all the types involved. Basically I'd been following the example at http://msdn.microsoft.com/en-us/library/ms228976.aspx, got stuck, and then tried to unwind things into a simple example that I could get working.

A: It is unclear why you would want to create this method dynamically. I can't really think of any situation in which you couldn't just apply a lambda to the event:
public delegate void SomethingHappenedEventHandler(object sender, object args);
public event SomethingHappenedEventHandler SomethingHappened;

public void DoSomethingElse(object a, object b)
{
    Console.WriteLine("Yay! " + a + " " + b);
}

// If the signature exactly matches the delegate, just use the method name
SomethingHappened += DoSomethingElse;

public void DoSomethingDifferent(object a)
{
    Console.WriteLine("Yay! " + a);
}

// Otherwise, just use a lambda expression
SomethingHappened += (a, b) => DoSomethingDifferent(a);

That said, the reason your code doesn't work is because DynamicMethod generates only static methods. Therefore, the IL code is invalid because Ldarg_0 and Ldarg_1 load the two parameters but Ldarg_2 refers to a non-existent parameter. If I change it in the following way, it works as one would expect — it is now a static method with three parameters, where the first parameter is basically this:
public void CreateDynamicHandler()
{
    var dynamicMethod = new DynamicMethod("DynamicMethod", null,
        new[] { typeof(MyClass), typeof(object), typeof(object) }, typeof(MyClass));
    var ilgen = dynamicMethod.GetILGenerator();
    ilgen.Emit(OpCodes.Ldarg_0);
    ilgen.Emit(OpCodes.Ldarg_1);
    ilgen.Emit(OpCodes.Ldarg_2);

    MethodInfo doSomethingElse = typeof(MyClass).GetMethod("DoSomethingElse",
        new[] { typeof(object), typeof(object) });
    ilgen.Emit(OpCodes.Call, doSomethingElse);
    ilgen.Emit(OpCodes.Ret);

    Delegate emitted = dynamicMethod.CreateDelegate(
        typeof(Action<MyClass, string, string>));
    emitted.DynamicInvoke(this, "Hello", "World");
}

Replace "MyClass" with the name of your class.
Regarding the EDIT of your question, you don't need to generate a dynamic method by writing IL code in order to call a method dynamically at runtime. Just use Reflection, for example:
public void DoSomething(object a, object b)
{
    var method = GetType().GetMethod("DoSomethingElse", BindingFlags.Instance | BindingFlags.Public);
    method.Invoke(this, new object[] { a, b });
}

or:
// Note "static"
public static void DoSomething(dynamic instance, object a, object b)
{
    // This will call whatever "DoSomethingElse" method exists on the type
    // that "instance" has *at run-time*
    instance.DoSomethingElse(a, b);
}

A: How about this scenario...
You have pairs of Methods and events such that each pair is MethodAsync and MethodCompleted. Each MethodCompleted has a different signature (differing in the subtype of the eventargs, which is the second parameter).
You want to create a wrapper for calling a given MethodAsync that hooks an all-purpose eventhandler up to the corresponding MethodCompleted.
Normally, you could create a method "void GlobalHandler(object, object)", and do
MethodCompleted += GlobalHandler;

However, you cannot pass the event object, so you have to use reflection to get a reference to the event handler and then do AddHandler. Again, the snag is that AddHandler doesn't like polymorphism (it seems), and complains that MethodCompleted wants something other than GlobalHandler.
In such a case, it seems like you'd need to create a DynamicMethod of the EXACT signature that MethodCompleted expects, and then call GlobalHandler from that. Am I right, or am I also missing something here.


text:
Q: There exist a point $ c \in [a,b]$ such that $f(c)= \frac{f(x_{1})+f(x_{2})+...+f(x_{n})}{n}$. Let $ f: [a,b]\to \mathbb{R}$ be continuous on $[a,b]$ and $ x_{1},x_{2},...,x_{n} \in [a,b].$Then there is a point $ c \in [a,b]$ such that $f(c)= \frac{f(x_{1})+f(x_{2})+...+f(x_{n})}{n}$.
Can anyone give me some hint which I can use to prove this? Any help would be appreciated. Thanks in advance