What are some interesting calculus facts your calculus teachers didn't teach you?

Question: I recently learned an interesting fact about what the value of a Lagrange multiplier represents: suppose the maximum of some real-valued function $f(\vec{x})$ subject to a constraint $g(\vec{x})=c$ is $M$ (of course, $M$ depends on $c$), which you obtained via Lagrange multipliers (solving $\nabla f = \lambda \nabla g$).  Then, it's easy to show (using the chain rule) that the multiplier $\lambda$ can be interpreted as the change of the maximum with respect to perturbations of the level set $g=c$. That is,
$$
\lambda = \frac{d M}{dc}
$$
I think this is a pretty cool result and I never it heard about during my time as an undergraduate.
What are some interesting calculus (or undergraduate mathematics) results nobody told you about during your calculus (or undergraduate) education?
Comment: "that's a good one, but I'm surprised nobody told you about it! " shows exactly what's wrong with this question. Voted to close.
Comment: Darboux's Theorem.
Comment: @DavidMitra - that's a good one, but I'm surprised nobody told you about it!
Comment: @DavidMitra: Even if it's a corollary, that's curious!
Answer: When I first learned Taylor's theorem it didn't really click with me; I thought it clunky and difficult. Then I saw the simplest, most intuitive proof of Taylor's theorem there's got to be. If $f \in C^n$ then
$$f(x) = f(x_0) + \int_{x_0}^x f'(t)$$
Iterate this relation and we get
$$f(x) = f(x_0) + \int_{x_0}^x (f'(x_0) + \int_{x_0}^x f''(t))$$
$$f(x) = f(x_0) + \int_{x_0}^x f'(x_0)\,dt + \int_{x_0}^x\int_{x_0}^u f''(t)\,dtdu$$
and then
$$f(x) = f(x_0) + \int_{x_0}^x (f'(x_0) + \int_{x_0}^x (f''(x_0) + \int_{x_0}^x f'''(t)))$$
$$ f(x)= f(x_0) + \int_{x_0}^x f'(x_0)\,dt + \int_{x_0}^x\int_{x_0}^u f''(x_0)\,dtdu + \int_{x_0}^x\int_{x_0}^u\int_{x_0}^wf'''(t)\,dtdwdu$$
so on and so forth, which reduces to
$$f(x) = f(x_0) + f'(x_0)(x-x_0) + f''(x_0)\frac{(x-x_0)^2}{2} + ... + R_n(x)$$
where
$$R_n(x) = \int_{x_0}^x\int_{x_0}^x...\int_{x_0}^x f^{(n)}(x) = \frac{1}{n-1!}\int_{x_0}^x f^{(n)}(t)(x-t)^{n-1}\,dt$$
So that Taylor's theorem is really just iterated integration and derivation all derived from the seemingly obvious formula
$$f(x) = f(x_0) + \int_{x_0}^x f'(t)$$
Comment: It's not just abusing notation: if you claim $f'(t) = f'(x_0) + \int_{x_0}^x f''(t)\,dt$ then $f'(t) - f'(x_0) = \int_{x_0}^x f''(t)\,dt$, and that makes no sense since the right side depends on $x$ and the left side does not.  Can you make the derivation accurate by writing $f'(t) = f'(x_0) = \int_{x_0}^t f''(t)\,dt$ (to abuse notation) or $f'(t) = f'(x_0) + \int_{x_0}^t f'(u)\,du$ (not to abuse notation)?
Comment: @KCd My prof proved the integral form of the remainder using something like the mean value theorem. I had never seen this proof in a book or a class, only on the internet. It's nice to hear that it's more common than I thought; a great proof.
Comment: I agree with @KCd that this is beyond merely abusing notation; I think it should be fixed because this answer is getting some popularity. It's easy to fix. See the link I gave above for a correct version.
Comment: Very neat. I'm used to think of Taylor as a generalized version of the Mean Value Theorem, but this is definitely clearer.
Comment: I love this derivation and it deserves to be more well known.  In your final expression for $R_n(x)$, how did you get the upper limits to all be $x$ rather than $u,w,...$?
Comment: @littleO that was just abuse of notation, it should be $u$'s and $w$'s; the equality follows from Cauchy's iterated integral formula https://en.wikipedia.org/wiki/Cauchy_formula_for_repeated_integration.
Comment: @littleO you say this derivation deserves to be more well known, but it is already one of the standard proofs of the integral form of the remainder. Find a book that proves the integral form of the remainder and I bet the argument will be this one. In fact it is even in Stewart's widely used calculus book.
Comment: @KCd Hmm, you might be right, maybe it just wasn't emphasized in my math classes for some reason.  There is a different approach based on integration by parts that is presented a lot.
Comment: By the way, here is a math.stackexchange post that gives more details about the final form of the remainder: http://math.stackexchange.com/a/492165/40119
Comment: @littleO  whoops, I see I did not really follow what was going on.  The standard proof is by repeated integration by parts, not this iterated integration. I think it would be better if the integrals did not have the $dt$'s ignored everywhere, and make the bounds right: in the iterated relation, it's not true that $f'(t) = f'(x_0) + \int_{x_0}^x f''(t)\,dt$; the letter $t$ is being used to mean two different things there.
Comment: @kcd yeah abusing notation; I do that often. It still sparks the same semantic network though :) I didnt have the patience to add all those $dt$'s and dummy variables.
Comment: This is a standard proof available on Wikipedia. Integral form of remainder is quite well known, for example, Apostol and G H Hardy both discuss it in their books. However I agree that proof via repeated integration is the easiest route to Taylor's theorem.
Comment: @ParamanandSingh The proof on wikipedia uses integration by parts; it's different than the derivation given here.
Comment: @littleO: the formula for the remainder at the end comes from integration by parts and that is the key for obtaining remainder in a useful form (like for obtaining error estimates).
Answer: Every basic fact about computing derivatives is easiest to understand if you allow yourself to use infinitesimals, the use of infinitesimals can be rigorously justified, and it doesn't require using nonstandard analysis. Moreover, in practice the fastest way to compute derivatives of complicated functions by hand is to use infinitesimals.
Here's a random example. Suppose I wanted to compute the derivative of $\frac{e^t \cos t}{1 - \tan \log (1 + t)}$ at $t = 0$. You might think I would have to use the quotient rule, then the product rule in the numerator, then the chain rule twice in the denominator. But actually I can do something much faster, which is to pretend that $t^2 = 0$, or in other words to repeatedly take Taylor series and cut them off after the linear term, and then just use ordinary algebra. This produces
$$\frac{(1 + t)(1)}{1 - \tan t} = \frac{1 + t}{1 - t} = 1 + 2t$$
(because $(1 + t)(1 - t) = 1$, so $\frac{1}{1 - t} = 1 + t$). So the derivative at $t = 0$ is $2$. A similar trick where you pretend that $t^3 = 0$ can be used to compute second derivatives, which I'll demonstrate on the above example because maybe only getting the first derivative looked too easy: this produces
$$\frac{\left( 1 + t + \frac{t^2}{2} \right) \left( 1 - \frac{t^2}{2} \right)}{1 - \tan \left( t - \frac{t^2}{2} \right)} = \frac{1 + t}{1 - t + \frac{t^2}{2}} = (1 + t) \left( 1 + t + \frac{t^2}{2} \right) = 1 + 2t + \frac{3t^2}{2}.$$
So the second derivative is $3$.
Here's a harder and less elementary example. Consider the function $X \mapsto \det X$ where $X$ is a square matrix. What is its derivative at the identity $X = I$? Well, a standard fact about determinants tells you that
$$\det (1 + t X) = 1 + \text{tr}(X) t + O(t^2)$$
(where $O(t^2)$ - Big O notation - is one way of justifying more rigorously what I'm doing when I ignore second-order and higher terms in the Taylor series). The coefficient of the linear term is $\text{tr}(X)$, so that's the derivative. It is really annoyingly difficult to try to do this computation by writing out the formula for the determinant in full and then differentiating it; I've never tried and I don't plan to.
This method of computing derivatives is so easy you can teach a computer how to do it.
Comment: +1. You probably know this, but Knuth has actually suggested teaching calculus via O-notation. (It's there in a few places on the internet e.g. [I've posted it here](https://shreevatsa.wordpress.com/2014/03/13/big-o-notation-a-couple-of-sources/).) Infinitesimals have a bad reputation, but this isn't even infinitesimals _per se_, just formal manipulation of "there exists" expressions, with good notation. It's a nice letter and demonstrates that this way of thinking can be successful.
Comment: Isn't this basically computing first couple of terms of Taylor series? If so, it is completely rigorous in standard analysis. What I'm wondering is if there is easy to see justification that you can calculate Taylor polynomial of order $n$ by calculating in $\Bbb R[t]/(t^{n+1})$?
Comment: @Ennar: there are a couple of ways to say it. One is that in the ring of functions which are $(n+1)$ times continuously differentiable at $0$, the subset of functions which are $O(t^{n+1})$ (as $t \to 0$) is an ideal, and you can quotient by it. This takes care of products and quotients when they make sense but not necessarily compositions; for compositions maybe a conceptually cleaner way to go forward is to embed $C^{\infty}$ functions into formal power series.
Answer: Nonelementary antiderivatives. While you may have heard that the antiderivative $$f(x)=\int_{0}^{x} e^{-\frac{t^2}{2}}dt$$
is not expressible as an elementary function you definitely haven't seen the proof.
Answer: During the 1st semester of calculus I teach my students about differentials. When I was a student nobody told me what is its geometric interpretation.
Comment: I was taught about the secant line and how you can take a limit to turn it into the tangent line, but they didn't actually do anything with differentials or infinitesimals.  I fear this may have been lost in the rush to stamp out the latter from (standard) analysis.
Comment: I too always teach the geometric interpretation of differentials. I find it alarming that someone would teach differentials without it.
Comment: @eeeeeeeeee I must admit I hate thinking of differentials geometrically without first justifying this with techniques far past basic Calculus courses.
Comment: @BrevanEllefsen I completely understand and appreciate the desire for rigor but I feel like motivating the topic with basic geometry first can only help.
Answer:
Misconception about L'Hospital's Rule

I learned about L'Hospital's Rule (LHR) in my first calculus course as a high school student.  For one of the indeterminate forms, the teacher presented the conditions as

Suppose $f$ and $g$ are differentiable in a deleted neighborhood of $x_0$, and $\lim_{x\to x_0}f(x)=\infty$, $\lim_{x\to x_0}g(x)=\infty$, and $g'(x) \ne 0$ in a deleted neighborhood of $x_0$.  If $\lim_{x\to x_0}\frac{f'(x)}{g'(x)}$ exists, then $\lim_{x\to x_0}\frac{f(x)}{g(x)}$ also exists and
$$\lim_{x\to x_0}\frac{f(x)}{g(x)}=\lim_{x\to x_0}\frac{f'(x)}{g'x)}$$

The misconception is that the limit of $f$ is required to be $\infty$.  This is not the case.  In fact, the limit $\displaystyle \lim_{x\to x_0}f(x)$ need not even exist for LHR to be valid provided that $\displaystyle g\to \infty$

EXAMPLE:

There are many applicable examples that might be considered trivial. Here is one that might be less obvious.
Let $f(x)=\log(1/x)+\int_0^1\frac{1-t^x}{1-t}\,dt$ and $g(x)=x$.
Now, without even knowing whether the limit, $\lim_{x\to \infty}f(x)$ exists or not (it is actually equal to $\gamma$, the Euler-Mascheroni constant), we know that $f$ is differentiable for $x>0$ with $f'(x)=-\frac1x-\int_0^1\frac{\log(t)t^x}{1-t}\,dt$.
Inasmuch as $g$ is differentiable with $\lim_{x\to \infty}g(x)=\infty$, L'Hospital's Rule asserts that
$$\begin{align}
\lim_{x\to \infty}\frac{f(x)}{g(x)}&=\lim_{x\to \infty}\frac{\log(1/x)+\int_0^1\frac{1-t^x}{1-t}\,dt}{x}\\\\
&=\lim_{x\to \infty}\frac{-\frac1x-\int_0^1\frac{\log(t)t^x}{1-t}\,dt}{1}\\\\
&=0
\end{align}$$
Answer: Integration by parts - visualization
Not that shocking, but my teacher never showed me this. For many people this will be familiar, but for those who never saw it: it can be an eye opener.

Image source: Wikipedia

The area of the blue / red region is:
$$A_1=\int_{y_1}^{y_2}x(y)dy$$
$$A_2=\int_{x_1}^{x_2}y(x)dx$$
So we have:
$$\overbrace{\int_{y_1}^{y_2}x(y)dy}^{A_1}+\overbrace{\int_{x_1}^{x_2}y(x)dx}^{A_2}=\biggl.x
> . y(x)\biggl|_{x1}^{x2} = \biggl.y . x(y)\biggl|_{y1}^{y2}$$
Assuming the curve is smooth within a neighborhood, this generalizes
  to indefinite integrals:
$$\int xdy + \int y dx = xy$$
Rearranging yields the well-known formula:
$\int xdy = xy - \int y dx$


Como impedir que as paginas sejam carregadas pelo navegador apos encerrar a sessão

Question: Estou tentando fazer um site acadêmico onde os usuários precisam se logar (pagina de login :pagina.php) ai será direcionado a pagina(nome.php) onde faz a conexão com o banco e se tiver o cadastro vai para a pagina site.php, e depois onde fará o logout(logoutt.php), mas quando faço o logout e aperto o botão de voltar do navegador (em vez de me direcionar para de login onde deveria logar novamente), esta indo para a pagina (site.php). Se puderem me ajudar Agradeço.
Obs: Ainda estou aprendendo, este site é mais para aprender na pratica`

Pagina de login:

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

    <form method="POST" action= 'nome.php'>
Login: <input type="text" name="login" id="login">

Senha: <input type="password" name="senha" id="senha">

<input type="submit" value="login" id="login" name="login">
</form>

pagina enquanto estar logado:

<!DOCTYPE html>

 <?php
session_start();
if((!isset ($_SESSION['login'])) and (!isset ($_SESSION['senha'])))
{
    unset($_SESSION['login']);
    unset($_SESSION['senha']);
    header('location:index.php');
    }
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SISTEMA WEB</title>

    SISTEM WEB TESTE

 Olá <?$_SESSION['login']?>! Logout!

    MENU AQUI
    CONTEUDO E ICONES AQUI

Pagina de logout:

<?php
session_start();
session_unset();
unset($_SESSION["login"]);
unset($_SESSION["senha"]);
session_destroy();
?>
Answer: É só colocar uma função de proteção em cada pagina que deve ser protegida. exemplo
<?php
  if(!isset($_SESSION['id'])){
    header('Location: /pagina.php');
    exit();
  }
?>

Se não existir $_SESSION['id']; ele manda o cara para /pagina.php
assim que o cara digitar o login e senha corretos, ponha o ID do banco da linha do banco de dados, no $_SESSION['id']
e quando o cara acessar o logou.php basta destruir a sessão usando session_detroy(); e em seguida por um header('Location: /pagina.php');


Confusion with the eccentricity of ellipse

Question: Confusion with the eccentricity of ellipse. On wikipedia I got the following in the directrix section of ellipse.

Each focus F of the ellipse is associated with a line parallel to the minor axis called a directrix. Refer to the illustration on the right, in which the ellipse is centered at the origin. The distance from any point P on the ellipse to the focus F is a constant fraction of that point's perpendicular distance to the directrix, resulting in the equality e = PF/PD. The ratio of these two distances is the eccentricity of the ellipse. This property (which can be proved using the Dandelin spheres) can be taken as another definition of the ellipse.
  Besides the well-known ratio e = f/a, where f is the distance from the center to the focus and a is the distance from the center to the farthest vertices (most sharply curved points of the ellipse), it is also true that e = a/d, where d is the distance from the center to the directrix.

It is given that $e=\frac fa=\frac ad$

In my book it was only given that $e=f/a$ (in my book there is nothing given about directrix of an ellipse).
My question
Knowing that $e=f/a$ how can I get $e=a/d$ and $e=PF/PD$?
Comment: You can get these facts "using the Dandelin spheres", as the quoted passage says. An actual proof of that kind is here: https://math.stackexchange.com/a/137462
Answer: If I understood your question correctly, you're essentially asking how one can find the equation for the directrix if one only has the equation for an ellipse with a given eccentricity.
You start with the equation below
$$
\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1
\qquad(1)
$$
where $a$ and $b$ are positive real-valued constants.
If you then define two points on the $x$ axis, $F$ and $F'$, by their coordinates,
$$
F \equiv (\epsilon a, 0)
\qquad(2)
$$
$$
F' \equiv (-\epsilon a, 0)
\qquad(3)
$$
for some as-yet undetermined real value $\epsilon \ge 0$, and then require that the sum of the distances from $F$ to $P$ and from $P$ to $F'$ be equal to $2a$ - for any arbitrary point $P$ on the ellipse - you'll find out that that is only possible if you choose $\epsilon$ to satisfy
$$
\epsilon = \sqrt{1 - \frac{b^2}{a^2}}
\qquad(4)
$$
So far, the above has nothing to do with the directrix. It's just a way to construct the foci and find the eccentricity, starting from some equation and then requiring that the curve described by that equation must have the fundamental property of an ellipse (namely, that the sum of the distances from any point on the ellipse to the two foci is a constant).
Now, let's see how we can prove the directrix property. Imagine that there is a vertical line at $x=d$ for some as-yet-undetermined real value $d \ge 0$ and let's see if we can find a value of $d$ such that the directrix property is satisfied. The focus for positive $x$ is $F$ (see its coordinates above), and an arbitrary point $D$ in the would-be directrix has coordinates $D = (d, y)$. The directrix property mandates that
$$
\epsilon = \frac{\overline{PF}}{\overline{PD}}
\qquad(5)
$$
Now, let's look at the square of the distances involved, since that gets rid of the square roots:
$$
\overline{PF}^{\,2} = (x - \epsilon a)^2 + (y - 0)^2 = (x - \epsilon a)^2 + y^2
$$
But $P$ lies on the ellipse so $(x,y)$ satisfies $(1)$. Therefore, eliminating $x^2$ in favour of $y^2$, but leaving the $x$ term alone, we have
$$
\overline{PF}^{\,2} =
a^2\,(1 + \epsilon^2) + y^2\,(1 - \frac{a^2}{b^2}) - 2\epsilon ax
$$
How about $\overline{PD}^{\,2}$? Note that $D$ and $P$ have the same $y$ coordinate so
$$
\overline{PD}^{\,2} = (x - d)^2 + (0)^2 = (x - d\,)^2
$$
Here's the crux now. Can we find a value of $d$ such that $(5)$ is true?
Imposing
$$
\frac{\overline{PF}^{\,2}}{\overline{PD}^{\,2}} =
\frac{a^2\,(1 + \epsilon^2) + y^2\,(1 - \frac{a^2}{b^2}) - 2\epsilon ax}{(x - d\,)^2} = \epsilon^2
$$
we get
$$
a^2\,(1 + \epsilon^2) + y^2\,(1 - \frac{a^2}{b^2}) - 2\epsilon ax = \epsilon^2\,(x - d\,)^2
$$
Note that the complicated expression above is something like this:
$$
(\mbox{terms independent of $x$ and $y$}) + (\mbox{terms involving $y^2$}) - 2\epsilon ax + 2\epsilon^2 xd = 0
$$
because the $x^2$ terms can be removed using $(1)$. Since the above has to be true for all $x$, the only hope for $(5)$ to be possible is if we choose $d$ such that
$$
2\epsilon ax - 2\epsilon^2 xd = 0
\qquad\Rightarrow\qquad
d = \frac{a}{\epsilon}
$$
With this choice, it's then not hard to show that the terms not written above also vanish so, indeed,
$$
\epsilon = \frac{\overline{PF}}{\overline{PD}}
$$
is true, provided we make that choice for $d$.

So, what's the conclusion? The conclusion is that an ellipse has two equivalent properties, namely, (A) the sum of the distances from the foci to any arbitrary point on the ellipse is a constant, and (B) the ratio of (the distance from an arbitrary point on the ellipse to one of the foci) to (the distance from that point to a fixed vertical line parallel to the semi-minor axis) is equal to the eccentricity of the ellipse.
And we also proved that $\epsilon = a/d$.
(Technically, I only proved that (A) above implies (B). We'd also have to prove that (B) implies (A) for the equivalence I referred to be proven. That's an exercise I leave for the reader...)
Answer: The ellipse can also be defined as the locus of points whose distance from the focus is proportional to the horizontal distance from a vertical line known as the conic section directrix, where the ratio is $<1$. Letting $e$ be the ratio and $d$ the distance from the center at which the directrix lies, then in order for this to be true, it must hold at the extremes of the major and minor axes, so

$r=\frac{a-c}{d-a}=\frac{\sqrt{b^2+c^2}}{d}$
With a bit of solving, you get
$d= \frac{a^2}{\sqrt{a^2-b^2}} = \frac{a^2}{c}$
and
$e = \frac{\sqrt{a^2-b^2}}{a}=\frac{c}{a}$.
From the value of $d = \frac{a^2}{c}$
or $\frac{d}{a} = \frac{a}{c} = \frac{1}{e}$
Hence $e = \frac{a}{d}$
In this proof, you can see that we have derived d and e from the extremities, since their values are easily available. For the $\frac{PF}{PD}$ ratio, you can put $PF = a - c$ and $PD = d - a$ (similar to what we did for finding d and e).
Hope this helped.
Cheers!
Answer: Hint: If the eccentricity $e$ & the major axis $2a$ of an ellipse are known then we have the following

Distance of each focus from the center of ellipse
$$=\text{(semi-major axis)}\times \text{(eccentricity of ellipse)}=\color{red}{ae}$$
Distance of each directrix from the center of ellipse
$$=\frac{\text{semi-major axis} }{\text{eccentricity of ellipse}}=\color{red}{\frac ae}$$
Comment: I don't think your hint addresses the OP's question but only repeats what he already knows. His questions are how to get the second expression from the first, and why there is a directrix at all.


Function that fulfils the equation

Question: Prove that for all $x\in\mathbb{R}$ there exists only one $y=y(x)$ that fulfils the equation: $$3x+e^x=y+e^y$$
I am completely lost with that. What should i do?
Comment: This is an *implicit* function
Answer: For any real number $a$, the equation $a=y+e^y$, or $e^y=a-y$, has exactly one solution (think of the plots, and use the Intermediate Value Theorem and the fact that the functions are monotone).  So for each $x$, there is a unique $y(x)$ satisfying the equation.
Answer: Let $$f(x,y)=3x+e^x-y-e^y$$.
We know that in the first place for all fixed real $x$, there always exists at least a  real $y$ s.t. $f(x,y)=0$, since $y+e^y$ ranges from $-\infty$ to $+\infty$. So it suffices to show that such a $y$ is unique, which is evident from the fact
 $$\frac{\partial f}{\partial
y}(x,y)=-1-e^y<-1\ne 0$$
due to Implicit Function Theorem.

Function that fulfils the equation


How to show video url from external database(mysql) in android?

Question: I have a project android app stream video from video url is saved in database. But I dont know how to show video from video url in database? Please, help me.... :)
public class PlayerActivity extends Activity {

private stream stream;
private ServerRequest server;
private Object newString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_player);
    stream = new stream();
    server = new ServerRequest();
    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        if(extras == null) {
            newString= null;
        } else {
            newString= extras.getString("alamat");
        }
    } else {
        newString= (String) savedInstanceState.getSerializable("alamat");
    }
    final VideoView vid = (VideoView) findViewById(R.id.videoView);
    Uri video = Uri.parse(server.sendGetRequest(ServerRequest.urlSelectAll+"?id="+stream.getId().toString()));
    vid.setVideoURI(video);
    MediaController hhh = new MediaController(this);
    vid.setMediaController(hhh);
    vid.requestFocus();
    vid.start();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

I want to play video when I click from list view, this list view from my database where in my database table have 2 coloumn : video name and video url. This my main activity for list view
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private ListView listView;
private ActionMode actionMode;
private ActionMode.Callback amCallback;
private ProgressDialog progressDialog;
private ServerRequest serverRequest;
private List<stream> list;
private ListAdapterStream adapter;
private stream selectedList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    serverRequest = new ServerRequest();
    listView = (ListView) findViewById(R.id.listview_main);
    list = new ArrayList<stream>();
    /** melakukan load data melalui AsyncTask */
    new MainActivityAsync().execute("load");
}

private List<stream> processResponse(String response){
    List<stream> list = new ArrayList<stream>();
    try {
        JSONObject jsonObj = new JSONObject(response);
        JSONArray jsonArray = jsonObj.getJSONArray("stream");
        Log.d(TAG, "data lengt: "+jsonArray.length());
        stream str = null;
        for(int i = 0; i < jsonArray.length(); i++){
            JSONObject obj = jsonArray.getJSONObject(i);
            str = new stream();
            str.setId(obj.getInt("id"));
            str.setVideo(obj.getString("video"));
            str.setAlamat(obj.getString("alamat"));
            list.add(str);
        }
    } catch (JSONException e) {
        Log.d(TAG, e.getMessage());
    }
    return list;
}

private void populateListView(){
    adapter = new ListAdapterStream(getApplicationContext(), list);
    listView.setAdapter(adapter);
    listView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View v, int pos, long id) {
            if(actionMode != null){
                return false;
            }
            actionMode = startActionMode(amCallback);
            v.setSelected(true);
            selectedList = (stream) adapter.getItem(pos);
            return true;
        }

    });

    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View v, int pos,
                                long id) {
            selectedList = (stream) adapter.getItem(pos);
            Intent in = new Intent(getApplicationContext(), PlayerActivity.class);
            in.putExtra("id", selectedList.getId().toString());
            in.putExtra("alamat", selectedList.getAlamat());
            startActivity(in);
        }
    });

}

private class MainActivityAsync extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("retrieving...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

            /** Mengirimkan request ke server dan memproses JSON response */
            String response = serverRequest.sendGetRequest(ServerRequest.urlSelectAll);
            list = processResponse(response);

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        progressDialog.dismiss();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                populateListView();
            }
        });
    }
  }
}

Answer: You should create an API, with NodeJS or PHP that connects to your MySQL database. Simple JSON for PHP would do the trick.
Then, you just have to retrive the url from the returned JSON via the GSON library. Several other subjects are about the same problem. example here


Reading vertexes and indices from a SpatialSurfaceMeshBuffer

Question: I'm developing a HoloLens UWP app using SharpDX (a C# DirectX wrapper), and I want to process the spatial mapping data generated by the device.
I have managed to get a list of SpatialSurfaceMesh, which contain the meshes describing the environment, and they have two properties -TriangleIndices and VertexPositions- that I am interested in reading.
The issue is that they are instances of SpatialSurfaceMeshBuffer, which contain an IBuffer with the raw data, alongside with the ElementCount, Stride(length of each element) an
DirectXPixelFormat, and while that format is optimal for rendering the mesh using DirectX I don't know how to read the coordinates of the vertexes and the order of the indices to use them in my app.
I guess I have to somehow read the data from the IBuffer using the specified Stride and Format, but I haven't been able to find any documentation about how to do it, any clue?
Answer: According to this link IBuffer is just a wrapper around byte[] and the vectors are (most of the time) saved in that order x,y,z,w. The format (if int16, float or whatever is used) can be found out by looking into the Format property of the SpatialSurfaceMeshBuffer class. This property also defines if the values are stored in a different order or if additional transformations are neccesary to get the correct position.
So basicly you could do something like
using System.Runtime.InteropServices.WindowsRuntime;

SpatialSurfaceMeshBuffer surfaceMeshBuffer = ...
byte[] data = surfaceMeshBuffer.ToArray();
var vectors = new List<Vector4>();

for(int i = 0; i < data.length; ) {
    float x  = System.BitConverter.ToSingle(data, i);
    i += sizeof(float) / 8;
    float y  = System.BitConverter.ToSingle(data, i);
    i += sizeof(float) / 8;
    float z  = System.BitConverter.ToSingle(data, i);
    i += sizeof(float) / 8;
    float w  = System.BitConverter.ToSingle(data, i);
    i += sizeof(float) / 8;

    vectors.Add(new Vector4(x, y, z, w));
}


How to set the default theme programmatically

Question: I've tried to set a theme as default theme in drupal 8 using the following code
> $config = \Drupal::configFactory()->getEditable('system.theme');
> $config->set('default', 'test_theme')->save();

On installing the module the code is not setting the theme as the one I've entered.
The code is written in hook_install().
Answer: The current advice is to set this via config:
\Drupal::configFactory()
  ->getEditable('system.theme')
  ->set('default', $theme)
  ->save();

The previous method using ThemeHandlerInterface::setDefault() is now deprecated.
You might need to install it first too, I'm not sure. In case you do:
\Drupal::service('theme_installer')->install(['test_theme']);

Answer: I just want to contribute to this answer by adding that there's no need to worry about running both of these commands if the theme is already installed. It technically runs the theme_installer service underneath and checks beforehand for installed themes.


What are these overlapping notes with different rhythms called in Music Theory?

Question: On piano, when playing a long note followed by an overlapping shorter note or vice versa, what is this called? I know this is an extremely common thing in piano music, but I don't know what it's called in music theory. Also, does anyone know how to do this in finale notepad?
Comment: Two part writing/playing?
Comment: What is the overlap? Do you mean the dotted quarter, eighth, quarter is "overlapping" the dotted half note?
Comment: Are you asking about the rhythm or about the multiple "layers of melody" played at the same time in different octaves?
Answer: They are called voices, and according to the Finale web site, Finale Notepad has a "layer" system for writing multiple voices.
https://usermanuals.finalemusic.com/NotePad2012Win/Content/NotePad/Multiple_Voices.htm
Here's an example picture from some other answer

The red circle highlights how notes overlap.
Comment: Genuinely surprised this hasn't been asked before. But several searches turned up nothing. Good, concise answer.
Comment: @Natia Welcome to Music.SE! If this answer did in fact answer your question sufficiently, I invite you to click the checkmark next to the answer to accept it. Of course, feel free to wait a bit for other answers to come in.


C++ Tokenize a string with spaces and quotes

Question: I would like to write something in C++ that tokenize a string. For the sake of clarity, consider the following string:
add string "this is a string with spaces!"

This must be split as follows:
add
string
this is a string with spaces!

Is there a quick and standard-library-based approach?
Comment: Depends. Do you need to support escaping quotes `\"`? Escaping the escape character ``\\``? Other quote characters `''`?
Answer: No library is needed. An iteration can do the task ( if it is as simple as you describe).
string str = "add string \"this is a string with space!\"";

for( size_t i=0; i<str.length(); i++){

    char c = str[i];
    if( c == ' ' ){
        cout << endl;
    }else if(c == '\"' ){
        i++;
        while( str[i] != '\"' ){ cout << str[i]; i++; }
    }else{
        cout << c;
    }
}

that outputs
add
string
this is a string with space!

Comment: you may add some protection in the while loop, i.e., `while( i<str.length() && ...`
Comment: another good point! however, this may fail when I have something with only an open quote, doesn't it?
Comment: Just a caveat: the above code outputs every character when encountered via ```cout```.  This is convenient but misleading: there's no need to worry about handling end-of-string because nothing is being accumulated.  If, on the other hand, the function needs to build up each token and return them in a vector, then you must be sure to also handle end-of-string by inserting the final built-up token into the vector when the for-loop finishes.
Answer: I wonder why this simple and C++ style solution is not presented here.
It's based on fact that if we first split string by \", then each even chunk is "inside" quotes, and each odd chunk should be additionally splitted by whitespaces.
No possibility for out_of_range or anything else.
unsigned counter = 0;
std::string segment;
std::stringstream stream_input(input);
while(std::getline(stream_input, segment, '\"'))
{
    ++counter;
    if (counter % 2 == 0)
    {
        if (!segment.empty())
            std::cout << segment << std::endl;
    }
    else
    {
        std::stringstream stream_segment(segment);
        while(std::getline(stream_segment, segment, ' '))
            if (!segment.empty())
                std::cout << segment << std::endl;
    }
}

Answer: Here is a complete function for it. Modify it according to need, it adds parts of string to a vector strings(qargs).
void split_in_args(std::vector<std::string>& qargs, std::string command){
        int len = command.length();
        bool qot = false, sqot = false;
        int arglen;
        for(int i = 0; i < len; i++) {
                int start = i;
                if(command[i] == '\"') {
                        qot = true;
                }
                else if(command[i] == '\'') sqot = true;

                if(qot) {
                        i++;
                        start++;
                        while(i<len && command[i] != '\"')
                                i++;
                        if(i<len)
                                qot = false;
                        arglen = i-start;
                        i++;
                }
                else if(sqot) {
                        i++;
                        start++;
                        while(i<len && command[i] != '\'')
                                i++;
                        if(i<len)
                                sqot = false;
                        arglen = i-start;
                        i++;
                }
                else{
                        while(i<len && command[i]!=' ')
                                i++;
                        arglen = i-start;
                }
                qargs.push_back(command.substr(start, arglen));
        }
        for(int i=0;i<qargs.size();i++){
                std::cout<<qargs[i]<<std::endl;
        }
        std::cout<<qargs.size();
        if(qot || sqot) std::cout<<"One of the quotes is open\n";
}

Comment: I think there is a small bug in this function. this string `"hello \"world  pol\"  'hello why'"` is tokenized to the following tokens:

`hello`
`world  pol`
`'hello why`

The last token must be `hello why`
Comment: Found the bug!
one `start++;` is missing inside `else if(sqot) {`
Comment: This is the real function that does this. It also supports an unpaired quote inside paired quotes as long as they are different quote characters. (single or double)
Comment: I also added the following to stop having 0 length tokens
`if (arglen > 0) {
            tokens.push_back(str.substr(start, arglen));
        }`
Answer: The Boost library has a tokenizer class that can accept an escaped_list_separator.  The combination of these look like they might provide what you are looking for.
Here are links to the boost documentation, current as of this post and almost certainly an old version by the time you read this.
https://www.boost.org/doc/libs/1_73_0/libs/tokenizer/doc/tokenizer.htm
https://www.boost.org/doc/libs/1_73_0/libs/tokenizer/doc/escaped_list_separator.htm
This example is stolen from the boost documentation.  Forgive me for not creating my own example.
// simple_example_2.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main(){
   using namespace std;
   using namespace boost;
   string s = "Field 1,\"putting quotes around fields, allows commas\",Field 3";
   tokenizer<escaped_list_separator<char> > tok(s);
   for(tokenizer<escaped_list_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg){
       cout << *beg << "\n";
   }
}

Answer: There is a standard-library-based approach in C++14 or later. But it is not quick.
#include <iomanip> // quoted
#include <iostream>
#include <sstream> // stringstream
#include <string>

using namespace std;

int main(int argc, char **argv) {
    string str = "add string \"this is a string with spaces!\"";
    stringstream ss(str);
    string word;
    while (ss >> quoted(word)) {
        cout << word << endl;
    }
    return 0;
}

Comment: Is there a way to keep in the quotes in the last tokened substring?
Comment: Not handling space
string str = "-arg1 -arg2=\"c:\\Test folder with space\\\" -arg3";
Answer: I would define a class Token to read a single token from a stream.
Then using your code becomes very trivial.
#include <iostream>
#include <string>

int main()
{
    // Simply read the tokens from the stream.
    Token   t;
    while(std::cin >> t)
    {
        std::cout << "Got: " << t << "\n";
    }
}

Stream objects like this are very easy to write:
class Token
{
    // Just something to store the value in.
    std::string     value;

    // Then define the input and output operators.
    friend std::ostream& operator<<(std::ostream& str, Token const& output)
    {
        return str << output.value;
    }

    // Input is slightly harder than output.
    // but not that difficult to get correct.
    friend std::istream& operator>>(std::istream& str, Token& input)
    {
        std::string tmp;
        if (str >> tmp)
        {
            if (tmp[0] != '"')
            {
                // We read a word that did not start with
                // a quote mark. So we are done. Simply put
                // it in the destination.
                input.value = std::move(tmp);
            }
            else if (tmp.front() == '"' && tmp.back() == '"')
            {
                // we read a word with both open and close
                // braces so just nock these off.
                input.value = tmp.substr(1, tmp.size() - 2);
            }
            else
            {
                // We read a word that has but has a quote at the
                // start. So need to get all the characters upt
                // closing quote then add this to value.
                std::string tail;
                if (std::getline(str, tail, '"'))
                {
                    // Everything worked
                    // update the input
                    input.value = tmp.substr(1) + tail;
                }
            }
        }
        return str;
    }
};

Answer: I guess there is no straight forward approach with standard library. Indirectly following algorithm will work:

a) search for '\"' with `string::find('\"')` . If anything found search for next '\"' using `string::find('\'',prevIndex)`, If found use `string::substr()`. Discard that part from the original string.

b) Now Search for `' '` character in the same way.

NOTE: you have to iterate through the whole string.
Comment: Is there anything for C?
Comment: Just found this (not tested):

https://www.howtobuildsoftware.com/index.php/how-do/cpYw/c-string-pointers-trying-to-tokenize-a-string-by-spaces-and-quotes
Answer: Here is my solution, it's equivalent to python's shlex, shlex_join() is the inverse of shlex_split():
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <sstream>
#include <utility>
#include <vector>

// Splits the given string using POSIX shell-like syntax.
std::vector<std::string> shlex_split(const std::string& s)
{
  std::vector<std::string> result;

  std::string token;
  char quote{};
  bool escape{false};

  for (char c : s)
  {
    if (escape)
    {
      escape = false;
      if (quote && c != '\\' && c != quote)
        token += '\\';
      token += c;
    }
    else if (c == '\\')
    {
      escape = true;
    }
    else if (!quote && (c == '\'' || c == '\"'))
    {
      quote = c;
    }
    else if (quote && c == quote)
    {
      quote = '\0';
      if (token.empty())
        result.emplace_back();
    }
    else if (!isspace(c) || quote)
    {
      token += c;
    }
    else if (!token.empty())
    {
      result.push_back(std::move(token));
      token.clear();
    }
  }

  if (!token.empty())
  {
    result.push_back(std::move(token));
    token.clear();
  }

  return result;
}

// Concatenates the given token list into a string. This function is the
// inverse of shlex_split().
std::string shlex_join(const std::vector<std::string>& tokens)
{
  auto it = tokens.begin();
  if (it == tokens.end())
    return {};

  std::ostringstream oss;
  while (true)
  {
    if (it->empty() || it->find_first_of(R"( "\)") != std::string::npos)
      oss << std::quoted(*it);
    else
      oss << *it;

    if (++it != tokens.end())
      oss << ' ';
    else
      break;
  }
  return oss.str();
}

void test(const std::string& s, const char* expected = nullptr)
{
  if (!expected)
    expected = s.c_str();
  if (auto r = shlex_join(shlex_split(s)); r != expected)
    std::cerr << '[' << s << "] -> [" << r << "], expected [" << expected << "]\n";
}

int main()
{
  test("");
  test(" ", "");
  test("a");
  test(" a ", "a");
  test("a   b", "a b");
  test(R"(a \s b)", "a s b");
  test(R"("a a" b)");
  test(R"('a a' b)", R"("a a" b)");
  test(R"(a \" b)", R"(a "\"" b)");
  test(R"(a \\ b)", R"(a "\\" b)");

  test(R"("a \" a" b)");
  test(R"('a \' a' b)", R"("a ' a" b)");
  test(R"("a \\ a" b)");
  test(R"('a \\ a' b)", R"("a \\ a" b)");
  test(R"('a \s a' b)", R"("a \\s a" b)");
  test(R"("a \s a" b)", R"("a \\s a" b)");
  test(R"('a \" a' b)", R"("a \\\" a" b)");
  test(R"("a \' a" b)", R"("a \\' a" b)");

  test(R"("" a)");
  test(R"('' a)", R"("" a)");
  test(R"(a "")");
  test(R"(a '')", R"(a "")");
}


Variance-covariance matrix of logit with matrix computation

Question: I'm trying to obtain the variance-covariance matrix of a logistic regression:
mydata <- read.csv("https://stats.idre.ucla.edu/stat/data/binary.csv")
mylogit <- glm(admit ~ gre + gpa, data = mydata, family = "binomial")

through matrix computation. I have been following the example published here for the basic linear regression
X <- as.matrix(cbind(1, mydata[,c('gre','gpa')]))
beta.hat <- as.matrix(coef(mylogit))
Y <- as.matrix(mydata$admit)
y.hat <- X %*% beta.hat

n <- nrow(X)
p <- ncol(X)

sigma2 <- sum((Y - y.hat)^2)/(n - p)
v <- solve(t(X) %*% X) * sigma2

But then my var/cov matrix doesn't not equals the matrix computed with vcov()
v == vcov(mylogit)

1   gre   gpa
1   FALSE FALSE FALSE
gre FALSE FALSE FALSE
gpa FALSE FALSE FALSE

Did I miss some log transformation?
Answer: @Deep North: You are right, there should not be a 'n'
The covariance matrix of a logistic regression is different from the covariance matrix of a linear regression.

Linear Regression:
Logistic Regression:

Where W is diagonal matrix with
 is the probability of event=1 at the observation level
Answer: The covariance for logistic regression from subra is correct. But $w_{ii}=\hat{\pi_i}(1-\hat{\pi_i})$. There should not have a $n_i$. ref. David W. Hosmer Applied Logistic Regression (2nd Editiion) p35 and p41 formular(2.8)
I revised your program and compare with variance estimation, they are close but not the same.
 library(Matrix)
 library(sandwich)
 mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv")
 mylogit <- glm(admit ~ gre + gpa, data = mydata, family = "binomial")
 X <- as.matrix(cbind(1, mydata[,c('gre','gpa')]))
 n <- nrow(X)

 pi<-mylogit$fit

 w<-pi*(1-pi)

 v<-Diagonal(n, x = w)
 var_b<-solve(t(X)%*%v%*%X)
 var_b

         x 3 Matrix of class "dgeMatrix"
          [,1]          [,2]          [,3]
[1,]  1.1558251135 -2.818944e-04 -0.2825632388
[2,] -0.0002818944  1.118288e-06 -0.0001144821
[3,] -0.2825632388 -1.144821e-04  0.1021349767

vcov(mylogit)

         (Intercept)           gre           gpa
(Intercept)  1.1558247051 -2.818942e-04 -0.2825631552
gre         -0.0002818942  1.118287e-06 -0.0001144821
gpa         -0.2825631552 -1.144821e-04  0.1021349526

They are the same at the first five digits
Answer: mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv")
mylogit <- glm(admit ~ gre + gpa, data = mydata, family = "binomial")

X <- as.matrix(cbind(1, mydata[,c('gre','gpa')]))
beta.hat <- as.matrix(coef(mylogit))

require(slam)
p <- 1/(1+exp(-X %*% beta.hat))
V <- simple_triplet_zero_matrix(dim(X)[1])
diag(V) <- p*(1-p)
IB <- matprod_simple_triplet_matrix(t(X), V) %*% X
varcov_mat <- solve(IB)

round(solve(IB),4) == round(vcov(mylogit),4)

# 1  gre  gpa
# 1   TRUE TRUE TRUE
# gre TRUE TRUE TRUE
# gpa TRUE TRUE TRUE

Comment: As a general advice, avoid using diagonal matrices, especially when their dimension depends on sample size, and the sample size is large. They will tend to considerably slow down computation. Element-wise multiplication can be used instead.


Alternatives to LinkedBlockingDeque?

Question: I've a Java program that runs on multiple threads. One of the threads wait for data from another thread and processes it. I used LinkedBlockingDeque to implement it, such that the thread will block until data is available in the queue.
However, the server I'm running on only has Java SE 5, a version that does not have this particular class. Are there any alternatives to this?
Comment: As a side-note: if the server is only running Java 1.5, that may well mean that it has significant security vulnerabilities. I would strongly urge you to start trying to get it upgraded.
Comment: @mushroom: I don't see any evidence of that. It implements `BlockingQueue`, and has `take()` and `poll` methods... what makes you think it's only blocking in one way?
Comment: Have you considered implementing it yourself?
Comment: Can you not use `LinkedBlockingQueue` instead of `LinkedBlockingDequeue`?
Comment: @OlaviMustanoja How should I do that?
Comment: @JonSkeet Doesn't `LinkedBlockingQueue` block only on insertion and not on removal? How should that work out?
Comment: You could implement your own *Producer-Consumer* pattern. check it in  [oracle docs](http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html)
Comment: The simplest way I would think is to download jdk 1.7 (or later) and seeing how java implements it.
Comment: @mushroom look at the source code for `LinkedBlockingDequeue`
Comment: the best approach would be to implement it on your own. see the source code  here http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/LinkedBlockingDeque.java
Comment: @JavaBond: That sounds like a bad idea to me. Threading can be very subtle indeed; it's possible that the source of `LinkedBlockingDequeue` will depend on some particular aspects of other classes. I don't think the OP needs to implement anything here.
Comment: @JonSkeet Hmm. That's true, I was under the impression that `BlockingQueue` only does it one way. On the other hand, the server is not under my administrative control.
Comment: @mushroom: Just because you can't perform the update yourself doesn't mean you can't start agitating for it - or plan to move somewhere else. What are you going to do if you find there *is* a significant security hole which is being exploited?
Comment: @JonSkeet Agreed but since `LinkedBlockingDequeue` extends `AbstractQueue` which is available in Java 5 and implements `BlockingDeque` which OP can introduce of his own there shouldn't be an issue.
Comment: @JavaBond: "There shouldn't be an issue" doesn't sound like a good reason to start copying code with potentially *very* subtle semantics around the memory model. Even though all the other classes that `LinkedBlockingDequeue` uses may exist, one particular implementation may end up relying on some aspects of other class implementation details. This is especially pointless when `LinkedBlockingQueue` can do the job already.
Comment: @JonSkeet Thanks, Jon, for the best answer and simplest solution. Couldn't believe I overlooked that.
Answer: For requirements you described you can use LinkedBlockingQueue available in Java 5
Answer: You can use backports:

The ambition of this project is to provide a concurrency library that
  works with uncompromised performance on all Java platforms currently
  in use, allowing development of fully portable concurrent
  applications. More precisely, the traget scope is Java 1.3 and above,
  and some limited support if offered for Java 1.2.

Alternatives to LinkedBlockingDeque?


Condição para não enviar campo no ajax

Question: Olá!
Existe alguma forma para não enviar o campo senha via ajax, caso este esteja vazio ?
Da forma que está, está enviando como vazio e substituíndo o valor do campo por vazio, então gostaria de enviar este campo, somente se for diferente de vazio.

function form_objeto() {
    var senha = $('#txt_senha').val();
    if (senha !== null){
        _obj_operador.nome     = $('#txt_nome').val();
        _obj_operador.cpf      = remove_mascara($('#txt_cpf').val());
        _obj_operador.login    = $('#txt_login').val();
        _obj_operador.senha    = $('#txt_senha').val();
        _obj_operador.situacao = $('#sel_situacao').val();

    } else {
        _obj_operador.nome     = $('#txt_nome').val();
        _obj_operador.cpf      = $('#txt_cpf').val();
        _obj_operador.login    = $('#txt_login').val();
        _obj_operador.situacao = $('#sel_situacao').val();

    }
}
//Função Salvar
function salvar() {
    form_objeto();
    if (salvar_operador()) {
     atualizar_tabela();
     $('#modal_operador').modal('hide');
 toastr.success('Operador salvo com sucesso');
     }
}
//Método Salvar
function salvar_operador() {
     var url;
     if(_metodo_salvar == 'novo') {
 url = "operador/novo";
     } else {
 url = "operador/atualizar";
     }

 $('#btn_salvar').html(' Salvando');
 $('#btn_salvar').attr('disabled', true);

    var ret;
    $.ajax({
        type: 'POST',
        async: false,
        datatype: 'json',
  url : url,
  data: { 'objeto': JSON.stringify(_obj_operador) },
        success: (function (data) {
            _obj_operador = data;
   $('#btn_salvar').html(' Salvar');
            $('#btn_salvar').attr('disabled', false);
            limpar_modal();
            ret = true;
  }),
        error: (function (erro) {
            //TrataErroAjax(erro);
   alert(erro);
            ret = false;
  })
 });
    return ret;
}
Answer: Tem sim, mas considere por essa validação em seu backend, é mais seguro, e você pode criar outras validações além dessa... você pode remove uma propriedade de um objeto usando o delete.
function form_objeto() {
 var senha = $('#txt_senha').val();
 if (senha !== null){
    _obj_operador.nome     = $('#txt_nome').val();
    _obj_operador.cpf      = remove_mascara($('#txt_cpf').val());
    _obj_operador.login    = $('#txt_login').val();
    _obj_operador.senha    = $('#txt_senha').val();
    _obj_operador.situacao = $('#sel_situacao').val();

 } else {
    delete _obj_operador.senha; //aqui você está removendo a senha

    _obj_operador.nome     = $('#txt_nome').val();
    _obj_operador.cpf      = $('#txt_cpf').val();
    _obj_operador.login    = $('#txt_login').val();
    _obj_operador.situacao = $('#sel_situacao').val();

 }
}

Condição para não enviar campo no ajax


Ubuntu Server 10.04 Heavy Network Traffic causes disconnect

Question: I'm currently running a headless Ubuntu 10.04 server. Installed is the LAMP stack, Joomla, Virtualbox, phpvirtualbox, webmin and proFTP.. It resolves the IP address so I can access it remotely (either the apache2 webserver or the FTP) using DDClient. Any packages installed have been installed using apt-get. Webmin, although discouraged in Ubuntu Server, is used mostly to administer the webserver aspect. This issue also appeared when I was using Ubuntu Server 10.10.
After periods of heavy network traffic, whether local or remote, the connect drops. I'm talking specifically about the transfer of files via FTP, SCP or Samba (the latter of which I seldom use). There is no response to ping or ssh. I can't FTP to the server nor can I load the website. There are times when the server has been on for a few days and everything runs fine because I haven't accessed it much, if at all (thus not much network traffic).
I've gone through a few hardware changes although I don't believe this has cause the issue: this has been happening long before I made any changes. At first I thought it was my ISP-provided router blocking traffic because of some kind of misconfiguration (perhaps assuming it was some kind of DoS attack). I've changed routers and still found no success. I've checked syslog, dmesg and kern.log for warnings but have uncovered none. I've ran memtest via the GRUB2 menu at boot and once it turned up 4 errors. I ran again with individual sticks of RAM in various slots and everything turned up fine. I've looked through the BIOS settings and everything looks fine. I've tried unplugging unnecessary pieces of hardware (other internal hard drives, CD drives, floppy, PCI cards, etc).
Any help or tips on how I can even begin to troubleshoot this would be very much appreciated. Please note that i've only started playing with servers as a hobby so my knowledge wouldn't be the most refined. I'm comfortable with command line and have the initiative to know how to look up something I can't do. Unfortunately I can't seem to find any issues like this.
Additionally: If a solution can't be found some assistance to write a script that will cause the server to reboot automatically if, after x minutes, it gets no response to pinging somewhere like google. Admittedly that's not the cleanest solution should my internet end up going down but I can't think of what else to do.
Comment: Apologies for the very slow reply, Sirex. I've been travelling a bit with limited internet access. I'll respond with this information later this evening.
Comment: I seem to be having a very similar problem on my 10.04 server at home. I'll watch this question closely, and keep you updated if i find a solution.
Comment: Following the advice below I've installed Collectd. I transferred more than 50GB last night without any problems. After that I began, using FTP, the transfer of approximately 130GB of files. Somewhere at 2am this morning the server froze again. I've purged webmin completely, too just in case this was an issue. Approximately at the same time the following command ran: Dec 23 02:39:01 kserver CRON[18114]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -n 200 -r -0 rm) - maybe related?
Comment: This may be coincidence. According to the information by collectd, system load, CPU usage and physical memory were all quite high around that time but reported that there was still RAM available.
Comment: lspci reports: 00:12.0 Ethernet controller: VIA Technologies, Inc. VT6102 [Rhine-II] (rev 78)
Comment: I may have a solution to this. If you run "lspci" - what network card do you have ?
Comment: do you have fail2ban installed ?
Answer: If the server is completely 100% hanging, then an automated reboot script may not help: unless the reboot happens before the hang you are stuck as the hang will likely affect what-ever process is intended to call the reboot script.
A regular reboot via cron may help, if it is set regular enough to trigger before any hang, but this would be treating the symptoms and not the cause. You could trigger the reboot from another machine (if it detects the server stopping responding) but that will likely require a hardware purchase in the form of a power supply/controller that can be toggled from one machine to force another to power-cycle.
I would recommend installing some sort of monitoring tool and checking to see what happens immediately before the hangs occur (i.e. just before new connections stop being accepted). I use collectd (with a custom CGI script to graph the recorded results) for general monitoring though there are several other popular options. Running such a monitoring tool with default settings (monitoring CPU use, memory use, disk I/O, temperature readings, and so forth) will help you spot obvious things like a sudden burst of CPU activity (which may imply a bad script or a DoS situation) or creeping memory/swap use (which may imply a memory leak somewhere, or in the case of Apache and similar services a worker allocation configuration that is inappropriate for the size of machine), a sudden rise in temperature (which may imply a circulation issue, poor ventilation, or other external environmental conditions being part of the problem), and so on. If a generic issue like this is identified you can then add more detailed monitoring to zero in on a more specific cause.
Also, install and configure smartd if you have not already done so. This may help tracking the problem if it is down to a drive that is developing (or already has) a serious problem.
In any case, check the usual suspects in /var/log after a hang - you may find some clues get recorded in places like /var/log/messages and /var/log/syslog (or similar) just before the machine stops responding. If nothing on the machine itself stops when the remote connections start failing, you might have a bad network card that is hanging (but leaving the rest of the machine OK) and staying in that hung state until the machine is rebooted or power-cycled.
More specifically: your RAM tests showing some errors on one or two occasions makes either RAM or cooling quite likely culprits. You could have some "slightly" dodgy RAM that usually works and passes tests but very occasionally flips bits and causes problems, or you could have a RAM issue that is temperature sensitive (all is fine until the heat hits a certain point), or it could be a more general heat/cooling issue. Your CPU or other core chips could also be experiencing heat problems that would result in similar intermittent effects.
Comment: David, Thank you for taking the time to write such an informative answer. I'm in the process of installing the monitoring tools you've prescribed in the hope that I can find the cause before considering resorting to a cron script. The final comment you made regarding temperature is very plausible - sometimes the room in which I keep the server gets quite warm and heavy CPU/RAM usage will just make the server warmer. Thank you again.
Answer: This may not be the reason for you but I've been seeing this in 10.04 LTS for some time when using dhcp.  However, when setting the interface address as a static one, the problem goes away.
I know it has been an issue with 10.04 LTS because I've seen it occur on at least 1 PC and 2 servers with Intel NIC's.  I should also point out that this issue seems to be resolved for me with the latest build of Ubuntu 10.04 LTS server.  I believe it is build 3 or 4 of that.
https://askubuntu.com/questions/102910/ubuntu-server-10-04-lts-xen-intermittent-networking
For now make sure you are not using DHCP to assign the address, even if the DHCP server is set to always give out the same address.  Rather, set it statically in /etc/network/interfaces
Answer: Similar issue w/ Apache/PHP on RHEL5.x: hanging and console/ssh access impossible.  Log /var/log/messages reported "[...] httpd invoked oom-killer [...]"
The solution was adding more memory, enabling KDump w/ panic_on_oom and creating more appropriate Apache/PHP process limits.  No issues since.  The KDump w/ panic_on_oom automatically restarted the system preventing a hang.  However the real fix was limiting Apache/PHP.  The defaults, esp. for PHP, were too wide open and not secure.  There are numerous online resources for securing PHP, so I will not try and recreate one here.
Answer: I believe it may be due to the services heavily taxing your system resources. Another possible solution may be to look at how many possible connections you can have to your web server and/or how many hosts can use the router.
Comment: I do not know if this is relevant but do you have a DMZ for your public facing web server?
Comment: I still may be wrong but to be more specific to any relevent info is check the subnetting of you dont dig enough into the problem it may be like ips get resolved if running somewhat of a small farm it could explain inresponse that when checking ip resolution since all have had layer3 access it would casue it all to drop because the packets still need a network device unless adhock and if you have bridgehead srv to other physical banks this addition to certain times of services being down thats almost network edge (exchange users) could possibly cause this heavy traffic gets exceeds the number


How difficult is GRE Math compares to these two past exams?

Question: I am wondering how difficult GRE Math Subject Exam is. I have tried the following two:

http://www.math.ucla.edu/~cmarshak/GRE2.pdf
http://www.math.ucla.edu/~cmarshak/GRE3.pdf

I am getting different claims. Some people say that these two tests are old and current test is way more difficult than them. Some people say that they are roughly the same. Any thought?
Comment: 170min for 66 questions ?
Comment: @user1952009 What is wrong with that?
Comment: Misakov, you'll find out what's wrong with it when you take the exam.  :)
Comment: I never took the math GRE and I got into a top 20 school! That's a "don't try this at home" thing though.
Comment: the links are not working.
Answer: The current versions are significantly harder.
I would say that if you want to finish the current GRE in the $170$ minute time frame you need to be able to solve the ones from the $20$th century in about an hour.
Regards.
Comment: My best students second this opinion. And I quote, "that was nothing like the practice tests... it was... mean".
Comment: I'm planning on taking the GRE in the fall...if these tests aren't a sufficient indication of the difficulty level, do you know what would be? Thanks
Comment: When I took it ~3yr ago, it was *only* people taking the math GRE that needed every last second -- even the physics people seemed to finish (or give up) with a few minutes to spare. It was pretty unpleasant.
Comment: @Misakov Tricky and there are a good number of out-of-left-field questions that you wouldn't really reasonably be able to prepare for. It's not a pleasant experience.
Comment: This is on-point. The practice MGREs floating around online are nowhere near as challenging as the MGREs have been as of late, in my opinion.
Comment: Agreed to all of this.  Hardest test I've ever taken..
Comment: @CameronWilliams Like how challenging? Is it computationally intense or you have to know lots of theorems or it's just tricky? O_O
Comment: @Misakov, yes, yes, and yes.
Comment: I think you can safely break the test up into two pieces.  For more advanced topics (topology, analysis, probability theory, etc), you basically just need to know a definition and a simple result.  For the calculus/algebra/"real analysis" type problems, you need to really know your stuff.  It's not just that it's computationally intensive - you need to understand the material fundamentally enough that you can extrapolate greatly from your coursework to derive results; most of these types of problems "suggest" a computational approach that you will never be able to complete in the time limit.


Number of arrangements of 7 persons in a round table with 7 seats

Question:
How many arrangements of $7$ persons at a round table with $7$ seats do you have?

I know there are two approaches for this problem:
1) If seats are numbered, I have $P_7=7!$ dispositions. I'm sure about it.
2) If seats are not numbered, I should consider the positions of people compared to each other (So I have e.g. $\{1,2,3,4,5,6,7\}=\{2,3,4,5,6,7,1\}=...=\{7,1,2,3,4,5,6\}=\{7,6,5,4,3,2,1\}=...\{1,7,6,5,4,3,2\}$
cause people are arranged always in the same way).
My book says solution for this point is $\frac{P_7}{7}$ but I'm not sure it's correct. I think I should remove more arrangements, but I don't know the number.
Am I wrong or am I right?
Answer: If the seats are numbered, you are correct.
If the seats are not numbered, by convention, it is the relative order of the people around the table that matters.
Two approaches:

Suppose Alexandra is one of the people.  We seat her at the table.  It does not matter where.  We then proceed to seat people clockwise around the table, starting at her immediate left.  There are six choices for the person to her immediate left, five choices for the person to the immediate left of that person, and so forth.  Hence, there are $6!$ distinguishable seating arrangements.
We can seat seven people in $7!$ orders.  However, since only the relative order of the people matters, the seating arrangements are invariant under rotation.  Rotations to the right by $0$, $1$, $2$, $3$, $4$, $5$, or $6$ places all preserve the same seating arrangements.  Hence, the number of distinguishable seating arrangements is
$$\frac{7!}{7} = 6!$$
Comment: I understand your first approach and thank you for your corrections and answer. What I can't understand is why you divide the Permutation for $7$.
Comment: By the way, I think I will always use the first approach.
Comment: I also prefer the first approach.  As for the second approach, notice that for each seating arrangement, there are seven rotations that preserve the same relative order, namely rotations to the right by $0$, $1$, $2$, $3$, $4$, $5$, or $6$ seats.  Hence, we must divide by $7$ so that we do not count these arrangements seven times.


Python Beginner Using Variables to change Tkinter Canvas Items

Question: I am having a seemingly simple issue with getting the default value of variables to change. I am trying to make a rectangle drawn on a Tkinter Canvas to get smaller when I press a button. Any help in understanding how the variables work would be greatly appreciated. I am working in Python 3.6.
Here is a sample:
from tkinter import *
root=Tk()
bar_var=200

def test_callback():
    iteration = 100
    for iteration in range(0, iteration):
        bar_var -= 1
        bar_display.coords('bar', 0, 4, bar_var, 16)
        print("bar_var =" + str(bar_var))
bar_display = Canvas(root, height=20, width=200)
bar_display.grid(row=0, column=0)
bar_display.create_rectangle(0, 4, 200, 16, fill='blue', tag='bar')

button = Button(root, text="Resize Bar", command=test_callback)
button.grid(row=1, column=0)
root.mainloop()

I have tried to change the "bar_var" variable to an example I found:
bar_var = None
    if bar_var():
        bar_var = 200

but this seems to throw an exception None Object type is not callable. Any help and explanation would be appreciated. Thanks!
Answer: Your variable bar_var is not defined as a local variable within your function. Even if you put a simple command like bar_var += 2 into the function body, it will throw an error, because it doesn't know, what your variable is.
One way to overcome this problem, is to refer to the global variable, when calling the button function with, surprise, global:
def test_callback():
    global bar_var
    iteration = 20
    for iteration in range(iteration):
        bar_var -= 1
        bar_display.coords('bar', 0, 4, bar_var, 16)
        print("bar_var =" + str(bar_var))

Comment: Thanks this worked. Although for anyone wondering this did not update the Canvas item until the function ends and root.mainloop() was executed so to fix that problem I instead changed it to an if statement and set it to call the function for each draw update I wanted to force the mainloop to update the canvas items.


Wrapper to build std::unique_ptr with plain function deleters

Question: I was trying to implement an std::unique_ptr factory that I could use like this:
auto fd = my_make_unique<fclose>(fopen("filename", "r"));

I.e., pass the deleter function as a template argument.
My best attempt in C++11 was:
template<typename D, D deleter, typename P>
struct Deleter {
    void operator()(P* ptr) {
        deleter(ptr);
    }
};

template<typename D, D deleter, typename P>
std::unique_ptr<P, Deleter<D, deleter, P>> my_make_unique(P* ptr)
{
    return std::unique_ptr<P, Deleter<D, deleter, P>>(ptr);
}

In C++14 it is much cleaner:
template<typename D, D deleter, typename P>
auto my_make_unique(P* ptr)
{
    struct Deleter {
        void operator()(P* ptr) {
            deleter(ptr);
        }
    };
    return std::unique_ptr
(ptr);
}

But both solutuions would require me to pass the type of &fclose before fclose itself as template argument:
auto fd = my_make_unique<decltype(&fclose), fclose>(fopen("filename", "r"));

Is it possible to get rid of decltype(&fclose) template argument in C++11? What about in C++14?
EDIT: Why this question is not a duplicate of RAII and smart pointers in C++: referenced question is about general RAII techniques in C++, and one of the answers estates that std::unique_ptr can be used for this purpose. I am already familiar with RAII pattern and how std::unique_ptr is a solution, but I am concerned with present question on how to build an easier to use abstraction to this frequent case I encounter when interacting with C libraries.
Comment: `FILE*` was just an example everyone is acquainted to. This is most useful to interact with C libraries full of `create_()` and `destroy_()` functions. Anyway, `*` and `->` are available for plain `FILE *` pointers, too, and it is no worse inside `std::unique_ptr`.
Comment: I disagree with this duplication mark, my question is much more specific.
Comment: Most voted answer in this other questions shows usage `RAIIFunc f = ::open("...");`, which, as my solution, also requires the type of the destructor function as the first template argument. My question is specifically how to remove that template argument (if possible).
Comment: Taking the address of a standard library function is undefined. thus passing fclose as a template argument is undefined behavior (even so it works), because a standard library implementation is free to add additional overlaods or more parameters with default arguments, only the calls are specified to work (with some exceptions) see https://wg21.link/p0551 R>=3)
Answer:
Is it possible to get rid of decltype(&fclose) template argument in C++11? What about in C++14?

No, not until C++17 can you get rid of the type of that parameter. Template non-type parameters need a type, which you can't deduce - because it has to be a template non-type parameter. That's one problem.
Additionally, you have the problem that taking the address of functions in the standard library is unspecified. The standard library is always allowed to provide additional overloads, for instance, so &fclose may be invalid. The only truly portable way of doing this is to provide a lambda or write your own wrapper function:
auto my_fclose_lam = [](std::FILE* f) { std::fclose(f); }
void my_fclose_fun(std::FILE* f) { std::fclose(f); }

And with either of those, with C++14 at best you can introduce a macro like:
#define DECL(v) decltype(v), v
auto fd = my_make_unique<DECL(my_fclose_lam)>(fopen("filename", "r"));

C++17 allows you to at least lift your custom function into a template parameter (though not yet a lambda) via template auto:
template <auto deleter, typename P>
auto my_make_unique(P* ptr)
{
    struct Deleter {
        void operator()(P* ptr) {
            deleter(ptr);
        }
    };
    return std::unique_ptr
(ptr);
}

my_make_unique<my_fclose_fun>(fopen(...));

C++20 will finally allow you to stick a lambda into there:
my_make_unique<[](std::FILE* f){ std::fclose(f); }>(fopen(...));

Old incorrect answer:
So the best you can do is introduce a macro like:
#define DECL(v) decltype(v), v
auto fd = my_make_unique<DECL(&fclose)>(fopen("filename", "r"));

Whether or not you think that's a good idea is probably up to your coworkers.

In C++17, with template auto, you could just be able to write my_make_unique<fclose>, which is great:
template <auto deleter, typename P>
auto my_make_unique(P* ptr)
{
    struct Deleter {
        void operator()(P* ptr) {
            deleter(ptr);
        }
    };
    return std::unique_ptr
(ptr);
}

Comment: see my comment to the question, taking the address of fclose is non-portable and not sanctioned by the C++ standard (will be more explicit verboten in C++2a)
Answer: Pragmatic approach: Make the deleter a runtime parameter.
template<typename P, typename D>
auto my_make_unique(P* ptr, D deleter)
{
    return std::unique_ptr
(ptr, deleter);
}

int main()
{
    auto fd = my_make_unique(fopen("filename", "r"), fclose);
}

Comment: This is what I am currently doing. The drawback, besides the possibly larger structure, is that the return type (that I typedef to something) is not default constructible.
Comment: see above. &fclose is verboten.
Comment: @PeterSom What do you want to tell me?
Comment: It is unspecified to take the address of a standard library function. That includes the functions inherited from the C library, such as fclose. To make this answer correct, fclose must not be given directly as an argument. One workaround would be a lambda calling fclose and passing that.
Comment: @PeterSom I see. I will update this answer when I find some time.
Answer: Another workaround is use exactly signature of function:
template<typename T, int (*P)(T*)> //for `fclose`
auto my_make_unique(T*) { ... }

template<typename T, void (*P)(T*)> //for other function signatures
auto my_make_unique(T*) { ... }

//etc.

auto uniq = my_make_unique<File, fclose>(fopen("filename", "r"));

This is not universal solution but in 95% cases will work.
Answer: The typical way to create a std::unique_ptr for a FILE* pointer is:
auto fd = std::unique_ptr<FILE, decltype(fclose)>(fopen(...), fclose);

You could wrap that in a macro:
#define my_make_unique(ptr, deleter) \
    std::unique_ptr<std::remove_pointer<decltype<ptr>>::type, d>(ptr, deleter)

And then use it like this:
auto fd = my_make_unique(fopen(...), fclose);


How to alter routes defined in route_callbacks?

Question: Usually I alter static routes in routes subscriber:
  protected function alterRoutes(RouteCollection $collection) {
    $route = $collection->get('gutenberg.media.load_media');
    if ($route) {
      $route->setDefault('_controller', '\Drupal\gutenberg_adv\Controller\MediaController::loadMedia');
    }
  }

However I this does not work for routes defined in routes_callback, so this does not work for search route for example:
$route = $collection->get('search.view_node_search');
if ($route) {
  $route->setDefault('_controller',
      '\Drupal\wi_misc\Controller\SearchController::view');
}

So how to alter search route controller?
Comment: Did you set the `search` module as a dependency of your own module ?
Comment: A full example of overriding the SearchController can be found at https://stackoverflow.com/a/44522792/6046296
Answer: Try to change the weight of the execution of the alterRoutes function.
You can override the getSubscribedEvents function:
public static function getSubscribedEvents(): array
{
    return [
        RoutingEvents::ALTER => [
            'onAlterRoutes', 1
        ],
    ];
}

Notice that i call onAlterRoutes instead of alterRoutes. This is because in the parent class this is a wrapper for the called function:
public static function getSubscribedEvents() {
    $events[RoutingEvents::ALTER] = 'onAlterRoutes';
    return $events;
}

The higher your number (= weight) is, the earlier it gets executed (or the other way around).
I would try with some high and some low numbers and check the result.
I have never tried it with this specific eventbut i used this method to solve other problems with events in some RouteSubscriber.
If you use drush to clear your cache (which you should after changing code in a RouteSubscriber) then you can also use var_dump($route); to ensure your route does exist and is loaded correctly. The dump will get displayed in the cmd.
Comment: unfortunately this does not affect at all
the route definitely exists, I checked it
but Drupal still uses default controller


How to display the data of a View in table format?

Question: I created a view using "Table" as its format already. When I click on the title column record it shows the fields one by one.
Can I display the data of a view as table format?
Comment: Have you tried to play with display options? Table is there...
Answer: yes there us absolutely a way

go to any view->FORMAT->Format (unformated list) click on that see below for image
click on table format ->apply display

and enable label in all fields. will display it in table format
Comment: I got the View in Table format already. My question is, when i click on the title column record that shows fields one by one. i want to display it as table format
Answer: The DataTables module might help to further enhance the prior answers to this question. Here is a quote from its project page:

The DataTables module integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:

Variable length pagination
On-the-fly filtering
Sorting with data type detection
Smart handling of column widths
Themeable by CSS
And more ...

Another feature that it offers is that you can "hide" specific columns from the default table display. But still the user has the option to do things like:

expand the hidden columns.
use the DataTables search feature to search for rows containing one or more strings contained in ... even those hidden columns.

So you could use an approach to only show, by default, a subset of all the columns, and leave it to the user to yes/no also display the (initially hidden) columns.
A few more links you may want to look at:

Show / hide columns dynamically (use the links following Toggle column to see it at work).
Tutorial about Using DataTables In Drupal 7.
How to hide (and show) a table column (using the jQuery DataTables plugin).
jQuery DataTables hide column without removing it from DOM.

Refer to the (short) video about Create Powerful Tables with the DataTables jQuery Plugin and Views for an intro about it, and how to use it as a views style plugin. Using the "settings" link for this views style, you can specify all sorts of dataTables options/features. In the above video starting from around 3:00 you see many of them.
Example
Below is a screenprint of such display using DataTables. It's a display created using Views (of course) with a table with:

8 fields in (defined in my view).
5 table columns for the 5 fields I have decided to always show.
3 table columns which I defined as "hidden and expandable" (within the DataTables settings after you select DataTables as the Views style).

Here is how the DataTables display looks like:

For each row there is a link 'Show Details' (in its 1st column). If you click on one (or more) of them, the hidden fields of such row are shown below that row (with grey background here) and the link you clicked changes to 'Hide Details'. Obviously, I've not done any styling for such expanded row (hence the grey background, etc). But you can see the 3 fields that were initially hidden.
Bonus: assume none of the rows are shown expanded, and you type "Basic" in the DataTables search box. It will then dynamically (in the browser, no server calls) reduce the table display to only those rows with Basic Page as value for "Type". But wait, there is even more: if you'd type a string like part of "21:15" instead (hidden in some of the rows), it will also dynamically reduce the table display to only those rows, like the expanded row shown in the screenprint. But wait, there is even (quite) a bit more: a search string like  "basic 21:15" will filter the rows to a combination of both search strings. For only this one feature I often recommend the amazing DataTables module, one of Drupal's hidden gems I think. And then there are the other features like pager, sortable columns, etc.
Remarks

Make sure to use the 1.9.x version of the DataTables library (not 1.10.x or above), as mentioned also on the project page, which states:

While there is work in the 7.x-2.x branch to upgrade to the latest DataTables version (1.10.x), the 7.x-1.x branch only works with DataTables <= 1.9.x. Since it's not listed in the projects download page, you will have to download it directly.

When creating a view, disable the pager of your view, since DataTables provides its own paging features (the video talks about that starting from 2:05).
Answer: In the Views interface, in "Format", you can select the "Table" format, instead of the default "Unformatted list".
See more about View formats.
Comment: i am asking about a record. When i click the record title it shows one by one.


Dynamically building a table for a report

Question: I have a temporary table that hold all items available
#TableA

ItemId  ItemName    ItemVer
1       Name1       2
2       Name2       9
3       Name3       5
.
.
.
500     Name500     3

I then have another that holds all the dates a Snapshot was taken along with the SnapshotId
CREATE TABLE #tmpSnapshot_Dates(
[SnapshotId] [uniqueidentifier] NOT NULL,
[DateTaken] datetime NOT NULL)

INSERT INTO #tmpSnapshot_Dates SELECT SnapshotId, DateTaken From Snapshot_Info Where DateTaken <= @EndDate

Now for each date in the #tmpSnapshot_Dates table I want to get a count that relates it each Item
SELECT ItemId, Count(*) From Items Where SnapshotId = @SnapshotId

And then update #TableA by adding a column
DECLARE @ColName VARCHAR(100)
SET @ColName = 'Installed ' + CONVERT(Varchar, @DateA, 6)

exec('ALTER TABLE #TableA ADD ['+@ColName+']  int NOT NULL CONSTRAINT [DF_#TableA_Installed on] DEFAULT 0')

And then insert the data into the new column.  I then need to repeat this for each date in #tmpSnapshot_Dates
giving a resulting #TableA that looks something like
#TableA

ItemId  ItemName    ItemVer    Installed 01 Jan 12    Installed 07 Feb 12
1       Name1       2          34                     33
2       Name2       9          56                     59
3       Name3       5          12                     26
.
.
.
500     Name500     3          98                     106

My questions are

Am I creating a nightmare here by approaching it the wrong way?
How am I best to loop through #tmpSnapshot_Dates and then get the data to create the next column? I always try to avoid cursors but is this one of those situation I need to use one?

There could be 12 columns to add and not every item will be returned for each date.
Comment: I don't know why the format of this post has ended up in long lines.  It doesn't look like this when I edit it.
Answer: Definitely it won't be nice, but yes, you need to use cursors and iterate over the #tmpSnapshot_Dates, but if you have the option i suggest you to use a reporting software with the capability to create pivot grids.
Comment: I cant use any other reporting software bar the one I have. I have used cursors and its not as bad as it it could be.  With a max of 12 dates it should be fine.
Answer: Would it not be better to have a separate (temp?) table referencing the ItemId in #TableA eg:
InstalledDate    ItemId    Count
-------------    ------    -----
2012-01-01            1       34
2012-01-01            2       56
2012-01-01            3       12
.                     .        .
.                     .        .
.                     .        .
2012-01-01          500       98
2012-02-07            1       33
2012-02-07            2       59
2012-02-07            3       26
.                     .        .
.                     .        .
.                     .        .
2012-02-07          500      106


Is there a way to open the word (doc or docx) file by default on load using ejs-documenteditorcontainer in angular 8+?

Question: Here I have tried using [(ngModel)] to render a word file but it's not working as required. Is there any other way around?
I have used Angular 10
Thanks in advance
HTML:

    <ejs-documenteditorcontainer
      serviceUrl="https://ej2services.syncfusion.com/production/web-services/api/documenteditor/"
      style="display:block;height:660px" [enableToolbar]=true [(ngModel)]="editor"> </ejs-documenteditorcontainer>

TS:
import { Component, ViewEncapsulation } from '@angular/core';
import { ToolbarService } from '@syncfusion/ej2-angular-documenteditor';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [ToolbarService]
})
export class AppComponent {

  editor: any = 'www.someWordFileFromOneDriveOrFromGoogleDrive.com'

}

Answer: Finally I found a trick. I don't know why Syncfusion didn't mention this api in their documentation. But it works!! Stackblitz demo is here. You can load your word file to ejs-documenteditorcontainer by following this idea.
Add to HTML:
    <input id="open_word" #open_word style="position:fixed; left:-100em" type="file" (change)="onFileChange($event)" accept=".dotx,.docx,.docm,.dot,.doc,.rtf,.txt,.xml,.sfdt"/>
    <button ejs-button (click)="onFileOpenClick()">Import</button>

Add to TS:
    public onFileOpenClick() :void {
        document.getElementById('open_word').click();
    }

    public onFileChange(e: any) :void {
         if (e.target.files[0]) {
            let file = e.target.files[0];
            if (file.name.substr(file.name.lastIndexOf('.')) !== '.sfdt') {
                this.loadFile(file);
            }
        }
    }

    public loadFile(file: File): void {
        const serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/documenteditor/';
        let ajax: XMLHttpRequest = new XMLHttpRequest();
        ajax.open('POST', serviceUrl + 'Import', true);
        ajax.onreadystatechange = () => {
            if (ajax.readyState === 4) {
                if (ajax.status === 200 || ajax.status === 304) {
                    // open SFDT text in document editor
                    this.documentEditor.open(ajax.responseText);
                }
            }
        }
        let formData: FormData = new FormData();
        formData.append('files', file);
        ajax.send(formData);
    }

Old Answer: Actually it is not easy to load. Either you need to convert your doc/docx file to SFDT format and open it with document editor or you can make this file conversion using the .NET Standard library Syncfusion.EJ2.WordEditor.AspNet.Core by the web API service implementation.
You can check this documentation from Syncfusion for details.
Comment: The way you want seems not possible. If you want, you can try two methods, but I am not sure if those are working for you. First method, you can try below link by changing sfdt file extension restriction to doc/docx. Second method, you can lead your user to use toolbar to open doc/docx file.   https://ej2.syncfusion.com/angular/documentation/document-editor/import/#import-document-from-local-machine
Comment: My scenario is that I am developing a document management system using angular and on clicking a file in my app, I need to open that respective file in the **ejs-documenteditorcontainer**. So this is not posssible?
Comment: your new solution works perfectly for opening a file manually. That is, the user needs to click on the import button in order to open or select a file. But I wanted to open the file on load. That is, I want to display a specific doc/dox file in the editor initially and there should be no use of the open/import button.
Comment: I see. Where is your specific doc/docx file? Is it local file or in the asset or somewhere else?
Answer: Document editor is not a form element. Hence it won't support ngModel directive for binding data. It accepts only SFDT Json string. Hence you need to convert the word document to SFDT to open it in editor via open API of document editor.
https://ej2.syncfusion.com/documentation/api/document-editor#open
To open the file on load, you can use created event of document editor.
https://ej2.syncfusion.com/documentation/api/document-editor#created
Sample link to open the SFDT data in created event: https://stackblitz.com/edit/angular-7tvebw-3abz1v?file=app.component.html
For converting word documents to SFDT to load it in editor, you need server-side interaction.
Please refer the below documentation for converting word documents to SFDT in server-side.
https://ej2.syncfusion.com/angular/documentation/document-editor/import/#convert-word-documents-into-sfdt
you can also check the below documentations platform-wise on web services needed for document editor.
https://ej2.syncfusion.com/angular/documentation/document-editor/web-services/core/
https://ej2.syncfusion.com/angular/documentation/document-editor/web-services/mvc/
https://ej2.syncfusion.com/angular/documentation/document-editor/web-services/java/


Javascript declaring a function in an Object

Question: I am looking at some old code and some of the functions are defined as option 1 and others as option 2.
Is there a difference between these function declarations:
Option 1
obj.util.test = function util$test(x){
...
}

Option 2
obj.util.test = function (x){
...
}

Comment: If you got many different `test` functions, identifying the `util$test` function among them might help in debugging. Apart from that, there's hardly any difference.
Answer: In this case they are both identical.

In Options 1 property test is created using a named function.
In Options 2 property test is created using a anonymous function.

Named functions  are useful because can be seen in stack traces and call stacks.