text:
Q: Criando um Uber Jar com Gradle não está funcionando Estou usando o plugin do johnrengelman
/
shadow para criar um uber jar com as algumas dependências locais, mas por alguma razão que desconheço não está funcionando.
build.gradle
/*
 * This file was generated by the Gradle 'init' task.
 */
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

plugins {
    id 'java'
    id 'maven-publish'
    id 'com.github.johnrengelman.shadow' version '5.2.0'
}

repositories {
    mavenLocal()
    maven {
        url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/'
    }

    maven {
        url = 'https://repo.bukkit.org/content/groups/public/'
    }

    maven {
        url = 'https://repo.maven.apache.org/maven2'
    }
}

shadowJar {
   archiveBaseName = "uber"
   classifier = ''
   archiveVersion = '1.0.0-SNAPSHOT'
}

dependencies {
    compileOnly fileTree(dir: 'lib', include: 'minecraft-colors-*.jar')
    shadow fileTree(dir: 'lib', include: 'knautiluz-http-*.jar')
    shadow fileTree(dir: 'lib', include: 'knautiluz-http-services-*.jar')
    testImplementation 'junit:junit:4.8.1'
    testImplementation 'org.mockito:mockito-all:1.9.5'
    compileOnly 'org.spigotmc:spigot-api:1.15.1-R0.1-SNAPSHOT'
}

group = 'com.knautiluz.lorelei'
version = '1.0.0-SNAPSHOT'
description = 'Knautiluz Verify'
sourceCompatibility = '1.8'

publishing {
    publications {
        maven(MavenPublication) {
            from(components.java)
        }
    }
}

Com os comandos gradle build e gradle shadowJar os jars criados são praticamente os mesmos, e não carregam as dependências mencionadas

A: Apesar de ver em diversos locais que a forma de criar o shade é usar o shadow algo deve ter mudado na ultima versão, pois obtive o uber jar usando implementation no lugar do shadow ficando:
dependencies {
    compileOnly fileTree(dir: 'lib', include: 'minecraft-colors-*.jar')
    implementation fileTree(dir: 'lib', include: 'knautiluz-http-*.jar')
    implementation fileTree(dir: 'lib', include: 'knautiluz-http-services-*.jar')
    testImplementation 'junit:junit:4.8.1'
    testImplementation 'org.mockito:mockito-all:1.9.5'
    compileOnly 'org.spigotmc:spigot-api:1.15.1-R0.1-SNAPSHOT'
}

E assim ele criou meu jar gordinho com as dependências.


text:
Q: Control flow logic in for loop How is the following for loop different from original?
Why after initialization, it  checks for the condition?
Why such behavior and what are other such tricky behaviors of for loop?
class FooBar
{
static public void main(String... args)
{
    for (int x = 1; ++x < 10;)
    {
        System.out.println(x);  // it starts printing from 2

    }
}
}

Output:
    2
    3
    4
    5
    6
    7
    8
    9

A: ++x increments the value of x. As a result, two things are happening:

*

*The value being checked for the for-loop condition (i.e., the inequality), is already incremented, and

*This incremented value is what gets printed within the loop.

If you want values from 1 to 9, use the standard loop:
for (int x = 1; x < 10; ++x) { ... }

The effects of prefix and postfix operators has been discussed and explained in detail elsewhere, this post, for example.

A: The increment of x is combined with the condition.  Normally, the increment is performed in the third section of the for loop, which is a statement executed at the end of an iteration.
However, the condition is checked at the beginning of the loop.  It's an expression, not a statement, but as you can see, that doesn't stop someone from inserting a side-effect -- the pre-increment of x.
Because x starts out as 1, the condition increments it to 2 before the first iteration.

A: This is not for-loop trickery, it's the way the prefix and postfix operator works that you're using on x.
++x - Increment x then evaluate its value
x++ - Evaluate the value of x and then increment it.
So, the loop with this definition:
for (int x = 1; ++x < 10;)

executes like this:

*

*Initialize x to 1

*Increment x by 1

*Evaluate if x < 10.  If yes, iterate loop.  If no, end loop.

What you want is this:
for (int x = 1; x < 10; x++)

*

*Initialize x to 1

*Evaluate if x < 10.  If yes, iterate loop.  If no, end loop.

*Increment x by 1

A: Each for-loop (except enhanced for loop) has the following structure -
for(initialization; conditionChecking; increment/decrement){

   //body

}

Your for-loop also has this structure with the incremetn/decrement portion empty. But to continue the for loop you have to change index (here x) of for-loop. If it is done some how then you can leave the increment/decrement portion empty. If you write the for-loop like this then it also fine -
for(int x=0; x<10; ){
   //do something
   x++;
}

You also may leave one/more portion (even the body) of a for-loop empty, like this -
int x=0;
for(;x<10;x++); //empty body; do nothing; just increment x

A: A for loop is valid with one or more of it's some portion leaving empty.
In the your code the increment portion is empty. You have done your increment of index x by using ++x>10. So it is valid. There is no difference from the regular for loop, it's just a way of representing the for loop in different way.

A: The Original way of a for loop  you may have in you mind:
for(initialization; condition; inc/dec/divide..)
And what you mentioned: for (initialization; Inc & check; nothing)
What does it mean? : for(some blaBla; any Bla; some, more, bla)
You may have any expression any where. The Original version is just a convention we follow. Go ahead an write a printing statement or a bitwise operator instead of some blaBla try it out!
Update:
Why :
  for (int x = 1; x++ < 10;)
      {
           System.out.println(x);

      }

Prints 2..10? For the answer first try to execute :
   for (int x = 1; ++x < 10;)
          {
               System.out.println(x);

          }

It prints from 2..9
You should understand how pre/post fix operators work. x++ in the loop increments the value but not immediately. It increments after  x++ < 10;
Where as ++x < 10; first increments and then rest everything happens.
So, when the x value is 9, 9(++)< 10 -> 9 is less ? yeah, now 9++ occurs.It then increments x. but ++x increments 1st so ++9< 10 -> 10<10 NO.

A: You can write your code as:
x = 1;
while (++x < 10)
{
    System.out.println(x);
}

You expect the following:
x = 1;
do
{
    System.out.println(x);
}
while (++x < 10);

This is the difference.
The following does what you expect:
for (int x = 1; x < 10; x++)
{
    System.out.println(x);
}

A: TL;DR of it all is that ++x is a pre increment operator. When you use ++x, x will be incremented before any other allied operation. That is why your code prints out 2 first instead of 1 and stops when ++x becomes 10

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable input type text, if value=true I want to disable input type when the value of the input is true
("SELECT * FROM userinfo WHERE id='studid'")

<input type='text' name='id' value='<?php echo $row['studid']; ?>' />

How can I do that ? Help me :(

A: Echo it out as php, but I'm not exactly sure what you mean by if stuid is true..? If it isn't true it doesn't exist and if it doesn't exist it shouldn't be the value of your input ....
if($row['studid'] == ""){
   echo "<input type='text' name='id' value='' disabled/>";
}else{
   echo "<input type='text' name='id' value='' />";
}

A: Try like this.
if(isset($row['studid']))
{
$dis='disabled';
}
else
{
$dis='';
}
<input type='text' name='id' value='<?php echo $row['studid']; ?>' <?=$dis?> />


text:
Q: VS CODE not showing Matplotlib images I have a simple script that reads and shows images in Matplotlib.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

baseimg = '/home/ahmad/Downloads/mnist/trainingSample/img_0.jpg'
img = mpimg.imread(baseimg)

plt.imshow(img)
plt.show()

It is working on Jupyter Notebook but when I run it in VS Code, it runs but does not show any image. Is there some problem in my code or how to fix it. Thanks


text:
Q: Delete all subcollections of a particular document(i,e.currentuser doc) in collection when app is killed in kotlin/android I have a collection which has a subcollection.I do not want to delete the collection,but I want to delete all subcollections of a particular document(i.e.currentuser doc) when user kills the app.
I was doing something like below from client side using services.But then that only deletes the collection documents data,it does not delete the subcollection:

class onAppKilled: Service() {
    private lateinit var mFirestore:FirebaseFirestore
    private var mAuth: FirebaseAuth? = null
    lateinit var currentUser: FirebaseUser
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
    override fun onTaskRemoved(rootIntent: Intent?) {

        mFirestore= FirebaseFirestore.getInstance()
        mAuth = FirebaseAuth.getInstance()
        currentUser= mAuth!!.currentUser!!

        currentUser.delete().addOnCompleteListener(OnCompleteListener {task->
            if(task.isSuccessful){
                Toast.makeText(this@onAppKilled,"User Deleted", Toast.LENGTH_LONG).show()

            }else{
                Toast.makeText(this@onAppKilled,"User not deleted", Toast.LENGTH_LONG).show()

            }
        })
     mFirestore.collection("AllUsers").document(SplitString(currentUser.email!!)).delete()

    }

I read about using cloud functions for deleting subcollections.So i installed cloud functions with my app but now I am not sure how do I go about deleting the particular documents subcollection when the app is killed?


text:
Q: How "tblGene()" call on JavaScript page.I am want to call on HTML page using onclick.. Without click this Json table show on my web page How tblGene() call on JavaScript page. I do not want to call on HTML page using onclick. Without click, this JSON table show on my web page. Please help me. When page was loaded this JSON table on my web page. I do not want to use input box for click.
<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />

    var people, asc1 = 1;
function tblGene() {
  var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
  var thead = document.createElement('thead');
  var tbody = document.createElement('tbody');
  tbody.id = "people";
  var tbl = document.createElement("table");
  tbl.id = "tblSample";
  var col = [];
  for (var i = 0; i < data.length; i++) {
    for (var colHdr in data[i]) {
      if (col.indexOf(colHdr) === -1) {
        col.push(colHdr);
      }
    }
  }
  var tr = tbl.insertRow(-1);
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th");
    th.innerHTML = col[i];
    th.dataset.key = i;
    tr.appendChild(th);
  }
  thead.appendChild(tr);
  for (var i = 0; i < data.length; i++) {
    tr = tbl.insertRow(-1);
    for (var j = 0; j < col.length; j++) {
      var td = document.createElement("td");
      var tabCell = tr.insertCell(-1);
      tabCell.innerHTML = data[i][col[j]];
    }
    tbody.appendChild(tr);
  }
  tbl.appendChild(thead);
  tbl.appendChild(tbody);
  var divCntr = document.getElementById("showData");
  divCntr.innerHTML = "";
  divCntr.appendChild(tbl);
  thead.addEventListener("click", function(event) {
    var key = event.target.dataset.key;
    people = document.getElementById("people");
    sort_tbl(people, key, asc1);
  });
  function sort_tbl(tblSample, key, asc) {
    var rows = tblSample.rows,
      rlen = rows.length,
      arr = new Array();
    for (var i = 0; i < rlen; i++) {
      var cells = rows[i].cells;
      var clen = cells.length;
      arr[i] = new Array();
      for (var j = 0; j < clen; j++) {
        arr[i][j] = cells[j].innerHTML;
      }
    }
    arr.sort(function(x, y) {
      if (isNaN(x[key]) && isNaN(y[key])) {
        var a = String(x[key]).toUpperCase();
        var b = String(y[key]).toUpperCase();
        if (a > b)
          return 1
        if (a < b)
          return -1
        return 0;
      } else {
        return x[key] - y[key];
      }
    });
    for (i = 0; i < rlen; i++) {
      rows[i].innerHTML = "" + arr[i].join("	") + "	";
    }
  }
}

A: Just remove the () from you onclick handler, like this onclick="tblGene".
If you leave the (), you're executing the function as soon as the <input> element is loaded - in your case on page load.


text:
Q: Changing git branches and recreating environments This is more a best practices questions. Sometimes, I'm working on a long term branch and I have to stop it to debug something quick in another branch. In order to do that, I checkout another branch and my project in local and in my remote server changes too (thanks to PhpStorm that connects both). I also do a composer.phar update, doctrine:schema:update and other commands to adapt the project to the new environment. The problem with that is:
1) I waist time changing branchs and using the commands just to debug something quick and then come back to my long term project.
2) The new branch erases new parameters if I had added new ones on the long term branch. I have to remember the values I chose and so on.
3) My database is updated and if I had filled it on the long term branch I loose the content.
The third point is easier to solve. I just have to create another database for the new branch. However, I think I can improve all these steps. Maybe having another folder for the new branche. But how would I do with git that points to only one folder? I would like to know how other developers do that in their everyday work to be more efficient.
Obs: I work on a Symfony project.


text:
Q: Modular arithmetic and inverse functions The question is shown below:
Suppose $S=\{0,1,2,3,4,5,6,7,8,9,10\}$ and that the function $f:S\rightarrow S$ is given by:
$f(x)=6x^2+3x+8$ (mod 11)
Let $T=\{0,5\}$.
Find $f^{-1}\left(T\right)$.
Alright,
so my initial approach with this question was to find the inverse function,
$f^{-1}(x)=\dfrac{\pm\sqrt{24x-183}-3}{12}$, but $f^{-1}x\in S\geq0$
thus,
$f^{-1}(x)=\dfrac{\sqrt{24x-183}-3}{12}$
and then just churn out congruent values of $x=0,5$ in modulo 11 until I find a suitable value for $f^{-1}(x)$ within $S$, but it seems a bit tedious. Anyways, I repeated this churning process until I received the values of $\{2,3,6,10\}$.
Can anyone suggest a faster approach and please advise me if my approach is logically sound.
Many thanks :)

A: Considering the quadratic $f(x)=6x^2 + 3x + 8$ we have a discriminant (in $\Bbb F_{11}$) of
$$D=3^2 - 4 \cdot 6 \cdot 8 \equiv 4 \pmod{11}$$
which is a square (whether it is $\ge 0$ or not is irrelevant, and we don't use $\sqrt{D}$ in finite fields. We just have the two roots $2, -2 \equiv 9$. So $f(x)$ has two roots  $$\frac{-3 + 2}{12} = -1 \equiv 10 \text{ and } \frac{-3 -2}{12} = -5 \equiv 6$$
where we have to remember that $12 \equiv 1 \pmod{11}$ which is helpful.
So modulo $11$ we have that $f(x)=(x+1)(x+5)$ and we've already found two members of $f^{-1}[\{0,5\}]$ namely the roots $10$ and $6$.
Next solve $f(x)=10$ (see below for the correct value) or equivalently $$6x^2 + 3x -2 = 0$$ which has discriminant $$3^2 - 4\cdot 6 \cdot (-2) =  2 \pmod{11}$$ and $2$ is not a square modulo $11$ (the squares in $\Bbb F_{11}$ are $0^2= 0,1^2=1, 2^2=4, 3^2= 9, 4^2=5, 5^2=3, 6^2=3, 7^2=5, 8^2=9,9^2=4,10^2=1$ or use quadratic reciprocity theory, if you know it. So $f$ does not assume the value $10$.
Solve $f(x)=5$ or $6x^2 + 3x+ 3= 0$, discriminant $3^2 - 4\cdot 6 \cdot 3 \equiv 3 \pmod{11}$ which is $5^2$ and $(-5)^2 = 6^2$ so roots are
$$\frac{-3 + 5}{12}=2, \frac{-3+6}{12}=3 \pmod{11}$$
so $$f^{-1}[\{0,5\}] = \{2,3,6,10\}$$ without tedious brute force.

A: If $\ a\equiv \alpha^2\pmod{11}\ $ is a quadratic residue $\mod{11}\ $, then
$$
a^6 \equiv \alpha^{12}\equiv \alpha^2\equiv a\pmod{11}\ ,
$$
so the square roots of $\ a\pmod{11}\ $ are $\ \pm a^3\pmod{11}\ $.
If $\ y\equiv 6x^2+3x+8\pmod{11}\ $ then $\ 2y+4\equiv$$ x^2+6x+9$$\equiv(x+3)^2 \pmod{11}\ $ must be a quadratic residue, so $\ (2y+4)^3\equiv$$\pm(x+3) \pmod{11}\ $, and $\ x\equiv$$\pm(2y+4)^3-3\pmod{11}\ $.
Substituing $\ y=0\ $ in this expression gives $\ x\equiv$$ \pm4^3-3\equiv$$6,10\pmod{11}\ $. Substituting one of $\ x=6,10\ $ back into the polynomial $\ 6x^2+3x+8\ $ shows that it is indeed congruent to $\ 0\mod11\ $ for both of them (this check is necessary for at least one of these two values, to eliminate the possibility that $\ 2\cdot5+4\ $ might have been a quadratic non-residue $\mod 11\ $).
Similarly, substituting $\ y=5\ $ into the expression for $\ x\ $ gives $\ x\equiv$$\pm3^3-3\equiv$$2,3\pmod{11}\ $, which again can be shown to satisfy the congruence $\ 5\equiv 6x^2+3x+8\pmod{11}\ $. Thus, $\ f^{-1}\left(\{0,5\}\right)=$$\{2,3,6,10\}\ $, as you've already established.


text:
Q: Using jQuery .trigger() method within iframe I'm trying to trigger a keydown event on an input element within an iframe, however it doesn't appear to be working:
var $$ = jQuery.noConflict(true);
var $ = jQuery = null;

$$('#myIframe').load(function () {
    $ = jQuery = window.frames[0].jQuery;

    ...

    var e = $.Event("keydown");
    e.which = 68;
    e.keyCode = 68;
    $('#myInput').trigger(e);
});

Similarly it doesn't seem possible to trigger other events, e.g.
$('#myInput').trigger('focus')

What's strange is that I can manipulate this input using other methods, e.g.
$('#myInput').focus();
$('#myInput').val('test');

... but .trigger() just doesn't seem to work. Does anyone have any suggestions?
Thanks in advance!


text:
Q: Text baseline different on IE I have the following CSS to control three a tags which should have vertically central text, however they appear at the top of the button. It's easier to see result.
CSS Code:
color: #fffae6;
border: 1px solid #fff;
outline: 4px solid #242424;
-moz-transition: background 500ms ease-in-out;
-ms-transition: background 500ms ease-in-out;
-o-transition: background 500ms ease-in-out;
transition: background 500ms ease-in-out;
padding: 5px 0;
-webkit-transition: background 500ms ease-in-out;
background: #242424;
font-size: 1.7em;
display: block;
margin: 0 15px;

In chrome:

In IE:

Any ideas?

A: you have to use both the height and line-height property to achieve the same effect in IE.
Check the DEMO.

A: Please use line-height, as per your height of the button. I hope it will work


text:
Q: Array of strings as text for nodes in Tikz I have a rather large number of nodes n1, n2,...,n41, all of them containing expresions like \textcolor{c}{blabla} and \large etc.
It seem when storing all these texts in an array of the form described in
List of strings for tikzpicture
namely
\documentclass{article}

\usepackage{tikz}
\begin{document}
\newcommand\johnlist{{"ala","bla","cla"}}

\begin{tikzpicture}
\node[shape=circle,draw=black] at (0,0) {\pgfmathparse{\johnlist[1]}\pgfmathresult};
\end{tikzpicture}

\end{document}

does not work if for example "bla" is replaced by \Large bla.
So the question is how to create lists or arrays of TeX-compatible strings?

A: Something like this?
\documentclass{article}
\usepackage{tikz}
\newcommand{\green}[1]{\textcolor{green}{#1}}

\begin{document}
\newcommand\johnlist{{"\noexpand\Huge ala","\noexpand\green{{bla}}","\noexpand\bfseries\noexpand\Large cla"}}

\begin{tikzpicture}
\foreach \i in {0,1,2}
{
\node[shape=circle,draw=black] at (\i,0) {\pgfmathparse{\johnlist[\i]}\pgfmathresult};
}
\end{tikzpicture}

\end{document}

A: My impression is that the handling of arrays in PGF is quite fragile.
\documentclass{article}
\usepackage{tikz}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\setlist}{mm}
 {
  \clist_clear_new:c { l_jens_#1_array_clist }
  \clist_set:cn { l_jens_#1_array_clist } { #2 }
 }
\NewExpandableDocumentCommand{\listitem}{mm}
 {
  \clist_item:cn { l_jens_#1_array_clist } { #2 }
 }
\ExplSyntaxOff

\begin{document}

\setlist{john}{\textbf{ala},\Huge bla,\large cla}

\begin{tikzpicture}
\node[shape=circle,draw=black] at (0,0) {\listitem{john}{1}};
\node[shape=circle,draw=black] at (1,0) {\listitem{john}{2}};
\node[shape=circle,draw=black] at (2,0) {\listitem{john}{3}};
\end{tikzpicture}

\bigskip

\begin{tikzpicture}
\foreach \x in { 0,1,2 } {
  \node[shape=circle,draw=black] at (\x,0) {\listitem{john}{\x+1}};
}
\end{tikzpicture}

\end{document}

Note that you can do arithmetic operations on the second argument to \listitem. The indexing starts from 1.

A: You could hack the random list stuff, although specifying items requires braces rather than commas, and indexing starts at 1:
\documentclass[tikz,border=5]{standalone}
\def\pgfmathrandomlistitem#1#2{\pgfmathparse{int(#2)}%
  \csname pgfmath@randomlist@#1@\pgfmathresult\endcsname}

\pgfmathdeclarerandomlist{list1}{%
  {\tiny\textcolor{red}{ala}}
  {\small\textcolor{green}{bla}}
  {\large\textcolor{blue}{cla}}
}
\begin{document}
\begin{tikzpicture}
\foreach \i in {0,...,2}
  \node [circle, draw] at (0, \i) {\pgfmathrandomlistitem{list1}{\i+1}};
\end{tikzpicture}
\end{document}


text:
Q: Why do we want a big parallelism? I would really like to know why we want the ratio T1/T_infinity (the parallelism) to be big?

A: So that you can parallelise the implementation of the algorithm, and achieve a big speedup!
That ratio describes how much speedup you'd get if you used an infinite number of processors compared to just one processor.  So it's an upper bound on how much speedup you'll get with a non-infinite number of processors.
See also: Amdahl's Law.


text:
Q: How do I decompose $\sigma = (15243)$ into $\sigma = (12)(34)(23)(12)(23)(34)(45)(34)(23)(12)$? Let $\sigma = (15243)$. Then two expressions for $\sigma$ as a product of transpositions are
$\sigma = (15)(52)(24)(43)$
and
$\sigma = (12)(34)(23)(12)(23)(34)(45)(34)(23)(12).$
I am having trouble understanding how one can easily go from $\sigma = (15243)$ to$\sigma = (12)(34)(23)(12)(23)(34)(45)(34)(23)(12)$.

A: Even though I strongly agree with what @JMoravitz states in the comments, if you still need to convince yourself about the equality, you can work backwards: work from $(12)(34)(23)(12)(23)(34)(45)(34)(23)(12)$ all the way to $(15243)$:
The way you go about doing this is picking a number from $1$ to $5$, and going through the transpositions to see where it ends up. Say we picked $1$.
A transposition $(1\ a)$ sends $1$ to $a$, just like a transposition $(a\ 1)$.
$$\begin{align} (12)(34)(23)(12)(23)(34)(45)(34)(23)(12)[1] &= (12)(34)(23)(12)(23)(34)(45)(34)(23)[2] \\
&= (12)(34)(23)(12)(23)(34)(45)(34)[3]\\
&= (12)(34)(23)(12)(23)(34)(45)[4] \\
&= (12)(34)(23)(12)(23)(34)[5] \\
&= 5\end{align}$$
Notice I skipped a bunch of steps in the end because in the last transpositions $5$ didn't appear.
In $(15243)$ we also have that $1$ goes to $5$, so we are fine. You can keep doing this if you want for $2, 3, 4$ and $5$.
Another interesting thing would be to find a way of easily turning a permutation into a product of transpositions. There is an easy algorithm for that.


text:
Q: how to get an alert message if the value entered is not found in the array in javascript I have an array of objects and I'm able to loop through the array using a for loop and I can print it to the page without problems if the value is found, but I'm trying to get an alert message to display if the value is not found and continue asking for the next value until the user types quit. The problems with my code is that the alert message keeps appearing until the loops ends if the value is not found. Here's my code:
var message = '';
var student;
var search;

function print(message) {
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}

function getStudentReport( student ) {
  var report = '
Student: ' + student.name + '
';
  report += '
Track: ' + student.track + '
';
  report += '
Points: ' + student.points + '
';
  report += '
Achievements: ' + student.achievements + '
';
  return report;
}

function findStudent( look ){

    for (var i = 0; i < students.length; i += 1) {
        student = students[i];
        if (look === student.name) {
          message += getStudentReport( student );
          print(message);
        } else{
            alert(look + ' was not found');
        }

    }
    print(message);
}

while (true){
  search = prompt('Search student records: type a name [Jody] (or type "quit" to end)');
    if (search === null || search === 'quit'){
        break;
    }
  findStudent(search);

}

Any help is appreciated. Thanks.

A: Lets explain this part of code:
function findStudent( look ) {

    for (var i = 0; i < students.length; i += 1) {
        student = students[i];
        if (look === student.name) {
          message += getStudentReport( student );
          print(message);
        } else{
            alert(look + ' was not found');
        }

    }
    print(message);
}

What that does is it loops with a for loop over an array/object and prints a message or alerts for every record inside the array. That is the problem. You only want to check if the value is found and print or alert if so.
function findStudent( look ) {

    var found = false;

    for (var i = 0; i < students.length; i += 1) {
        student = students[i];
        if (look === student.name) {
            found = true;
            break;  // if the student is found no need to loop further
                    // move on with rest of code
        }
    }

    // so if the student was found in the for loop, found will be true
    // else found will be false cause we set it to false at the beginning
    if(found) {
        message += getStudentReport( student );
        print(message);
    } else {
        alert(look + ' was not found');
    }

}

A: i think it could be help full for you https://codepen.io/kalaiselvan/pen/YQGbar
    var message = '';
    var student;
    var search;
    function print(message) {
      var outputDiv = document.getElementById('output');
      outputDiv.innerHTML = message;
    }

    function getStudentReport( student ) {
      var report = '
Student: ' + student.name + '
';
      report += '
Track: ' + student.track + '
';
      report += '
Points: ' + student.points + '
';
      report += '
Achievements: ' + student.achievements + '
';
      return report;
    }

    function findStudent( look ){
    var flag=0;
        for (var i = 0; i < students.length; i += 1) {
            student = students[i];
            if (look === student.name) {
              message += getStudentReport( student );
              print(message);
              flag=0;
              break;
            } else{
              flag=1;
            }
        }
      if(flag==1){
        alert(look + ' was not found');
        showprompt();
      }
    }

    function showprompt(){
      search = prompt('Search student records: type a name [Jody] (or type "quit" to end)');
      if (search != null && search !== "quit"){
          findStudent(search);
      }
    }
    showprompt();

A: you can use indexof
https://www.w3schools.com/jsref/jsref_indexof_array.asp
else if (students.indexOf(look) == -1){
    alert(look + ' was not found');
})

A: You need to stop the loop inside findStudent() function.
First, add a boolean varible: var flag = true;
Second, use it as condition of while loop: while(flag){...}
Finally, assign flag = falsewhenever want to stop the loop:
function findStudent( look ){
for (var i = 0; i < students.length; i += 1) {
    student = students[i];
    if (look === student.name) {
      message += getStudentReport( student );
      print(message);
      //possible stop here if you want
      flag = false;
    } else{
        alert(look + ' was not found');
      //possible stop here if you want
      flag = false;
    }

}
print(message);
//possible stop here if you want
flag = false;
}

A: var message = '';
var student;
var search;

function print(message) {
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}

function getStudentReport( student ) {
  var report = '
Student: ' + student.name + '
';
  report += '
Track: ' + student.track + '
';
  report += '
Points: ' + student.points + '
';
  report += '
Achievements: ' + student.achievements + '
';
  return report;
}

function findStudent( look ){
    message = '';

    for (var i = 0; i < students.length; i += 1) {
        student = students[i];
        if (look === student.name) {
            message += getStudentReport(student);
        }
    }
    return message;
}

while (true){
  search = prompt('Search student records: type a name [Jody] (or type "quit" to end)');
    if (search === null || search === 'quit'){
        break;
    }

    if(findStudent(search)){
        print(findPurpose(search));
        break;
    } else {
        alert(search + ' was not found');
    }

}


text:
Q: redirect to another view function As users login I'd like to redirect them simply to index instead of having '/login/' in the url.
I have two view functions one for login and index.
index view
def index(request):

    context = {

    }
    return render(request, 'index.html', context)

login view
def login(request):

    username = request.POST.get('username', '')
    password = request.POST.get('password', '')

    user = auth.authenticate(username=username, password=password)

    if user is not None:
        auth.login(request, user)
    else:
        print('Wrong user')

    return redirect('index') #<------ Something like that(?)

url patterns
urlpatterns = [
            url(r'^$', views.index, name='index'),

            url(r'^login/$', views.login, name='login'),
]

Console error:
Correct user
Internal Server Error: /Crowd/login/
Traceback (most recent call last):
  File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 66, in login
    return redirect('index')
  File "C:\Anaconda3\Lib\site-packages\django\shortcuts.py", line 116, in redirect
    return redirect_class(resolve_url(to, *args, **kwargs))
  File "C:\Anaconda3\Lib\site-packages\django\shortcuts.py", line 204, in resolve_url
    return urlresolvers.reverse(to, args=args, kwargs=kwargs)
  File "C:\Anaconda3\Lib\site-packages\django\core\urlresolvers.py", line 600, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "C:\Anaconda3\Lib\site-packages\django\core\urlresolvers.py", line 508, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns))
django.core.urlresolvers.NoReverseMatch: Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
[14/Sep/2016 19:46:12] "POST /Crowd/login/ HTTP/1.1" 500 88875

A: # views.py
def login(...):
    # ...
    return redirect('home')

and:
# urls.py
urlpatterns = [
    url(r'^$', 'views.index', name='home'),
    # ...
]


text:
Q: Python parallelism preserving data I need to repeatedly calculate very large python arrays based on small input and very large constant bulk if data, stored on the drive. I can successfully parallelize it by splitting that input bulk and joining response. Here comes the problem: sending identical data bulk to the pool is too slow. Moreover, I double required memory. Ideally I would read data in the thread from the file, and keep it there for multiple re-use.
How do I do it? I can only think of creating multiple servers that will listen to requests from the pool. Somehow it looks unnatural solution to quite common problem. Do I miss better solution?
best regards,
Vladimir


text:
Q: SQL Server Multiple Index Solution? Let's assume we have a table with name Tournament and columns of this table are Id, Name, GameId, TypeId, cityId, Status, Format. Except Id and Name columns I want to search this table with all of the combinations of these columns, I mean I can search with GameId & Status or TypeId & CityId & Status or Status & Format.
As you can see all of the search options count is equal to
=C(5,1)+C(5,2)+C(5,3)+C(5,4)+C(5,5).

So here is my question,what is the best indexing scenario and why? I think the options are,

*

*Index for each column.

*Composite ındex for all columns.

I know composite index is really faster than single index but if you go correct order, I mean if I have a composite index on [GameId, TypeId, CityId, Status, Format] columns and search like GameId = 1 & TypeId = 2 & CityId = 3 & Status = 5 & Format = 6 it will work great, but how about if I search GameId = 1 & Format = 6 I can not realize how this query will works fast enough, as I know SQL Server composite index is just a b-tree and the b-tree keys of composite index are ordered from left to right columns.


text:
Q: Create additionals vhost/user/pass for RabbitMQ at helm chart for Kubernetes Edit: I need to set some additionals rabbit vhost/users/pass at helm charts for a rabbitMQ we use in K8s, I tried via curl in a lifecyle postStart hook:
Here's an example:
lifecycle:
  postStart:
    exec:
      command: ["'/bin/sh', '-c','curl -i -u guest:guest -H ''content-type:application/json'' -XPUT -d '''{'password':'1234','tags':'monitoring'}''' http://localhost:15672/api/users/deleteme'"]

But fails :
Killing container with id docker://rabbitmq:FailedPostStartHook

I tried changing quotation and also setting it like:
command:
 - "sh":
 - "-c":
 - etc....

With no success, it's the first time I'm using hooks, any advice, please?
Thanks!
full statefulset:
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: {{ .Chart.Name }}
  labels:
    app: {{ .Chart.Name }}
spec:
  serviceName: {{ .Chart.Name }}
  replicas: {{ .Values.replicaCount }}
  updateStrategy:
    type: {{ .Values.updateStrategy }}
  template:
    metadata:
      labels:
        app: {{ .Chart.Name }}
    spec:
      terminationGracePeriodSeconds: 10
      containers:
        - name: {{ .Chart.Name }}
          image: {{ .Values.image.repository }}:{{ .Values.image.tag }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: epmd
              protocol: TCP
              containerPort: 4369
            - name: amqp
              protocol: TCP
              containerPort: 5672
            - name: http
              protocol: TCP
              containerPort: 15672
          livenessProbe:
            exec:
              command:
                - rabbitmqctl
                - status
            initialDelaySeconds: 30
            timeoutSeconds: 5
          readinessProbe:
            exec:
              command:
                - rabbitmqctl
                - status
            initialDelaySeconds: 10
            timeoutSeconds: 5
          env:
            - name: MY_POD_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: RABBITMQ_USE_LONGNAME
              value: "true"
            - name: RABBITMQ_NODENAME
              value: "rabbit@$(MY_POD_IP)"
            - name: K8S_SERVICE_NAME
              value: {{ .Chart.Name }}
            - name: RABBITMQ_ERLANG_COOKIE
              valueFrom:
                secretKeyRef:
                  name: {{ .Chart.Name }}
                  key: rabbitmq-erlang-cookie
            - name: RABBITMQ_DEFAULT_USER
              value: {{ .Values.rabbitmqUsername | quote }}
            - name: RABBITMQ_DEFAULT_PASS
              valueFrom:
                secretKeyRef:
                  name: {{ .Chart.Name }}
                  key: rabbitmq-password
            - name: RABBITMQ_DEFAULT_VHOST
              value: {{ .Values.rabbitmqVhost | quote }}
          volumeMounts:
            - name: data
              mountPath: /var/lib/rabbitmq
            - name: config
              mountPath: /etc/rabbitmq
          lifecycle:
              postStart:
                exec:
                  command:
                  - "sh"
                  - "-c"
                  - "curl -i -u guest:guest -H \"content-type:application/json\" -XPUT -d \"{\"password\":\"1234\",\"tags\":\"monitoring\"}\" http://rabbitmq:15672/api/users/deleteme"
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 1
              podAffinityTerm:
                topologyKey: kubernetes.io/hostname
                labelSelector:
                  matchLabels:
                    app: {{ .Chart.Name }}
      volumes:
        - name: config
          configMap:
            name: {{ .Chart.Name }}
        - name: data
          emptyDir: {}

I might ending up using values or trying to set it up at configmap:
https://github.com/helm/charts/tree/master/stable/rabbitmq-ha
If there's a better way, would be great.

A: I would recommend to look at Helm Hooks. They consist with various options to interpose at certain phases of the development life cycle. Hooks represent themselves as regular templates, however they require a special annotations to be set in order Helm to interpret them correctly.
apiVersion: ...
kind: ....
metadata:
  annotations:
    "helm.sh/hook": "pre-install"
# ...

You can consider to run a Job with post-install hook which executes after all resources are loaded into Kubernetes.


text:
Q: how to turn off wifi,bluetooth,data,gps,and reduce disable brightness-voloms in android? i need to turn off all services in android (wifi,bluetooth,data,gps,and reduce display brightness-voloms) XD.
i just google it and found some of them but couldn't find all theese.
can anyone help me?

A: you can turn ON/OFF  wifi,bluetooth,reduce display brightness-volume but you can't directly to for mobile data and gps. for those things you need to Manually push an intent.
bluetooth,WiFi ,brightness,Volume, GPS ,mobile-data


text:
Q: RavenDB and IDocumentStoreListener I am trying to add an autoincrement to a simple model via an IDocumentStoreListener. I have found that the documentation regarding implementation of this feature is fairly sparse (any pointers would be greatly appreciated). I have been trying to follow this blog post but it appears to be out of date. When i try to implement
store = new EmbeddableDocumentStore
{
    RunInMemory = true
}
.RegisterListener(new AuditableEntityListener(() => "Test User"))
.Initialize();

I get a build error stating "Cannot convert lambda expression to type Raven.Client.IDocumentStore because it is not a delegate type".
I managed to get it to build by using this code
store = new EmbeddableDocumentStore
    {
        RunInMemory = true
    }
    .RegisterListener(new AuditableEntityListener(store ))
    .Initialize();

The code for the listener is as follows
public class PublicIdStoreListener : IDocumentStoreListener
    {

        HiLoKeyGenerator generator;
        IDocumentStore store;
        public PublicIdStoreListener(IDocumentStore store)
        {
            this.store = store;
            generator = new HiLoKeyGenerator(store, "verifications", 1024);
        }

        public void AfterStore(string key, object entityInstance, RavenJObject metadata)
        {
            throw new NotImplementedException();
        }

        public bool BeforeStore(string key, object entityInstance, RavenJObject metadata)
        {
            var verification = entityInstance as VerifyAccountModel;
            if (verification.PublicId == "0")
            {
                verification.PublicId = generator.GenerateDocumentKey(store.Conventions, entityInstance);
            }
            return false;
        }
    }

However, when i run  the application it hits the PublicIdStoreListener when any document is stored, not just the VerifyAccountModel, which causes the application to throw an exception.
I was wondering if anyone can point me in the right direction on this as I am confused as to how this is actually supposed to be implemented. Thanks in advance.
EDIT
I updated the documentlistener to the following
public bool BeforeStore(string key, object entityInstance, RavenJObject metadata)
        {

            if (entityInstance.GetType() == new VerifyAccountModel().GetType())
            {
                var verification = entityInstance as VerifyAccountModel;
                if (verification.PublicId == "0")
                {
                    verification.PublicId = generator.GenerateDocumentKey(store.Conventions, entityInstance);
                }
            }
            return true;
        }

UPDATE
I figured out that i cant attach the store via RegisterListener in the same line that it is instantiated. It has to be done afterwards otherwise the store is still null when passed in. Thank you for your help.

A: I am not sure if there's a way to register the listener to only fire for certain types, but you can certainly structure your code to only process VerifyAccountModel entities.
var verification = entityInstance as VerifyAccountModel;
if (verification == null)
    return false; // We can't do anything, just let it pass through

Also, my understanding is that you should return true when you make a change, false if no change was made. This determines whether the entity needs to be re-serialized. If that is correct, the whole thing might be restructured as follows.
var verification = entityInstance as VerifyAccountModel;
if (verification != null && verification.PublicId == "0")
{
    verification.PublicId = generator.GenerateDocumentKey(store.Conventions, entityInstance);
    return true; // change made, re-serialize
}

return false; // no change made


text:
Q: changing the path to which pv is pointing I want to change the path to which the following pv is pointing. I am using Elasticsearch helm chart provided by elastic.coRefer to the below ss.
Here I am providing the link to the statefulset.yaml.


text:
Q: Label appendix as Appendix I, II, III rather than Appendix A, B and C When I am using the \appendix it is automatically naming the Appendix as Appendix A, A.1, A.2 etc.
Is there a way to change it to Appendix I, I.1, I.2, II.1, etc?
here is my current appendix commands:
\appendix
\include{AppendixA}
\cleardoublepage
\include{AppendixB}
\cleardoublepage

A: This depends on your document class. If it has \chapters, then you can use
\renewcommand{\thechapter}{\Roman{chapter}}

otherwise (if it the highest sectional unit is \section), use
\renewcommand{\thesection}{\Roman{section}}

after \appendix. Combining this into the document preamble (not a bad thing), you could use
\let\oldappendix\appendix
\renewcommand{\appendix}{%
  \oldappendix%
  \renewcommand{\the<unit>}{\Roman{<unit>}}}%

where <unit> defines the highest section unit in your class (say chapter or section).

A: With the standard LaTeX classes, KoMa-script ones and also memoir, the definition can be patched quite safely (before hyperref, if this package is loaded):
\usepackage{etoolbox}
\makeatletter
\patchcmd{\appendix}{\@Alph}{\@Roman}
  {}{\@latex@warning@no@line{\protect\appendix\space couldn't be patched}
\makeatletter

If the patch is not successful, which LaTeX will warn you about, it may be because the class already loads hyperref (which is not recommended, actually); in that case, try
\usepackage{etoolbox}
\makeatletter
\patchcmd{\HyOrg@appendix}{\@Alph}{\@Roman}
  {}{\@latex@warning@no@line{\protect\appendix\space couldn't be patched}
\makeatletter

because this is the "original" command as saved by hyperref.


text:
Q: How to generate random numbers from convex combination of densities? I'm solving a numerical problem in Matlab and I need to generate a sample from a non-standard probability density function. I'm fully aware of that old trick of inverting the cumulative distribution function and applying it on random numbers from an Uniform $[0,1]$ distribution but I think this won't do the trick here, since there's no closed form for the desired cdf.
Let $J$ be a fixed integer (odd). Define $\theta_{j} = j - (J+1)/2$, for all $j = 1, 2, ..., J$. Let $f(x, \theta)$ be the probability density function of a Normal $(\theta, 1)$ distribution. Now we define the following density:

$g(x) = \frac{\sum_{j=1}^{J}f(x,\theta_{j})}{J}$

It's easy to see that $g( ) $ has all of the good properties of pdf. My question is how to generate a sample coming from this density. I'm working on Matlab but I think the same procedure would work everywhere. Any ideas or hints?

A: Pick $j$ uniformly, and then pick $x$ from the $N(\theta_j,1)$ distribution.
ADDED:  this works because the density function of the output of this process matches your $g$ formula.  For any set $A$, we have $P(x \in A)$ is given by $\sum_{i=1}^J \int_A f(y,\theta_j) \,dy$, by conditioning on the randomly chosen $j$. But this is exactly what your $\int_A g(y)\,dy$ gives.


text:
Q: Python: unexplode many boolean columns of Pandas DataFrame into one column? You have data in Pandas dataframe like
>> pd.DataFrame({'Cat' : [1,0,0], 'Fish' : [0,0,1], 'Parrot' : [0,1,0]})

Cat | Fish | Parrot
1   |  0   |   0
0   |  0   |   1
0   |  1   |   0

and you want
Animal
Cat
Parrot
Fish

how can you unexplode the boolean columns into the multivariate column with Animal heading?


text:
Q: How to hide variables in package.json I have the following scripts in my package.json file
"docker-build": "docker build -t mouchin/my-image-name .",
    "docker-push": "docker push mouchin/my-image-name:latest",
    "deploy-server": "ssh root@myserverip 'docker pull mouchin/my-image-name:latest'",
    "deploy": "npm run docker-build && npm run docker-push && npm run deploy-server"

Problem is that i want to hide
mouchin/my-image-name and  root@myserverip
Using some sort of env, maybe saving my variables in .env.prod  , but i dont know if i can read the variables saved there directly into package.json

A: You can use environment variables in your rpm scripts just as you would if you execute the command on the command line (for example $SSH_HOST). However those variables will need to be set directly in the shell that executes the nom script.
Now in order to get the environment variables from an env file loaded, you have to do so manually. For example using a snippet like this:
if [ ! -f .env ]
then
export $(cat .env | xargs)
fi

Source
To execute this before any other script, you could use the built-in lifecylce scripts of npm.
Perhaps, you also want to change the snippet code to load one or the other .env file in case you have one for production and one for development. You will probably be able to use the environment variable NODE_ENV for this, as it is used in most setups, however this last step really depends on your build setup.


text:
Q: Support for lower resolutions with ScrollViewer I have a Silverlight application that is designed for a certain minimum resolution with layout growing gracefully if more space is available. What I want to do now is easily add some crude support for lower resolutions.
To do that, I introduced ScrollViewer as the layout root - the idea was to show appropriate scrollbars when screen is lower then the fixed minimum so the user can scroll the main layout. The problem is, now the whole layout grows without any bounds and scrollbars appear regardless of screen size.
One solution is to set the content's fixed size equal to the minimum supported size. This, however, kills the graceful growing if screen is larger. Or, I imagine, I could programmatically set the maximum size to what I determine is screen resolution.
Is there any way to do this elegantly in XAML?

A: Try looking at the MinWidth and MaxWidth properties, as well as MinHeight and MaxHeight. The ScrollViewer also has VerticalScrollbarVisibility and HorizontalScrollbarVisibility which may help. Both of these can be set to Disabled (different to just Hidden), which will set the dimensions of the content accordingly. See here.
I've just looked at a working scrollviewer I put in my application. I didn't specify any width or height on the control that is inside the scrollviewer. I specified HorizontalScrollBarVisibility="Disabled" and I laid out the controls inside a grid inside the scrollviewer. The grid expands to the width available and it scrolls vertically as I wanted it to.


text:
Q: Microsoft Dynamics 2013 and Microsoft Dynamics 365 works with same Rest API? I am working on an extension for dynamics.
Here i want to use dynamics api.
One client uses Microsoft Dynamics 365 (Rest API) and
another client uses Microsoft Dynamics 2013.
Can i use same api to serve both the clients ?
Currently i am using api's from
https://learn.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/web-api-functions-actions-sample-csharp
Will it work for Microsoft Dynamics 2013?

A: The Dynamics 365 Web API did not exist in CRM 2013, so you cannot use that for both purposes.
Instead you can use the Organization Service (also called the CRM 2011 endpoint). The behavior of this endpoint has been relatively consistent (with some minor changes to how e.g. updates should be made) from CRM 2013 to D365.
Be aware that the Organization Service will be removed at some point in the future, but currently works just fine:

The Web API is intended to replace the CRM 2011 endpoint, also known
  as the SOAP endpoint, for accessing the Dynamics 365 organization web
  service and other provided web services.
As of the release of Microsoft Dynamics CRM Online 2016 Update 1 and
  Microsoft Dynamics CRM 2016 Service Pack 1 (8.1.0), the CRM 2011
  endpoint has been deprecated. The 2011 endpoint will be removed some
  time after the release of Dynamics 365 version 9.

A: No you cannot use D365 Web API for both.
I found this is useful for CRM 2013.
http://xrmenterprise.com/2013/09/microsoft-dynamics-crm-2013-client-api-cheat-sheet/


text:
Q: Using Delphi to read emails subfolders in InBox on Thunderbird I need to read emails from Thunderbird email client for all accounts Inbox and all his subfolders.
How I change the code to read all email from every subfolders?
Thanks
With this code (get from examples by Jedy libraries) I read emails only from default InBox Folder:
DownloadsListView.Items.Clear;
JvMail1.LogonOptions := [JvMail.loNewSession, JvMail.loDownloadMail];
JvMail1.LogOn;
try
  b := JvMail1.FindFirstMail;
  while b do
  begin
    JvMail1.ReadOptions := [roFifo, roHeaderOnly, roPeek];
    JvMail1.ReadMail;
    with DownloadsListView.Items.Add do
    begin
      Caption := JvMail1.Subject;
      SubItems.Add(JvMail1.ReadedMail.RecipientName);
      SubItems.Add(DateTimeToStr(JvMail1.ReadedMail.DateReceived));
    end;
    b := JvMail1.FindNextMail;
  end;
finally
  JvMail1.LogOff;
  JvMail1.Clear;
  DownloadsListView.BringToFront;
end;

A: TJvMail is a wrapper for SimpleMAPI, which has no concept of subfolders, and can only access a profile's inbox. You would need to use CDO or Extended MAPI to have full access to a profile's subfolders, but TJvMail does not support that.
Differences between CDO, Simple MAPI, and Extended MAPI
Alternatively, use the IMAP protocol (such as via Indy's TIdIMAP4 component) to access the email server directly, instead of accessing the user's local email client.


text:
Q: Can't hover the child menu while creating css menu I am trying to create simple css menu with the following structure:

                Menu 1

 Sub menu 1

 Sub menu 2

 Sub menu 3

 Sub menu 4

 Sub menu 5

        ...

I trigger the menu with this css
.multiColumnMenu > li:hover  .column-menu{
    display: block;
}

The menu shows up but I can't hover over it. When I hover over it, it goes away.
Demo

A: It's the margin-top inside .column-menu causing it to disappear before you can hover over (due to the physical gap between the elements, the :hover state is lost) - remove that and it works fine.
jsFiddle here.

A: THe quick and easy fix, but I dont think this is exactly how you want it to be done is to take your margin-top: 8px completely off. That will make your dropdown work. See code below
 .column-menu {
display: none;
left: 5px;
margin-top: 0px;
width: 300px;
height: 200px;
color: #7B0000;
background: rgb(252, 252, 252);
border: 1px #ccc solid;
border-bottom: 3px #ccc solid;
position: absolute;
z-index: 20;
  }


text:
Q: Android: Problem playing videos from internal storage I'm trying to play a video file with this code:
MediaController mc = new MediaController(this);
 mc.setAnchorView(videoView);
 mc.setMediaPlayer(videoView);
 Uri video = Uri.parse(path);
 videoView.setMediaController(mc);
 videoView.setVideoURI(video);
 videoView.start();

With videos located on the SD card it works great, but when I try to play a video from the internal storage it says it's unable to play the video.
Now, I think (but not sure) it has something to do with the fact that maybe the videos in the internal storage don't have the necessary permissions.
What do you think?

A: Context.MODE_WORLD_WRITEABLE does not imply Context.MODE_WORLD_READABLE.
Probably you only want only readable, but you can "or" the constants together if you do want both.


text:
Q: Как изменить иконку узла JTree исходя из значения листов? Вот пример:

Исходя из успешности выполнения тестовых методов должна меняться иконка у узла, представляющего класс, в котором эти тестовые методы написаны. То есть на классе TestMyAssert должен быть крестик, если в классе выполнились все методы - должна быть галочка. Как я понял, сначала отрисовываются узлы, а потом уже листья в JTree.
Рисовальщик у меня такой:
class RedTreeCellRenderer extends DefaultTreeCellRenderer {
/**
 *
 */
private static final long serialVersionUID = 707287337017494764L;

@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
        boolean isSelected, boolean expanded, boolean leaf, int row,
        boolean hasFocus) {
    super.getTreeCellRendererComponent(tree, value, isSelected, expanded,
            leaf, row, hasFocus);
    setForeground(getTextSelectionColor());
    DefaultMutableTreeNode treenode = (DefaultMutableTreeNode) value;
    Object ob;
    if (leaf) {
        ob = treenode.getUserObject();
        if (((MyTreeLeaf) ob).getMessanger().isFailed()) {
            setIcon(new ImageIcon("images/redkrest.png"));
        } else if (((MyTreeLeaf) ob).getMessanger().isFailure()) {
            setIcon(new ImageIcon("images/blueminus.png"));
        } else {
            setIcon(new ImageIcon("images/green.png"));
        }
    }
    return this;
}
}

У меня был только один вариант: взять родителя и установить соответствующую иконку ему. Пробовал так:
treenode.getParent();

Но этот метод возвращает объект класса TreeNode, а у него нет метода setIcon()


text:
Q: send sensor's raw data using network socket on Android I'm trying to make an app that reads sensor (gyroscope) raw data and send it, on real-time, to other device using socket.
I've already implemented a simple communication between the two sides by using  Java Socket class inside an AsyncTask and it works fine with dummy data.
I'm not sure how should I integrate the whole reading raw data from sensor part with the socket part.
A button click should triger the start of sensor read and from that moment, in every 10ms a sample should be made and the sampled data should be sent via the socket.
Should I use another asyncTask for reading data from sensor? How can I send the data sampled from the sensor to the socket's AsyncTask while it executed? What is the best practise in this sutuation?
Here's the code I already hava (only socket handling, no sensor)
MainActivity:
public class MainActivity extends AppCompatActivity {

Button btnConnect, btnCloseSocket;
EditText etIP;
EditText etPort;
boolean isConnected = false;
ConnectToServerAsyncTask connectToServerAsyncTask = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnConnect = (Button) findViewById(R.id.btn_connect);
    btnCloseSocket = (Button) findViewById(R.id.btn_closeSocket);
}

public void socketOperationRequest(View view) {

    if (!isConnected) {
        connectToServerAsyncTask = new ConnectToServerAsyncTask(MainActivity.this);
    }
    switch (view.getId()) {
        case R.id.btn_connect:
        {
            isConnected = true;
            etIP = (EditText) findViewById(R.id.et_ip);
            etPort = (EditText) findViewById(R.id.et_port);
            String IP = etIP.getText().toString();
            String port = etPort.getText().toString();
            connectToServerAsyncTask.execute(IP, port);
            btnConnect.setEnabled(false);
            btnCloseSocket.setEnabled(true);
            break;
        }
        case R.id.btn_closeSocket:
        {
            isConnected = false;
            connectToServerAsyncTask.cancel(true);
            btnCloseSocket.setEnabled(false);
            btnConnect.setEnabled(true);
            break;
        }
    }

}

}
AsyncTask:
public class ConnectToServerAsyncTask extends AsyncTask<String,String,String> {

Context context;
Socket socket;
OutputStream os;
//boolean running = true;

public ConnectToServerAsyncTask(Context ctx) {
    this.context = ctx;
}

@Override
protected String doInBackground(String... strings) {
    String IP = strings[0];
    String port = strings[1];
    InputStream is = null;
    int data = 1;
    try {
        InetAddress inetIP = InetAddress.getByName(IP);
        socket = new Socket(inetIP, Integer.parseInt(port));
        os = socket.getOutputStream();
        publishProgress("test");
        while(!this.isCancelled()){
            os.write(data);
            Thread.sleep(2);
        }

    } catch (UnknownHostException e) {
        publishProgress("Exception");
        e.printStackTrace();
    } catch (IOException e) {
        publishProgress("Exception2");
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    String message = values[0];
    Toast.makeText(this.context, message, Toast.LENGTH_LONG).show();
}
@Override
protected void onCancelled() {
    super.onCancelled();
    try {
        os.flush();
        os.close();
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}
Sorry for my bad English,
Thanks

A: First, you should find your sensor in the SensorManager. For example (replace your os.write loop with this, then add an infinite sleep loop like you have):
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor gyro = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
sensorManager.registerListener(new MySensorListener(), gyro, SensorManager.SENSOR_DELAY_FASTEST);

Then you should implement the listener, to write to the os from it's onSensorChanged methods.
Make sure to unregister that listener (unregisterListener) before you close your stream.
For more information see the Android documentation: https://developer.android.com/reference/android/hardware/SensorManager.html


text:
Q: Secure Restful Spring boot application I have developed a RESTful web service using Spring Boot. Once a URL is entered, a JSON resource is returned. The server side is not perfectly JSON API conformed but it works.
Now I want to secure the RESTful service with simple HTTP basic authentication. Simply put, if a client send a HTTP GET in order to access
http://mycompany.com/restful/xyz

it will receive a HTTP unauthenticated error, unless the request is configured with proper Authorization basic XXXXXXXX. The xxxxxx is the encrypted form of user:pwd
I wanted to do it with Spring Security. After some googling I might need to create some class like:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
     ....
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      ....
    }
}

There are two things I need to understand:

*

*Most Spring Security sample I found were somehow related to web application using Spring MVC, but I am sure that it can be used in a scenario as shown above - a standalone web service (in a Tomcat all right, but not a web app);

*Can anyone show some code snippet in the two methods above that work to the effect that only certain user/pwd is allowed to pass the filter to the resource,
http://mycompany.com/restful/xyz

otherwise a HTTP authentication error code is returned.
Can anyone help?

A: You can have something like this:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/restful/**").hasRole("ROLE_USER").and().httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("john").password("mypass").roles("ROLE_USER");
    }
}


text:
Q: issues with jmeter concurency testing I'm doing stress test on my web server, using 8 different clients in jmeter:

*

*3 of them are on SunOS 5

*3 of them are on SunOS 5 but in virutalbox

*2 of them are on linux

If I do a test only using clients which are on SunOS machines I receive best result (my web server can service ~1300 req/sec). If I make a test using all client machines, my result is ~half (600-800 req/sec) of result which I get using only 3 SunOS machines.
Can someone explain to me why?

A: My guess would be network congestion or network overhead. Your jmeter machines not only connect to the client, but they are also sending back results to the jmeter master machine. More jmeter machines does not always mean more load on your application.
Try to find httpd timing logs, and try to find network througput for all machines and see what you come up with. Hope this helps. Cheers!


text:
Q: How to find out the interval within which probability of sample mean lying within +/- a units of population mean is 0.95 using python? I am a beginner in the field of statistics and data science, so request you to treat me kindly.
I have to solve the following problem in python:
Problem statement - Suppose the population variable X is N(3, 0.3) and n = 20. How large an interval must be chosen so that the probability is 0.95 that the sample mean  ¯  lies within ±a units of the population mean μ?
I know 68% data lies within 1 standard deviation ie 2.7 to 3.3. 95% data lie within 2 standard deviations ie 2.4 to 3.6.
My code:
 from scipy.stats import norm
  a,b = norm.interval(alpha=0.95, loc=3, scale=0.3)
  print(b-a)

Output:
1.1759783907240324

But the answer (b-a) is incorrect as its not matching the predefined answer of the hidden test case.
On printing a,b values I got:
a= 2.412010804637984
b= 3.587989195362016
May be I did not get the question correctly or I am not computing in a proper way.
Edited
Attempt 2
from scipy.stats import norm
import numpy as np
a,b = norm.interval(alpha=0.95, loc=3, scale=np.sqrt(0.3))
print(b-a)   # 2.147032972460588
print(a,b)    # 1.9264835137697058 4.073516486230294

Using the concept μ=¯ ± Z(σ/√n). ¯ is sample mean. μ is population mean. 95% is confidence interval.
Attempt 3
from math import sqrt
u=3+(1.96*(0.3/(sqrt(20))))
l=3-(1.96*(0.3/(sqrt(20))))
u-l   # 0.2629615941539756

Attempt 4
from math import sqrt
u=3+(1.645*(0.3/(sqrt(20))))
l=3-(1.645*(0.3/(sqrt(20))))
u-l   # 0.22069990937922945

All attempts are showing incorrect answers.
Kindly suggest me what to do.

A: Your formula is correct, but you need to divide  0.95  in half and find that probability inside the body of the table. Then read on the top and left margins the number of standard deviations it takes to get this level of probability.
So your py code would be:
from scipy.stats import norm

a,b = norm.interval(alpha=0.475, loc=3, scale=0.3)
print(b-a)

Interval would be .38

A: You were right at the beginning. It is just a matter to how accurate you want the results.
"I know 68% data lies within 1 standard deviation ie 2.7 to 3.3. 95% data lie within 2 standard deviations ie 2.4 to 3.6." That is roughly speaking as in https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule
Please note that 1.1759783907240324 is very similar to 1.2 = 3.6-2.2
You can reproduce the 1.17597839072 as follow:
u=3+(1.96*(0.3))
l=3-(1.96*(0.3))
print(u-l)
1.1760000000000002

Note that that if 0.3 is already the standard deviation there is no need to divide by sqrt(20). That could be useful if you were doing a t-test in line with https://en.wikipedia.org/wiki/Confidence_interval
The 68–95–99.7 rule
can be easily check in python as follow.
a,b = norm.interval(alpha=0.69, loc=0, scale=1)
print('one std to each side: ',b-a)
print('with a: ',a)
print('with b: ',b)

a,b = norm.interval(alpha=0.95, loc=0, scale=1)
print('two std to each side: ',b-a)
print('with a: ',a)
print('with b: ',b)

With output:
one std to each side:  2.0304440664340557
with a:  -1.0152220332170279
with b:  1.0152220332170279
two std to each side:  3.919927969080108
with a:  -1.959963984540054
with b:  1.959963984540054

As you can see for one standard deviation +-1 and +-1.96 for two.
I could do the same with our own functions:
#a,b = norm.interval(alpha=0.69, loc=0, scale=1)
b=0+(1*(1))
a=0-(1*(1))
print('one std to each side: ',b-a)
print('with a: ',a)
print('with b: ',b)
#a,b = norm.interval(alpha=0.95, loc=0, scale=1)
b=0+(1.96*(1))
a=0-(1.96*(1))
print('two std to each side: ',b-a)
print('with a: ',a)
print('with b: ',b)

With output:
one std to each side:  2
with a:  -1
with b:  1
two std to each side:  3.92
with a:  -1.96
with b:  1.96

As you can see for one standard deviation +-1 and +-1.96 for two.
As expected-->  https://en.wikipedia.org/wiki/68–95–99.7_rule


text:
Q: PHP and JSON comment help thanks for looking
my problem is that i cant seem to get jquery to display my generated data.
here is my JSON output
("posts":[{"id":"1-2","time":"0","name":"dash","avatar":"http:\/\/www.gravatar.com\/avatar\/9ff30cc2646099e31a4ee4c0376091b0?s=182&d=identicon&r=PG","comment":"rtetretrete tet rt uh utert"},{"id":"2-2","time":"0","name":"james","avatar":"http:\/\/www.gravatar.com\/avatar\/d41d8cd98f00b204e9800998ecf8427e?s=182&d=identicon&r=PG","comment":"fsdfdfsdf\r\n"}])

and here is my jquery
    $(document).ready(function(){
        var url="comments.php";
        $.getJSON(url,function(json){
            $.each(json.posts,function(i,post){
$("#content").append(
    '
'+
        '
'+post.name+'
'+
        '
'+post.comment+'
'+
        '
added: '+post.time+'
'+
        '
posted by: '+post.name+'
'+
        '
avatar: '+post.avatar+'
'+
    '
'
); });
});
    });

A: I have just tried to validate your JSON using http://www.jsonlint.com/
And it failed:
syntax error, unexpected TINVALID, expecting '{' or '[' at line 1
Parsing failed

The overall (outside) brackets need to be changed from ( and ) to { and } This will validate your JSON and the script should work fine

A: I didnt check your syntax for you json, but if it is correct then try this before sending the output (in PHP file)
header ('Content-type: application/json');

A: Your Json object is missing leading and trailing curly braces, thus is not valid.
Try to add them:
{"posts":[{"id":"1-2","time":"0","name":"dash","avatar":"http:\/\/www.gravatar.com\/avatar\/9ff30cc2646099e31a4ee4c0376091b0?s=182&d=identicon&r=PG","comment":"rtetretrete tet rt uh utert"},{"id":"2-2","time":"0","name":"james","avatar":"http:\/\/www.gravatar.com\/avatar\/d41d8cd98f00b204e9800998ecf8427e?s=182&d=identicon&r=PG","comment":"fsdfdfsdf\r\n"}]}

A: json should be
{
    "posts": [
        {
            "id": "1-2",
            "time": "0",
            "name": "dash",
            "avatar": "http:\/\/www.gravatar.com\/avatar\/9ff30cc2646099e31a4ee4c0376091b0?s=182&d=identicon&r=PG",
            "comment": "rtetretrete tet rt uh utert"
        },
        {
            "id": "2-2",
            "time": "0",
            "name": "james",
            "avatar": "http:\/\/www.gravatar.com\/avatar\/d41d8cd98f00b204e9800998ecf8427e?s=182&d=identicon&r=PG",
            "comment": "fsdfdfsdf\r\n"
        }
    ]
}

use jsonLint to validate json..


text:
Q: Timestamp 201512250445 update in Minutes I get the link of satellite images(weather satellite images) from sat24, but the sat24 keeps updating the time of images in timestamp UTC, for example: 201512250445. I want to add some code, to get the timestamp UTC but the time keeps updating every 15 min, example:  201512250430, 201512250445, because the sat24 updates every 15 min in timestamp UTC
I am trying but I get undefined time
    var region = "" + 'sa' + "";
    var imageType = "" + 'visual5HDComplete' + "";
    var imageCount = 0 + 10 +0;
    var allowZoom = 'False' == 'True';
    var AmazonUrl = "" + '' + "";
    var satbeelden = 0 + 10 + 0;
        var expDate = new Date();

    var minutes = 480;
    expDate.setTime(expDate.getTime() + (minutes * 60 * 1000));
    //(this.refspot4 != null) $.fn.cookie("satrefspot4-v2", this.refspot4.toString(), { expires: expDate, path: '/' });
    var zoomX = 0;
    var zoomY = 0;
    var iszoom = false;

    var arrayImageTimes = [];
    arrayImageTimes.push("" + minutes + "");
    arrayImageTimes.push("" + minutes + "");
    arrayImageTimes.push("" + minutes + "");
    arrayImageTimes.push("" + minutes + "");
    arrayImageTimes.push("" + minutes + "");
    arrayImageTimes.push("" + minutes + "");
    arrayImageTimes.push("" + minutes + "");
    arrayImageTimes.push("" + minutes + "");
    arrayImageTimes.push("" + minutes + "");
    arrayImageTimes.push("" + minutes + "");

A: Just normalize that:
var region = 'sa';
var imageType = 'visual5HDComplete';
var imageCount = 10;
var allowZoom = false;
var AmazonUrl = '';
var satbeelden = 10;
var expDate = new Date();

var quarter= 15*60*1000;
var currentTimeMillis = expDate.getTime();
var nearestQuarter =  Math.round(currentTimeMillis / quarter) * quarter;

var zoomX = 0;
var zoomY = 0;
var iszoom = false;

var arrayImageTimes = [];
for ( var n = 0; n < 10; n++ ) {
    arrayImageTimes.push(nearestQuarter);
    nearestQuarter += quarter;
}

This would give you an array of the next ten full quarters stored as milliseconds since the epoch.

A: This code 'alert's current date-time in the format you would like to see rounded to 15 minutes:
var d = new Date();
var t = d.getTime();
d.setTime(t-t%(1000*60*15));
alert(f2(d));

function f(n) { return ('0'+n).slice(-2); };
function f2(d) {
    return d.getUTCFullYear()+f(d.getUTCMonth() + 1)+f(d.getUTCDate())+f(d.getUTCHours())+f(d.getUTCMinutes());
};

https://jsfiddle.net/ja81uLu8/


text:
Q: Creating Correlation Matrix-style table in Python I'm trying to create a correlation matrix / contingency table style output for my data. I am working with a dictionary that contains overlap measures for (differing number of) clusters.
overlap={(0,0): 0.5, (1,0):0.2, (1,1):0.0}

Overlap btw clusters "0" and "0" is 0.5, etc.
Now I would like to output this like this:
    0       1
0   0.5     0.2

1   0.2     0

I thought it would be easy enough but I am totally stuck at this point.
Here is what I have done so far: I get my rows and columns.
t=overlap.items()
column_names=[i[0][0] for i in t]
rows=[[i[0][1], i[1]] for i in t]

I make a string template to fill those values in:
template="{}\t"*len(column_names)

Then I try to fill this by writing out the column names and iterating over the rows. And that's when I get stuck:
print template.format(??)
for row in rows:
    print template.format(??)

I don't know how to

*

*Get format to accept the items of a the lists (either column or rows) piece by piece? (especially as I don't have the same number of clusters every time!)

*Also, I would have to fill in duplicate values (1-2 vs 2-1) or replace them with white space?

*Is this even possible / advisable as a print output?
I looked at PrettyTable and tabulate that were recommended elsewhere but couldn't get those to work either. I guess I could use Pandas or some other stats module, but it seems a bit of an overkill as all I want to do is output these values.
Edit: Here is what I ended up doing, where "dict" is my input dictionary:
entries=dict.items()
column_names=list(set([i[0][0] for i in entries]))
row_names=list(set([i[0][1] for i in entries]))
coltemplate="\t{:<25}"*len(column_names)
print "{:25}".format(" "), coltemplate.format(*column_names)
for r in row_names:
    result=[]
        for c in column_names:
            if c == r:
                result.append("***")
            elif dict.get((c,r), None) == None:
                result.append(dict.get((r,c), "***"))
            else:
                result.append(dict.get((c,r), "SERIOUS ERROR"))
result=[str(i) for i in result]
rowtemplate="\t{:25}"*len(result)
print "{:>25}".format(r), rowtemplate.format(*result)

A: I am relativly new to computational field but I think I have a solution. if this doesnt help or is not conveniant please tell me why ( I have a lot to learn)
overlap={(0,0): 0.5, (1,0):0.2, (1,1):0.0, (2,1):0.3, (2,0):0.4}
t=overlap.items()

liste_columns = list(set([i[0][0] for i in t])) # get the columns name
liste_columns = [str(element) for element in liste_columns]

liste_rows =  list(set([i[0][0] for i in t])) # get the rows name
liste_rows = [str(element) for element in liste_rows]

header = '\t' + str('\t'.join(liste_columns)) # header column name
print(header)
for row in liste_rows:
    print( row, end='\t') # row name
    for columns in liste_columns:
        key = (int(columns),int(row)) # key for accessing valu in dict
        if key in overlap:
            value = overlap[key]
        else:
            value = overlap[key[::-1]] #reverse the tuple
        print(value, end= '\t')
    print('')

see for reversing tuple
How to reverse tuples in Python?
output
    0   1   2
0   0.5 0.2 0.4
1   0.2 0.0 0.3

Hope this help
ps: If you need further explanation feel free to ask.


text:
Q: How to keep the drop down list selection after web page refresh using Angularjs I am writing and application using AngularJs, HTML and PHP. In the application I have a dropdown list, which when an option is selected a table is populated with related data drawn from a database. I can add to or delete info from the table. That works perfectly. However, the challenge I have is that each time the table is edited, the web page refreshes/route is reloaded and the drop down list returns to its default value. The effect of this is the user having to manually reselect the dropdown list value to carryout each operation on the table.
How can I alter the code to keep/persist the last selected option value and have the said dropdown list option selected when the webpage/route reloads?
I have seen many help responses to setting initial default value for dropdown lists. However that is not what I am trying to achieve. I am trying  to set the post reload value or value after the webpage reloads.
Below is a part of what I have tried. I am at my whits end trying to figure it out. Any help is appreciated.
EDIT
Problem Solved
HTML before changes

<select id="b_year" ng-options="b.year for b in budgets track by b.year" ng-model="b.selectedBudget" ng-change="getBudgetItems(b.selectedBudget.year)" required><option value="">-- Choose budget year --</option></select>

HTML with solution changes

<select id="b_year" ng-options="b.year for b in budgets" ng-model="b.selectedBudget" ng-init="b.selectedBudget" ng-selected="getBudgetItems(b.selectedBudget.year)" required><option value="">-- Choose budget year --</option></select>

Controller snippet before changes

$scope.reloadRoute();
$scope.items.push({'line_item': li.line_item, 'weight': li.weight, 'allocated': li.allocated});

localStorage['b_year'] = year; //Store the selected year in local storage for later use
budget_size = server.getBudgetSize();

for(var i = 0; i < budget_size; i++){
  if($scope.budgets[i].year === localStorage['b_year']){
    $scope.b.selectedBudget[i] = localStorage['b_year'];
  }else{

  }
}

Controller with solution changes

app.controller(.... {
    ....
 (function(){
    $http.get( //Get info on budgets
        "http://localhost/TrGway/getbudgetinfo.php"
    )
    .success(function(data){
       $scope.budgets = data.budgets;
        for(var i = 0; i < data.budgets.length; i++){
            if($scope.budgets[i].year === selectedYear){

               $scope.b = {};

               $scope.b.selectedBudget = $scope.budgets[i];
            }
        }

    })
    .error(function(data){
       $scope.message = "Error!! Getting Budget Info Failed: " + data;
    });
})();
    ....
$scope.$watch("b.selectedBudget.year", function(item) {
       localStorage.setItem("selectedYear", item);
});

});

App.controller('budgetCtrl', ['$scope', '$http', '$location', '$window', '$route', 'BudgetService', function($scope, $http, $location, $window, $route, BudgetService){

    (function(){
        $http.get( //Get info on budgets
            "http://localhost/TrGway/getbudgetinfo.php"
        )
        .success(function(data){
           server.setBudgets(data.budgets);//Set the budget info in the BudgetService for
             //later usage anywhere in the program;
           $scope.budgets = data.budgets;
           budget_size = server.getBudgetSize();

           server.getBudgetInfo();
        })
        .error(function(data){
            $scope.message = "Error!! Getting Budget Info Failed: " + data;
        });
    })();

    (function(){ //Get Line Items Info to populate the table
        $http.get(
            "http://localhost/TrGway/lineItemInfo.php"
        )
        .success(function(data){
           server.setLineItems(data.items);
           $scope.items = data.items;
           server.getLineItemsInfo();
        })
        .error(function(data){
            $scope.message = "Error!! Getting Line Items Info Failed: "+data;
        });
    })();

    $scope.addBudget = function(budget){
       if( budget.year < new Date().getFullYear() ){
          alert("Budgets cannot be created retroactively.\n\
                 \nPlease enter a budget year greater than "+ new Date().getFullYear() );
          $scope.budget.year = "";
       }else{
         server.addBudget(budget);
         server.getBudgetInfo();
         $scope.budgets = server.getBudgets();
         $scope.budget = {};//Clear the add budget form
      }
    };

    $scope.getBudgetItems = function(year){
 /*This is where info on the budget for the selected year is retrieved and passed to the table
   This works great every time*/
       if( year === undefined ){ //If no year is selected do nothing
         $scope.budget_amount = 0;
         $scope.budget_amount_used = 0;
         $scope.budget_amount_remaining = 0;
       }else{
         Budgets = server.getBudgets();
         budget_size = server.getBudgetSize();
         for(var i = 0; i < budget_size; i++){
             if(Budgets[i].year === year){
                $scope.budget_amount = Budgets[i].starting_amount;
                $scope.budget_amount_used = Budgets[i].amount_used;
                $scope.budget_amount_remaining = Budgets[i].running_balance;
                amount_remaining = Budgets[i].starting_amount - Budgets[i].amount_used;
                percent_used += (Budgets[i].amount_used / Budgets[i].starting_amount * 100);
                server.setSelectedBudget(Budgets[i]);
             }else{
                //$scope.budget_amount = 0;
             }
         }
         server.setPercentUsed(percent_used);
         server.setPercentRemaining( 100 - percent_used);
         server.setAmountRemaining(amount_remaining);
       }
    };
    /*======================= THIS IS WHERE THE CHALLENGE IS ====================*/
    $scope.addLineItem = function(li, b){
 /*This is where the List items are added to the table before page reload*/
        if(($scope.budget_amount_used-0 + li.allocated-0) > $scope.budget_amount){
            alert("Budgeted amount exceeded!!!\nPlease consider revising");
            $location.path('editbudget');
            $scope.li.weight = 0;
            $scope.li.allocation = 0;
        }else{
   server.setSelectedBudgetYear(b.selectedBudget.year); //Save selected year to a variable
   server.addLineItem(li, b); //Add the new Line items row to database

   $scope.reloadRoute();
   $scope.items.push({'line_item': li.line_item, 'weight': li.weight, 'allocated': li.allocated});

   $scope.b = {};
   //$scope.b.selectedBudget = localStorage.getItem("selected");
   $scope.$watch("b.selectedBudget.year", function(item) {
    localStorage.setItem("selected", item);
   });

          //$scope.b.selectedBudget.year = server.getSelectedBudgetYear();   //I tried this also
        }
        $scope.li.line_item = "";
        $scope.li.weight = 0;
        $scope.li.allocation = 0;

  $scope.b.selectedBudget = localStorage.getItem("selected");

        /* LEAVING THIS SO YOU CAN SEE WHAT ELSE I HAVE TRIED
    $scope.b = {};
          $scope.b.selectedBudget = localStorage.getItem("selectedBudget");
          $scope.watch("b.selected", function(item) {
             localStorage.setItem("selected", item);
          });
    $scope.b.selectedBudget = localStorage['b_year'];
        */

       /* LEAVING THIS SO YOU CAN SEE WHAT ELSE I HAVE TRIED
  budget_size = server.getBudgetSize();
         for(var i = 0; i < budget_size; i++){
    if($scope.budgets[i].year === server.getSelectedBudgetYear()){
    $scope.b.selectedBudget.year = server.getSelectedBudgetYear();
    }else{

    }
        }*/

    };

 $scope.deleteLineItem = function(row, b){
        $http({
           method: "post",
           url: "http://localhost/TrGway/deleteLineItem.php",
           crossDomain: true,
           data:{
               'seq': row.seq,
               'year': row.year,
               'allocated':row.allocated,
               'starting_amount': b.selectedBudget.starting_amount,
               'amount_used': b.selectedBudget.amount_used,
               'running_balance': b.selectedBudget.running_balance
           },
           headers: {
               'Content-Type': 'application/x-www-form-urlencoded'
           }
        })
        .success(function(response){
            if(response.toString() === "success"){
              var index = -1;
              var itemsArr = eval( $scope.items );
              for( var i = 0; i < itemsArr.length; i++ ) {
                if( itemsArr[i].seq === row.seq ) {
                  index = i;
                  break;
                }
              }
              if( index === -1 ) {
                alert( "Something has gone wrong!!\nLine item was not deleted.\nPlease try again" );
              }
                server.reset();
                server.reload();
                $scope.budget_percent_used = server.getPercentUsed()-0;
                $scope.budget_percent_remaining = server.getPercentRemaining()-0;
                $scope.budget_amount_used = server.getAmountUsed()-0;
                $scope.budget_amount_remaining = server.getAmountRemaining()-0;

                server.setTotalWeighting($scope.totalweighting + row.weight)-0;
                server.setPercentUsed(server.getTotalWeighting())-0;
                server.setPercentRemaining(100 - server.getPercentUsed())-0;
                $scope.items.splice( index, 1 ); //Remove the row with matching index/seq value
                $scope.totalweighting = server.getTotalWeighting();
                $scope.budget_percent_used = server.getPercentUsed()-0;
                $scope.budget_percent_remaining = server.getPercentRemaining()-0;*/
                $scope.reloadRoute();
            }else{ //If deleting the line item failed
                $location.path('editbudget');
                $scope.budgetmessage = "Line Item Update Failed: "+response;
            }
        })
        .error(function(response){ //If there was an error connecting to the server
            $scope.budgetmessage = "Error!! Updating Line Item Failed: "+response;
        });
       row.isEditing = false;
    };

    $scope.updateLineItem = function(row){
        $http({
           method: "post",
           url: "http://localhost/TrGway/updateLineItem.php",
           crossDomain: true,
           data:{
               'seq': row.seq,
               'line_item': row.line_item,
               'weight': row.weight,
               'allocated': row.allocated
           },
           headers: {
               'Content-Type': 'application/x-www-form-urlencoded'
           }
        })
        .success(function(response){
            if(response.toString() === "success"){
                $location.path('editbudget');
            }else{
                $location.path('editbudget');
                $scope.budgetmessage = "Line Item Update Failed: "+response;
            }
        })
        .error(function(response){
            $scope.budgetmessage = "Error!! Updating Line Item Failed: "+response;
        });
       row.isEditing = false;
    };

    $scope.cancelLineItemEditing = function(row){
        row.isEditing = false;
    };

    $scope.updateBudget = function(b){
        $http({
           method: "post",
           url: "http://localhost/TrGway/updatebudget.php",
           crossDomain: true,
           data:{
               'year': b.selectedBudget.year,
               'starting_amount': b.edit_starting_amount
           },
           headers: {
               'Content-Type': 'application/x-www-form-urlencoded'
           }
        })
        .success(function(response){
            if(response.toString() === "success"){
                server.setStartingAmount(b.edit_starting_amount);
                var line_items = server.getLineItems();
                var start_amount = server.getStartingAmount();
                var total_weight = 0;
                var amount_used = 0;
                var amount_remaining = 0;
                var percent_used = 0;
                var percent_remaining = 0;
                for(var i = 0; i < line_items.length; i++){
                    //Update the line items on the page immediately
                    line_items[i].weight = ( line_items[i].allocated / start_amount) * 100;
                    total_weight += line_items[i].weight;
                    amount_used += line_items[i].allocated-0;
                    //Update the line items in the database immediately
                    $scope.updateLineItem(line_items[i]);
                }

                server.load();

                percent_used = ( amount_used / start_amount) * 100;
                amount_remaining = start_amount - amount_used;
                percent_remaining = 100 - percent_used;

                server.setLineItems(line_items);
                server.setTotalWeighting(total_weight);
                server.setAmountUsed(amount_used);
                server.setPercentUsed(percent_used);
                server.setAmountRemaining(amount_remaining);
                server.setPercentRemaining(percent_remaining);

                $scope.items = server.getLineItems();
                $scope.total = 0;
                $scope.total = server.getStartingAmount();
                $scope.totalweighting = server.getTotalWeighting()-0;
                $scope.budget_amount_used = server.getAmountUsed()-0;
                $scope.budget_percent_used = server.getPercentUsed()-0;
                $scope.budget_percent_remaining = server.getPercentRemaining()-0;
                $scope.budget_amount_remaining = server.getAmountRemaining()-0;

                $location.path('editbudget');
            }else{
                $location.path('editbudget');
                $scope.budgetmessage = "Budget Update Failed: "+response;
            }
        })
        .error(function(response){
            $scope.budgetmessage = "Error!! Updating Budget Failed: "+response;
        });

        $scope.b = {};
    };

    $scope.reloadRoute = function(){
       $route.reload();
       server.reload();
    //alert('Loaded!!');
    };
}]);

Home

Add/Edit line Items

Logout

Back

        <form name="LineItemForm" class="form-horizontal" role="form">
          <fieldset>

                  Select Budget Year To Edit Line Items

                      <select id="b_year" ng-options="b.year for b in budgets track by b.year" ng-model="b.selectedBudget" ng-change="getBudgetItems(b.selectedBudget.year);" ng-selected="" required>
                        <option value="">-- Choose budget year --</option>
                      </select>

                  {{b.budgetmessage}}

Add Line Item Here

                          Line Item

                             <input type="text" class="form-control" name="line_item" id="line_item" ng-model="li.line_item" ng-disabled="!b.selectedBudget" required/>

                          weighting %

                            <input type="number:2" class="form-control" name="weight" id="weight" ng-init="li.weight = 0" ng-model="li.weight" ng-disabled="!b.selectedBudget || !li.line_item || li.line_item.length<5" required/>

                          Allocated $

                            <input type="number:2" class="form-control" name="allocated" id="allocated" placeholder="{{li.allocated = (budget_amount * li.weight) / 100 | currency}}" ng-init="li.allocated=0"  ng-model="li.allocated" ng-disabled="!b.selectedBudget || !li.weight" required />

                            {{message}}

                            <button type="submit" class="width-35 pull-right btn btn-sm btn-primary" ng-click="addLineItem(li, b)" data-ng-disabled="LineItemForm.$invalid || li.weight===0 || li.line_item.length < 5">
                                Add Line Item
                            </button>

          </fieldset>
        </form>

            <form>
                <fieldset>

                           Line Items	% Weighting	Allocation $	Tasks

                          {{row.line_item}}

                            <input type="text" name="line_item" ng-model="row.line_item" class="editable-input form-control input-sm" required />

                         {{ row.weight = row.allocated / budget_amount * 100 | number: 2 }}

                          {{ row.allocated | currency }}

                            <input type="text" name="allocated" ng-model="row.allocated" class="editable-input form-control input-sm" required/>

                           <button class="btn btn-primary btn-sm" ng-click="updateLineItem(row)" ng-if="row.isEditing" ng-disabled="rowForm.$pristine || rowForm.$invalid"></button>
                           <button class="btn btn-default btn-sm" ng-click="cancelLineItemEditing(row)" ng-if="row.isEditing"></button>
                           <button class="btn btn-default btn-sm" ng-click="row.isEditing = true" ng-if="!row.isEditing"></button>
                           <button class="btn btn-danger btn-sm" ng-click="deleteLineItem(row, b)" ng-if="!row.isEditing"></button>

                               TOTAL (Budget Estimate)

                               {{ totalweighting =  budget_amount > 0 ? 100 : 0 | number:2 }}%

                               {{ budget_amount | currency }}

                               BUDGET AMOUNT USED

                               {{ budget_percent_used = budget_amount_used > 0 ? budget_amount_used * 100/budget_amount : 0 | number:2 }}%

                                {{ budget_amount_used | currency }}

                               BUDGETED AMOUNT REMAINING

                               {{ budget_percent_remaining = 100 - budget_percent_used | number:2 }}%

                                {{ budget_amount_remaining | currency }}

                </fieldset>
              </form>

A: I'd do something like this:
app.controller(.... {
    ....
    $scope.b = {};
    $scope.b.selected = localStorage.getItem("selected");
    $scope.watch("b.selected", function(item) {
        localStorage.setItem("selected", item);
    });
    ....
});

EDIT
So we suspect that the initial value gets overwritten somewhere. Here is some help how to debug it: You can define a property setter on $scope.b, that could alert or break to debugger. Use something like this:
$scope.b = {
    set selectedBudget(v) {
        debugger;
        // or alert(1);
    }
};

A: Solution
This is the solution I came up with to keep the drop down list selection after webpage refresh. I hope this will help someone. I have added comments to help explain what I did. I hope they are clear. However, I welcome any correction or clarification. I was able to come up with this solution , thanks to help from @Tamas Hegedus, who pointed me in the right direction.

app.controller(.... {
    ....
 (function(){
    $http.get( //Get info on budgets
        "http://localhost/TrGway/getbudgetinfo.php"
    )
    .success(function(data){
       $scope.budgets = data.budgets; //assign array of elements to the scope variable
        for(var i = 0; i < data.budgets.length; i++){ //Loop through each array element
            if($scope.budgets[i].year === selectedYear){ //Check if any of the 'year' value in the array match the value stored in localStorage

               $scope.b = {}; //reset the selected scope variable

               $scope.b.selectedBudget = $scope.budgets[i]; //Assign the array element with the matching year, as the selected scope element
            }
        }

    })
    .error(function(data){
       $scope.message = "Error!! Getting Budget Info Failed: " + data;
    });
})();
    ....
$scope.$watch("b.selectedBudget.year", function(item) { //Set watch on array element 'year' for changes/selection
       localStorage.setItem("selectedYear", item);      //When an element is selected from the drop down list, its value is stored in localStorage
});

});
<select id="b_year" ng-options="b.year for b in budgets" ng-model="b.selectedBudget" ng-selected="getBudgetItems(b.selectedBudget.year)" required><option value="">-- Choose budget year --</option></select>


text:
Q: Fill info from another sheet if cell info matched from another sheet If info in G column of Intermediate, Beg Flutes, or Beg Clarinet matches info in the Inventory sheet column C.  I want to fill in Inventory sheet cell H2 with info from the other sheets first name column.
End product with Inventory sheet
enter image description here
Intermediate Band Sheet
enter image description here
Beg Flute Sheet
enter image description here
Beg Clarinet Sheet
enter image description here

A: Try this formula:
=INDEX('Intermediate 22-23'!A:A,MATCH(Inventory!C2,'Intermediate 22-23'!G:G,0))


text:
Q: How to pass parameters to a controllers in ROR I want to pass year and month to a controller. When the submit button is pressed, the year and month info should be passed to the action show of the controller foo.
I have edited my form as
<%= form_tag "/test" do %>
<%= month_field_tag :yearMonth %>
<%= submit_tag %>
<% end %>

How should I do to archive this in a view and how to get the passed parameter in foo controller?

A: Rails 4+ You must have a params.require private def in your controller to permit the variables you define as "okay" to be parsed. Your controller will filter out anything not specifically allowed via the .require.
private
def name_of_controller_params
  params.require(:name_of_controller).permit(:yearMonth, :anothervar, :etc)
end

To see the params hash in your controller at the action point, you can insert this debug code into your relevant action. You can use this to see if your param is making it from the form into your controller's action.
    def show
      flash[:info] = "Params hash #{params}."
      other actions...
    end

A: Something like this will work:
<%= form_tag '/test' do %>
  <%= month_field_tag 'month_value', '' %>
  <%= submit_tag %>
<% end %>

Then inspect params from show action to see if month_value is there.


text:
Q: Pandas/Python Combine two data frames with duplicate rows Ok this seems like it should be easy to do with merge or concatenate operations but I can't crack it. I'm working in pandas.
I have two dataframes with duplicate rows in between them and I want to combine them in a manner where no rows or columns are duplicated. It would work like this
df1:

A B
a 1
b 2
c 3

df2:

A B
b 2
c 3
d 4

df3 = df1 combined with df2

A B
a 1
b 2
c 3
d 4

Some methods I've tried are to select the rows that are in one but not the other (an XOR) and then append them, but I can't figure out how to do the selection. The other idea I have is to append them and them delete duplicate rows, but I don't know how to do the latter.

A: You want an outer merge:
In [103]:
df1.merge(df2, how='outer')

Out[103]:
   A  B
0  a  1
1  b  2
2  c  3
3  d  4

The above works as it naturally finds common columns between both dfs and specifying the merge type results in a df with a union of the combined columns as desired.

A: You can use the following to drop the duplicates:
pd.concat([df1, df2]).drop_duplicates()


text:
Q: Opening a port to a VM on Azure Firstly, apologies if similar questions have been answered before, but the Azure configuration seems to have changes since most of the posts I have seen so far.
I have an application which I have installed on an Azure VM [Windows server 2012].
It's actually wso2 API manager, if anybody has experience of that.
The application fires up Tomcat and listens for SSL traffic on port 9443. Why it's not 443 I'm not sure.
I've set up an Inbound Security rule on my Network Security Group, as follows:
Priority : 1010
Source: Any
Service: Custom
Protocol: Any
Port Range: 9443
Action : Allow
I still have no joy accessing this from a browser though, I get the slightly confusing "This site can't be reached / the connection was reset" error.
I'd welcome any pointers to get this working or to debug!

A: I recently experienced nearly the same issue that you did.  What worked for me:
1) I added my inbound rule prior to any other inbound rule.  I noticed your rule is 1010 which means it's being applied after the default RDP rule is.  No, this shouldn't make a difference, but it may.
2) When you create your inbound rule, hit the "advanced" button, choose the CIDR option and route the traffic to the internal IP address of the VM.
3) For the destination port range I chose only the port I needed.  In your case 9443.
The issue for me was the internal IP address.  Once I set that everything started working for me.