There's got to be a FOSS web-based LDAP password reset app out there, right?

Question: It seems like every shop that uses LDAP at some point has to cobble together something to let users reset their passwords without bothering the IT staff.  The workflow almost always looks like:

User gives username (jblow)
Email jblow@company a link
User clicks link, puts in a new password

On the backend, that corresponds to:

Web form gets a username, stores (username, big unique string) in a DB, emails big unique string to username@company
Other form has a click on https://site/pwreset/big unique string , uses that to authenticate the user, changes their password

Right? So, has someone written one of these that they share?  I'd rather use one that's had a bit more thought put into it than the 10 minute job everyone seems to do.
I did a quick search of Sourceforge, Freshmeat etc and didn't find anything that wasn't abandoned.
Comment: Why do your users have LDAP passwords that are different from their email passwords?
Comment: @Bill: did you find anything useful? I need to do the same thing.
Comment: you should be able to wrap this up into a little cgi script. shouldn't be a need for unique links though, just old password + new password, add some rate limiting to it and log all access to the script, and / or have the script read a list of allowed usernames and add an entry when someone requests a password change.
Comment: @Sirex: you miss the point. This is such a common thing, with usability and security subtleties, that we shouldn't each have to roll our own self-reset script. There should be at least one well-known, well-maintained open-source solution out there.
Comment: maybe. ive never experienced anything beyond 4-5000 or so users, but password resets are perhaps once a fortnight here at most. How many do you get ?
Comment: Jason: I haven't had a chance to play with any of these yet. It's been a while, I know, but that's what I've got :(
Comment: Do you want "reset when user has forgotten" or "periodic change"?  They're two quite different requirements, and in a corporate environment I don't think I'd really *want* to let people reset passwords automatically when they forget them.  At any rate, most places probably roll their own because integrating all the password-related policies into a standard tool is just too much effort.
Comment: user84104: Different environments.  Email is in the office, LDAP is in our production site.  We don't want production things authing to the office, because it would be bad if production went down because the office was being worked on :)
Comment: Womble: Really?  Assuming we auth them in some manner (such as access to email, which is a different pw, etc), why not let them reset their passwords?
Comment: https://github.com/jrivard/pwm
Answer: We use horde for password changes, but not sure if it can fit the workflow you want.
Comment: http://www.horde.org/apps/passwd
Comment: Oh, ok.  How did I miss that?  Thanks!
Comment: Did it work out for you?
Comment: I'll take a look.
Comment: It looks like it would be a pretty huge install to just do password changes.  Is there a component that does that that I don't see?
Answer: This isn't the best documented project, but it has the advantage of being fairly simple PHP with a couple of installers for various linux flavors that get it up and running fast:
http://ltb-project.org/wiki/documentation/self-service-password/
If you are concerned about security, my recommendation is to use a more fully supported widely used package, since I don't know how well this project has been put through its paces.
Comment: Hey, that looks pretty good! I'll give it a shot.
Answer: phpLdapPasswd, but it is no longer being maintained.
Comment: Yeah, I saw that one, but the big "HEY, NO ONE CARES FOR THIS CODE ANYMORE" always worries me.
Answer: ADSelfService Plus from ManageEngine is available in a free version. You'll have to check it out for yourself to determine the limitations of the free version to see if it fits your needs.
Comment: I'll take a look.
Comment: Hmm.  I don't see anything on there about the feature set of the free one, and I see the language "30 day free trial".  I also don't see anything about LDAP on there.  Have you used it for a non-AD LDAP server?  Do you know what the free version is, compared to the paid?
Answer: An alternative to the sequence you give is the LDAP Password Modify Extended Operation, which is supported by modern, professional-quality directory servers. This is an LDAP extended request that changes the password upon being presented with the existing password (as opposed to a reset), and can also request the directory server to generate a password if desired.
Comment: That's not really what I want.  There still needs to be a frontend for the non-technical people, right?
Answer: I don't know of password reset apps, unfortunately. There are a few for changing passwords:
There's admin-ldap in Ruby/Sinatra, ldap_password in Perl/Mojolicious, and ldapchangepw in Python/Flask.
I wasn't happy with the approach admin-ldap or ldap_password took to changing passwords, so I wrote Gente. It uses the Modify Password extended LDAPv3 operation. I would recommend using it or ldapchangepw.
Comment: Looks interesting.  In my case I need something to let users reset their password if they've forgotten it, which is missing here.
Comment: Good point. I've clarified my answer.
Answer: Is there any way to lock down phpLDAPadmin for "normal" users to login and manage their own information (I don't know, just a thought)? This might be worth looking into, if you guys use OpenLDAP (of course, I don't know which implementation of LDAP you have...)
I've been doing a lot of theoretical / high-level research on openLDAP recently, and will probably be implementing a new LDAP server w/ phpLDAPadmin soon...
Comment: I don't think so... users can log in to it and modify whatever they have access to, which doesn't really fit my needs.


Probability computation involving order statistics

Question: Let $X_1$, $X_2$.. $X_n$ be iid uniform random variables i.e.   $X_i \sim U(0,1)$. We know that the order statistics, $X_{(i)}$ is beta distributed $X_{(k)} \sim B(k,n+1-k)$.
Also let $Y_1$, $Y_2$.. $Y_n$ be another set of uniform random variables i.e.   $Y_i \sim U(0,1)$. The order statistics $Y_{(i)}$ are also beta distributed $Y_{(k)} \sim B(k,n+1-k)$.
I'm interested in  finding the following probability,
$\Pr(X_{(1)} < Y_{(2)}, X_{(2)} < Y_{(3)})= ?$
The problem here is that the events $E_1 \equiv \{X_{(1)} < Y_{(2)}\}$ and $E_2 \equiv \{X_{(2)} < Y_{(3)}\}$ etc are not independent, and I'm unable to come up with ways to make them independent so as to make use of the known marginal densities.
Is there any simple way to solve this problem?  Any pointers to a solution are welcome.
Comment: Using _Mathematica_, one can find the answer using `Probability[
x1 < y2 && x2 < y3, {Distributed[{x1,x2}, OrderDistribution[{UniformDistribution[],n}, {1, 2}]], Distributed[{y2,y3}, OrderDistribution[{UniformDistribution[], n}, {2, 3}]]}]` that gives the answer of $$ \Pr\left(X_{(1)} < Y_{(2)}, X_{(2)} < Y_{(3)}\right) = \frac{(5n-4)(n-1)-1}{8(n-1)^2 - 2}$$
Comment: In Mathematica, is it possible to use an arrays x[1] and y[2], instead of x1,x2 and y1,y2? It will help to get the general result when an expression such as $\Pr\left(X_{(1)} < Y_{(2)}, X_{(2)} < Y_{(3)},.., X_{(k)} < Y_{(m)}\right) $ need to be evaluated. How else can this be solved for a variable k?
Comment: Yes, it is possible. Direct substitution just works: `Probability[
 x[1] < y[2] &&
  x[2] < y[3], {Distributed[{x[1], x[2]},
   OrderDistribution[{UniformDistribution[], n}, {1, 2}]],
  Distributed[{y[2], y[3]},
   OrderDistribution[{UniformDistribution[], n}, {2, 3}]]}]`
Answer: One solution is to use joint distribution for two order statistics:
$$
   f_{X_{1:n}, X_{2:n}}\left(x_1, x_2\right) = n(n-1) \left(1-x_2\right)^{n-2} \left[ 0 < x_1 < x_2 <1\right]
$$
$$
   f_{Y_{2:n}, Y_{3:n}}\left(y_2, y_3\right) = n(n-1)(n-2) y_2 \left(1-y_3\right)^{n-3} \left[ 0 < y_2 < y_3 <1\right]
$$
To evaluate the probability use
$$ \begin{eqnarray}
    \Pr\left(X_{1:n}\lt Y_{2:n},X_{2:n}\lt Y_{3:n}\right) &=& \mathbb{E}\left( \Pr\left(X_{1:n}\lt Y_{2:n},X_{2:n}\lt Y_{3:n} \mid Y_{2:n},Y_{3:n}\right) \right) \\ &=& \mathbb{E}\left(  F_{X_{1:n},X_{2:n}}\left(Y_{2:n},Y_{3:n}\right)\right)
\end{eqnarray}
$$
The probability $F_{X_{1:n},X_{2:n}}(y_2,y_3)$ is computed as follows, assuming $0<y_2<y_3<1$
$$\begin{eqnarray}
   F_{X_{1:n},X_{2:n}}(y_2,y_3) &=& n(n-1) \int_0^{y_3} \mathrm{d}x_2 \int_{0}^{\min(y_2,x_1)} \mathrm{d}x_1 \cdot  \left(1-x_2\right)^{n-2} \\&=& 1 - \left(1-y_2\right)^{n} - n y_2 \left(1-y_3\right)^{n-1}
\end{eqnarray}$$
Now
$$
 \begin{eqnarray}
    \Pr\left(X_{1:n}\lt Y_{2:n},X_{2:n}\lt Y_{3:n}\right) &=&  1 - \mathbb{E}\left(  \left(1-Y_{2:n}\right)^{n} \right) - n \mathbb{E}\left( Y_{2:n} \left(1-Y_{3:n}\right)^{n-1}\right) \\
  &=& 1 - \mathbb{E}\left(  Y_{n-1:n}^{n} \right) - n \mathbb{E}\left( Y_{2:n} \left(1-Y_{3:n}\right)^{n-1}\right)
\end{eqnarray}
$$
The latter integral is easy to evaluate:
$$
\begin{eqnarray}
  n \mathbb{E}\left( Y_{2:n} \left(1-Y_{3:n}\right)^{n-1}\right) &=& \int_0^{1} \mathrm{d}y_3 \int_0^{y_3} \mathrm{d} y_2 \cdot n^2(n-1)(n-2) y_2^2 (1-y_3)^{2n-4}  \\
  &=& \frac{n^2 (n-1)(n-2)}{ \frac{1}{2} (2n)(2n-1)(2n-2)(2n-3)} \int_0^{1} \mathrm{d}y_3 \int_0^{y_3} f_{Z_{3:2n},Z_{4:2n}}\left(y_2,y_3\right) \\
  &=& \frac{n(n-2)}{2 (2n-1)(2n-3)}
\end{eqnarray}
$$
The remaining integral is evaluated using singe statistics density function:
$$
  \mathbb{E}\left(  Y_{n-1:n}^{n} \right) = \int_0^1 x^n \cdot n(n-1) x^{n-2} (1-x) \mathrm{d} x = \frac{n(n-1)}{2n(2n-1)} \int_0^1 f_{Y_{2n-1:2n}}(x) \mathrm{d}x =  \frac{n-1}{2(2n-1)}
$$
Thus
$$
   \Pr\left(X_{1:n}\lt Y_{2:n},X_{2:n}\lt Y_{3:n}\right) = 1-\frac{n-1}{2(2n-1)}-\frac{n(n-2)}{2 (2n-1)(2n-3)}=\frac{(5n-4)(n-1)-1}{2(2n-1)(2n-3)}
$$
Comment: @AIB Yes, it reads $$f_{X_{1:n},X_{2:n},\ldots,X_{k:n}}\left(x_1,x_2,\ldots,x_k\right)  = \frac{n!}{(n-k)!} (1-x_k)^{n-k} [ 0<x_1<x_2<\ldots<x_k<1] $$ It is easily obtained as a marginal density of the complete order statistics pdf: $$f_{X_{1:n},X_{2:n},\ldots,X_{n:n}}\left(x_1,x_2,\ldots,x_n\right) = n! [ 0 < x_1 < x_2 < \cdots < x_n < 1] $$ There are some good books on order statistics, like [this](http://www.amazon.com/Order-Statistics-Wiley-Series-Probability/dp/0471389269) and [that](http://www.amazon.com/Course-Statistics-Classics-Applied-Mathematics/dp/0898716489).
Comment: Thanks a ton!! One more thing, is there a general formula for the joint distribution of k order statistics i.e. $f_{X_{1:n}, X_{2:n} ...X_{k:n}}\left(x_1, x_2, ..., x_k\right)$ , for uniform density?
Comment: Is there an expression for the CDF? I checked in the second book, but couldn't find any. Is it possible to use Mathematica to arrive at the answer(CDF), by integrating the pdf?
Comment: @AIB Do you mean the cdf of all order statistics, i.e. $$\Pr\left(X_{1:n} \leqslant x_1, X_{2:n} \leqslant x_2, \ldots, X_{n:n} \leqslant x_n \right)$$ There is an expression for it in terms of multiple sum that involves products of $F_X$ Look at the page 18 of the first book for the logic of deriving it.
Comment: Actually, I meant $\Pr\left(X_{1:n} \leqslant x_1, X_{2:n} \leqslant x_2, \ldots, X_{k:n} \leqslant x_k \right)$. This (marginal), I think, can be obtained by setting $x_{k+1}=1,x_{k+2}=1,...x_n=1$ in the cdf of all order statistics. Meanwhile, I am trying to a get a copy of the book from our library.
Comment: got a copy from library and got the CDF


Is there a way to conditionally change the state of a collapsible field group in admin, ie without changing a template or module file?

Question: I want to move the Metatags, keywords and edit summary into collapsible field groups at the top of the node edit page, but keep it open the first time the node is created, but collapsed in subsequent edits.
Can some CSS or Javascript be used to accomplish that? I don't want to do it in the file system code, whether are module or a template file.. I'd prefer something using the Admin even if it means applying some PHP there. If a module like the Context module can be used to test whether it is a newly created record and change some settings that will be fine.
Answer: If you want it to be open on page creation, you can target the page using the node-add-CONTENTTYPE class on the body. Using some jQuery in document ready you can set it open.
Something like:
jQuery('body.page-node-add-<YOUR-CONTENT-TYPE> fieldset.#YOUR-ID-HERE').removeClass('collapsed').children('.fieldset-wrapper').show();

Comment: all though your suggestion resembles gigabates version it didn't work. I used code per node module to apply it. Is it an exact answer or a pointer to a solution?
Comment: A pointer but you should only need to identify the machine name of the content type and the fieldset's ID (unless metatag module has different HTML structure).

Gigabates solution is convoluted for something so simple. It wouldn't be nice from a maintenance perspective. For example, you don't need to use drupal behaviors unless it's an ajax form.
Answer: Not sure what you mean by applying PHP 'in the Admin' but you could add a hook to template.php in your admin theme.
function mytheme_form_node_form_alter(&$form) {
  if (!$form['nid']['#value']) {
    $form['myfieldset']['#collapsed'] = FALSE;
  }
}

If you'd rather go with a JS solution the following should work.
(function ($){
  Drupal.behaviors.dynamicCollapsedFieldset = {
    attach: function (context, settings) {
      $('.page-node-add #myfieldset').once('dynamic-collapsed-fieldset').removeClass('collapsed');
    }
  }
}(jQuery));

You'd need to attach the JS in a file either in a module (which you said you want to avoid) or in your admin theme's .info file.
Unless you're using a custom admin theme I'd strongly advise against hacking core / contrib to implement either method. Either create a subtheme or a small module for this.
Edit:
Here's a version checking for a fieldset prefix
function mytheme_form_node_form_alter(&$form) {
  if (!$form['nid']['#value']) {
    foreach ($form as $key => $value) {
      if (strpos($key, 'group_metatags_') === 0) {
        $form[$key]['#collapsed'] = FALSE;
      }
    }
  }
}

Comment: I've added an example of this to my solution.
Comment: I named the field group `group metatags' but field group names can't be shared across content types. Is there some kind of regex match I could use to locate the metatags field groups on all content types if they were named 'group_metatags_xxxx'


IntelliJ is showing print Output wrong

Question: When I try to print a triangle "/\" in Java using IntelliJ, I encounter a problem that the console is not showing what I want, instead it underlines the triangle as if it were a link. I am told that this is a problem on IntelliJ's behalf but I don't know how to print it normal without the underlined "linked" stuff.
<code>public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("/\\");

    }
}
</code>
Answer: It's a known issue in IntelliJ IDEA. It provides hyperlinks to the files where it shouldn't. The link/URL is causing the underline.
As a workaround, you can disable the Groovy plug-in and restart the IDE.
Another workaround would be to disable the Underscored effect for hyperlinks at Settings (Preferences on macOS) | Editor | Color Scheme | General | Hyperlinks.

IntelliJ is showing print Output wrong


Philosophy of a Mathematician.

Question: Introduction
I don't study Mathematics at university, and probably I don't have any chances to have a little understanding of what mathematics in all its aspects.
But I love to find structures and links betwen ideas, and to ask myself philosophical questions about foundations of mathematics .If I have understood well is what is happening with the "categorical" point of view: there is some kind of "great unification" of the mathematics from a structural point of view.
Obviously I understand that for humans it is impossible to reach a total understanding of something, and that moves me is a mirage. I must give up until I'm sane and study modestly mathematics, in a relaxed way: playing with my easy problems, reading books, and learning from the basics all I can, without eccesive expectations maybe.
More I understand and more new interesting mathematical topics I discover... but the facts that overwhelm me are the acceleration of this process and the fact that there are a lot of young theories; and that this implies that this growth will be even faster.
Probably I, as an amateur mathematician, don't have a chance to come at new ideas in the foundational research (or even understand the actual point of view since it is changing so fast)...

Questions

$\mathcal Q_1$ From your($*^1$) experience how can mathematicians deal (or how they usually chose to behave) with this huge mathematical universe and be satisfied from a philosophical($*^2$)  point of view?
$\mathcal Q_2$ How can a mathematician interested in the foundations of mathematics be satisfied by an always partial knowledge of the mathematics?

Personal observation and conclusion
Is maybe possible that in 100 years tha amount of mathematical knowledge will be so huge that even Mathematicians will be totally overwhelmed from it? In other words, is possible that will be impossible for anyone to research new things because the knowledge required will take like 80 or 90 years of hard study? I say this because I think that humans has a limit to the speed of learning.
If this is possible,  is in the destiny of mathematicians to abandon the hope of understanding of mathematics?
I remember a quote of John von Neumann:

"Young man, in mathematics you don't understand things. You just get used to them."

I have read many stories about his math skills, and how he was a genius... anyways from my point of view... I feel very sad when I read this quote.

Notes
($*^1$) I ask this question HERE on SEMath because I'm looking for human experiences of real mathematicians, that is very important for me in this moment, and I do not think is fair that this question was closed in 40 seconds...is a soft question, as many others questions, but it has philosophical contenents too and I think it deserves at least a chance.
I must quote Andres Caicedo that was able to express way better than me, maybe, the meaning of my question:

"I think that there may be insights that only working mathematicians
  could provide (as opposed to philosophers), and even if there are
  wildly differing points of view, seeing them described may be useful.
  [...] Of course, it may be that answering the question in detail,
  considering as many of its subtleties as possible would just be too
  long and unfeasible. That's fine; even providing a few references and
  ideas that can potentially be fleshed out would be more useful that
  simply dismissing it."

Improved version 05/14/'13:
($*^2$) Following the advice of Gustavo Bandeira I explain better the meaning of "satisfied from a philosophical point of view" in my fisrt question; What I mean is only linked to the mathematicians interested in the foundations, in other words who is interested in that process of generalization of all the mathematics to easier concepts ( like "$\in$" for set theorists or the structuralists for example)
Here the same question on Phylosphy.SE

How can a mathematician interested in the foundation of mathematics
  be satisfied by an always partial knowledge of the mathematics?
Comment: How can [insert any academician] be satisfied by an always partial knowledge of [insert any academic area]?
Comment: $\large 1.$ I don't believe there is an answer to "what makes you satsified?" - We somehow look at that and we think that is beautiful, but there are plenty of *answers* to such questions based on free association.| $\large 2.$ What do you mean with *philosophical point of view*?| $\large 3.$ Mathematics is already huge, [I posted a quote from Sawyer in the chat some months ago](http://chat.stackexchange.com/transcript/36?m=6016840#6016840).| $\large 4.$ In the future, we will work as we always did: Get the big stuff, divide the work for thousands of people.
Comment: This doesn't look to me like a "practical, answerable question" and I'm not sure if even an entire book could answer this question...
Comment: Anyway, as far as $Q_2$ goes, you don't need full knowledge of something for it to be useful. Think of physics, for example (which IMHO has worse chances to reach "full knowledge", whatever that could be).
Comment: http://meta.math.stackexchange.com/a/9437/462
Comment: @ArthurFischer The question is about foundations of mathematics...that has something to do with the questions like, what is the mathematics. Am I wrong?
Comment: @A.P. really I don't undesrtand who this question is different from What is the purpose of mathematics, what is the purpose of a mathematicians or something like that. I believe that my question is about the philosophy of a mathematician that works in foundation.
Comment: @A.P. I' searching for human experience of real mathematicians, that is very important for me in this moment, and I do not think is fair that this question was closed in 40 seconds...is a soft question, as many others questions, but it has philosophical contenents too and I think it deserves at least a chance.
Comment: @GustavoBandeira I find your quote very "on topic" and closely related to my question, why don't you port your comment as an answer? I must qoute Andres Caicedo that was able, maybe, to express way better than me the meaning of my question: "[...] Of course, it may be that answering the question in detail, considering as many of its subtleties as possible would just be too long and unfeasible. That's fine; even providing a few references and ideas that can potentially be fleshed out would be more useful that simply dismissing it."
Answer: I'm a student of mathematics at the third year undergraduate level.
Lets begin with what's unsatisfying. Example are when:

you perceive that a branch of math "isn't set up right", or
a theorem is clumsily worded or clumsily proved, possibly because the writer hasn't had enough exposure to adjacent fields, or
an author's definition is suboptimal for ease of expression, or
terminology/notation in the literature is inconsistent and there seems to no way to fix the problem - its like you can't win,

etc.
On the other hand, the existence of a huge mathematical universe is not unsatisfying. It's wondrous. I love the fact that there's always more to explore, always harder problems to face...  in fact, at any level of difficulty, there's always progress to be made - its like a video game set in an enormously massive world that is just full of secrets, and it just stretches forever.
It can become pretty addictive. I'll leave you with the following quote.

Yeah, I used to think it was just recreational... then I started doin'
  it during the week... you know, simple stuff: differentiation,
  kinematics. Then I got into integration by parts... I started doin' it
  every night: path integrals, holomorphic functions. Now I'm on
  diophantine equations and sinking deeper into transfinite analysis.
  Don't let them tell you it's just recreational.
Fortunately, I can quit any time I want.
Answer: @MphLee - May I add some new comments ?
You speak of math as human experience  : this is a good point to start with. You quote also von Neumann statement's: it looks a little bit "wittgensteinian".
Try to link them; math is a game where you play with simbols, prove theorems, explore new concepts... If you live inside the math community (if you play the math game) you know well how it works.

What is the "sense" of this human activity or experience ?

You can find the answer in the field of philosophy, where you can find reflections on other human experiences : art, religion, ... Are we satisfied with available answers to this kind of reflections and questions ? I don't think so.
But math is also part of a bigger human activity: science. With "science game" we were able to build rockets and travel to the moon, to bulid atomic bomb (alas !), to calculate the earth's circumference a lot of time before Columbus (ignoring ancient Greek's calculation and using a wrong estimate) discovered the Americas.
Again, we can ask ourself what is the "sense" of science as human experience, but we may not ignore the fact that science (with the central role played in it by mathematics) is a "big game".
Both "games" grows with an impressive rate and you are right : how can I understand a field of knowledge like mathematics (or physics) if I'm not able to "manage" the total amount of mathematical knowledge ?
Comment: Certo che puoi! Thanks for the comment. I need time to think about your answer.

Philosophy of a Mathematician.


Prove that the affine transformation $f$ has at least one fixed point,

Question: If $f:X \rightarrow\ X$ is an bijective affine transformation of finite order ( an affine automorphism of finite order) in the group of affine automorphisms of $X$, prove that $f$ has at least one fixed point.
I supposed that for every $x \in X$, $f(x)\neq x$, so $F_{f}=\{M\in X:f(M)=M\}$ has the property $F_{f}=\emptyset$. $F_{f}=ker(f`-id_{\vec{x}})$, so because it is null, $f`(x) \neq id_{\vec{x}}$, but I don`t know how to prove what I am required. Any help, please?
Comment: The centroid of an orbit?
Comment: Please develop it. I sincerely don`t know.
Comment: I am in the first year of university.
Answer: Let $p$ be the order of $f$ and $x\in X$, write $y={1\over p}(x+f(x)+..+f^{p-1}(x))$, $f(y)=y$.
Comment: Please develop it a little, I quite don`t catch it.


Derivation of Riemann Explicit formula from Von Mangoldt formula

Question: To drive Riemann explicit formula for counting of primes $$J(x)=li(x)-\sum_{ρ}li(x^ρ )-log(2)+\int_x^∞\frac{dt}{t(t^2-1)  log(t) }\qquad (1)$$
One can start from Von Mangoldt formula  $$ψ(x)=x -\sum_{ρ}\frac{x^ρ}{ρ}-\frac{1}{2}log(1-\frac{1}{x^2})-log(2π) \qquad (2)  $$
knowing that $dψ=log(x) dJ$ we can find J'(x) as
$$J'(x) =\frac{dJ(x)}{dx}=\frac{1}{log(x)}\frac{dψ}{dx}$$
$$J'(x)=\frac{1}{log(x)}-\frac{1}{log(x)}\sum_{ρ}x^{ρ-1}-\frac{1}{x(x^2-1)  log(x) }$$
And now integrating from 0 to x we get
$$J(x)=\int_0^x\frac{dt}{log(t)}-\sum_{ρ}\int_0^x\frac{t^{ρ-1}}{log(t)}dt-\int_0^x\frac{dt}{t(t^2-1)  log(t) }$$
which yields
$$J(x)=li(x)-\sum_{ρ}li(x^ρ )-\int_0^x\frac{dt}{t(t^2-1)  log(t) }\qquad (3)$$
And now comparing eq (3) to eq (1)  we see that the first two terms match fine but not the third one! What did go wrong in the derivation?
Comment: The function $\frac{1}{{t(t^2  - 1)\log t}}$ has a non-integrable singularity at $t=1$. The integral from $0$ to $x>1$ does not exist, even if you consider the Cauchy principal value.
Comment: But Gary, how do you proceed then from J'(x) to obtain J(x)?
Answer: According to the definitions, $J(x)$ and $\psi(x)$ satisfies the following identies:
$$
J(x)=\sum_{p^k\le x}\frac1k=\sum_{p^k\le x}{\log p\over\log p^k}
=\sum_{1.5<n\le x}{\Lambda(n)\over\log n} \\
\psi(x)=\sum_{p^k\le x}\log p=\sum_{n\le x}\Lambda(n)
$$
where $\Lambda(n)=[n=p^k]\log p$ is von Mangolt function. Now, using Abel's summation formula, we have
$$
\begin{aligned}
J(x)
&=\left.\psi(t)\over\log t\right|_{1.5}^x-\int_{1.5}^x\psi(t)\mathrm d\left(1\over\log t\right) \\
&={\psi(x)\over\log x}-{\psi(1.5)\over\log(1.5)}+\int_{1.5}^x{\psi(t)\over t\log^2t}
\end{aligned}
$$
Since $\psi(x)\equiv0$ for all $x<2$, we can simplify this into
$$
J(x)={\psi(x)\over\log x}+\int_2^x{\psi(x)\over t\log^2t}\mathrm dt
$$
Now, plugging the explicit formula for $\psi(x)$ sh


Non RBAC User Roles and Permissions System: checking the user's City

Question: We are currently designing a User Roles and Permissions System in our web application (ASP.NET), and it seems that we have several cases that do no fit within the classical Role-Based Access Control (RBAC). I will post several questions, each devoted to a particular case, this being the first post.
We have the following case: not to allow a user view a certain page if the user lives in a particular city. This is a simple case that is coded in the following way:

if (User.City == "Moscow")
// Allow the user to view the page.
else
// Do not allow the user to view this page.

Though this case is very simple and straightforward, it has nothing to do with the RBAC.
On StackOverflow, someone called this an Attribute-based Access Control.
Under the classical RBAC, it seems that this case should be designed like this: introduce a permission "City where the person lives", this permission will have a property City. Then create a role, add a permission of type "City = Moscow" to it and the assign the role to the user. Looks extremely cumbersome.
The question is whether it is acceptable to introduce such non-RBAC approaches to our permissions system – does that break the design or not?
This might seem a primitive question, but we found that most applications use pure RBAC, and we started to think that we might be doing something wrong.
Thank you.
Comment: See my answer to your other question - the issues are the same. I am voting to close this as a dupe of http://stackoverflow.com/questions/2839819/non-rbac-user-roles-and-permissions-system-a-role-with-properties. No offense intended.
Comment: possible duplicate of [Non RBAC User Roles and Permissions System: a role with properties](http://stackoverflow.com/questions/2839819/non-rbac-user-roles-and-permissions-system-a-role-with-properties)
Answer: This would be a nice case for an atribute based access control. However, if you don't mind looking at a PHP implementation, Zend Framework has a role based access control that uses assertions to solve more special cases:
http://framework.zend.com/manual/en/zend.acl.advanced.html
A standard rule would allow a role to do an action on a resource. A fourth parameter allows the rule only to apply when some condition is met. In pseudocode:
allow(member, view, page) // standard
allow(member, view, page, userLivesInMoscow) // assertion used

The assertion is an object that is passed the user. It has a method that checks whether the assertion is met:
interface Assertion
 bool public function assert()

class UserLivesIn implements Assertion
 public function UserLivesIn(User, City) ...
 // implementation of assert method comes here

This is a way of implementing what you need.
Comment: @code poet I don't suggest solving it in another environment. I'm only pointing to an example solution in another environment that can be used as inspiration to port to the current environment. 'Looking at' != 'implementing with'.
Comment: uh... if you were working in a Linux,PHP environment and had a problem and someone suggested that perhaps it would be easier to solve in an ASP.Net/C#/Windows environment, what would your impression be?
Comment: ok, point taken. note: no downvote. But the reality of the situation is that the ASP.Net membership/roles infrastructure does not lend itself to this type of extension and consideration there of would require redesign, reimplementation of the entire security infrastructure.


Melhores práticas ao apresentar tela de loading em Android

Question: A abordagem mais conhecida e difundida para  mostrar ao usuário que uma requisição à rede está acontecendo e fazê-lo aguardar até o fim desta, tem sido por meio do uso do componente ProgressDialog. O componente é criado no início da requisição e fechado ao final. Isto pode ser conseguido, por exemplo, utilizando uma AsyncTask.
Utilizando a abordagem descrita teríamos no método onPreExecute() de nossa AsyncTask algo como:
protected void onPreExecute() {
     dialog = new ProgressDialog(context);
     dialog.setTitle("Realizando o carregamento dos dados");
     dialog.setMessage("Aguarde o fim da requisição...");
     dialog.show();
}

E ao fim da requisição, no onPosExecute() da AsyncTask:
protected void onPostExecute(String retorno) {
    Activity activity = (Activity) context;
    TextView dados = (TextView) activity.findViewById(R.id.dados);
    dados.setText("Dados: " + retorno);
    dialog.dismiss();//Fecha o dialog após o fim da requisição
}

O produto do uso do ProgressDialog seria algo como:

Embora bastante usada esta abordagem parece que se tornou uma má prática no que diz respeito a usabilidade e aparece entre os 10 piores itens que afetam a experiência do usuário.
Diante disso, pergunto: qual a melhor forma de mostrar ao usuário que uma requisição está ocorrendo? Como adaptar o código abaixo de modo a fazê-lo se adaptar as novas exigências de usabilidade?
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button botao = (Button) findViewById(R.id.botao);
        botao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Task(v.getContext()).execute();
            }
        });
    }

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

        private ProgressDialog dialog;
        private Context context;

        public Task(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(context);
            dialog.setTitle("Realizando o carregamento dos dados");
            dialog.setMessage("Aguarde o fim da requisição...");
            dialog.show();
        }

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

            String urlServico = "http://echo.jsontest.com/key/value/one/two";

            try {
                URL url = new URL(urlServico);
                HttpURLConnection http = (HttpURLConnection) url.openConnection();
                InputStream stream = http.getInputStream();

                Reader reader = new InputStreamReader(stream, "UTF-8");
                char[] buffer = new char[1024];
                reader.read(buffer);
                return new String(buffer);

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return "";
        }

        @Override
        protected void onPostExecute(String retorno) {
            Activity activity = (Activity) context;
            TextView dados = (TextView) activity.findViewById(R.id.dados);
            dados.setText("Dados: " + retorno);
            dialog.dismiss();
        }
    }
}

Comment: Depende de onde você despoleta a ação: se for um botão o *Progress* pode aparecer no próprio botão, se for na *ActionBar* a mesma coisa, ao preencher uma lista pode aparecer na lista, etc.
Comment: Olá, @ramaral. Como eu faria para usar este abordagem que você destacou? Existe alguma propriedade ou método nesses componentes descritos que permita a apresentação do Progress?
Comment: Veja [isto](https://guides.codepath.com/android/Handling-ProgressBars) e [isto](http://www.vogella.com/tutorials/AndroidActionBar/article.html#actionbar_actionview)
Answer: A sua pergunta já foi muito bem respondida pelo colega @ramaral. E, aliás, o ponto principal da resposta do colega é esse:

Qualquer que seja a forma escolhida ela deve garantir que não bloqueia
  a tela e, se possível, permita ao utilizador sair da aplicação e
  voltar mais tarde para aceder ao resultado da requisição.

Mas como você usou as tags usabilidade e ux, eu achei que dava pra explorar mais o assunto. Assim, eu só estou respondendo porque acho que posso colaborar adicionando algumas informações e cenários para enfatizar a colocação acima do colega. Aliás, eu não vou oferecer exemplos de código simplesmente porque a sua pergunta não vale apenas para Android, mas para qualquer plataforma, e porque esse não é o foco da minha resposta.

Usabilidade na Indicação de Progresso
Exclusivamente sob o ponto de vista da usabilidade - em que se deseja que o produto seja "usável" (dai o nome "usabilidade"), isto é, fácil de utilizar, entender, aprender, memorizar, etc - o uso de telas de progresso é especialmente necessário para transmitir a informação de que o sistema não está inoperante. Em outras palavras, algo importante está sendo realizado e por isso o usuário deve aguardar. A palavra "importante" está destacada porque essa importância é relativa ao usuário: a tarefa é importante para ele, de forma que ele está disposto a aguardar seu encerramento. Um exemplo bem simples é de um aplicativo de modelagem 3D em que o artista criou todo um cenário e então solicita a renderização da imagem ou vídeo com as animações. Essa tarefa leva tempo, o usuário está ciente disso no processo de uso do aplicativo, e aguardará o tempo necessário dentro dos limites óbvios de algo factível. Mas o aplicativo precisa demonstrar que está fazendo tal tarefa.
Uma indicação óbvia de que o processo está fazendo algo é uma animação simples. Com o uso do sistema o usuário aprende que enquanto aquela animação está em execução o sistema não está simplesmente "travado", e sim fazendo a tarefa que foi solicitada. Hoje em dia usa-se esse disco circular que você cita na pergunta, mas mesmo no passado - em que sistemas eram desenvolvidos apenas em interface textual - utilizava-se animações com a adição de pontos ou com a alternância de caracteres como esses:

Além dessa indicação visual de que o processo está em execução, idealmente deve-se também fornecer duas informações adicionais para melhorar a usabilidade: uma estimativa de conclusão e a opção de cancelar o processo. Essas informações são importantes para que o usuário não apenas tenha informações sobre aquela tarefa que lhe é importante (critério importante de usabilidade chamado feedback), mas também para que se sinta confiante e seguro no controle da interação (outros critérios importantes da usabilidade são a segurança e a recuperação de erros).
A estimativa de conclusão pode ser oferecida na forma de um percentual (quanto já foi realizado x quanto falta realizar) ou na forma de tempo (quantos segundos/minutos/horas/dias/semanas/etc faltam para terminar), e a escolha depende do domínio do problema e dos dados para cálculo estarem disponíveis (número de itens a processar). Mas em geral (e quando possível) usa-se as duas. Um exemplo clássico é uma ferramenta de download por Torrents. Mais informações sobre o cálculo dessas estimativas podem ser obtidas nesta outra pergunta.
A opção de cancelar é importante principalmente em tarefas iniciadas pelo usuário porque permite que ele se recupere de erros. No exemplo do artista 3D renderizando uma cena, no caso de ele perceber que faltou ajustar algum objeto na cena ele pode cancelar o processamento para fazer tal ajuste a qualquer momento, e não precisa esperar até o final do processamento para essa ação.
Mas mesmo em tarefas que não são iniciadas pelo usuário, tanto o feedback de progresso como a opção de cancelamento são importantes para garantir uma utilização mais prazerosa (diferentemente de usabilidade, aqui já se começa a pensar mais na experiência do usuário, ou ux).
Experiência na Indicação de Progresso
Quando eu disse que o ponto chave da resposta do colega @ramaral era que deve sempre ser possível ao utilizador sair da aplicação e voltar mais tarde, era principalmente pelo aspecto da Experiência. O seu sistema computacional (seja ele em utilizado no Android, no iOS, na Web, no PlayStation 4, na SmartTV, não importa) é um produto. E nada é mais desgastante para o usuário do que um produto que não permite ser utilizado como desejado.
O usuário tende a ser mais paciente com tarefas que ele solicitou ("estou disposto a aguardar por esse download que eu pedi") do que com tarefas que o seu sistema "acha" que precisa ser realizada. Eis um cenário muito real:

Ned Stark gosta muito de assistir episódios de séries no Netflix
  durante seu horário de almoço. Como ele trabalha de casa, o horário de
  almoço é aquele momento de relaxamento importante pra ele (que mantém
  sua cabeça no lugar, digamos). Certo dia, ele preparou seu almoço, sua
  bebida, e se sentou confortavelmente no sofá ansioso por aquele novo
  episódio de House of Cards. Então, ligou sua SmartTV e abriu o
  aplicativo do Netflix, que então exibiu a mensagem: "Há uma
  atualização que PRECISA ser realizada agora. Por favor guarde.". Sem
  opção de cancelamento, o aplicativo levou 40 minutos para ser
  atualizado via Internet.

Certamente o usuário desse cenário bem real ficou muito desapontado com o produto. A razão é bem simples: o produto parece saber mais do que ele, tirou completamente o controle dele sobre quando seria o melhor momento para fazer uma tarefa (atualização) que ele sequer solicitou. Pode ser algo importante, mas não para ele.
Apesar do comicidade nesse cenário, esse assunto é sério e muita gente se preocupa cada vez mais com isso em seus produtos (infelizmente não tantos como gostaríamos, ainda mais no Brasil - não sei em Portugal). Assim, o resumo prático é o seguinte:

Tarefas longas que são iniciadas pelo usuário tendem a ser mais bem recebidas. Mas ainda assim é importante oferecer opções de cancelamento, adiamento ou execução em pano de fundo. O usuário precisa se sentir no controle da interação, seja na consideração de que vai fazer outra coisa enquanto a tarefa é executada, ou na consideração sobre desistir de sua execução.
Tarefas longas que não são iniciadas pelo usuário devem ser realizadas com muito mais cuidado, de forma a reduzir o máximo possível o impacto em suas atividades. Se é algo que interrompe o serviço, deve ser realizada apenas com a anuência do usuário e deve lhe ser dada a opção de cancelar a qualquer momento. Dependendo da plataforma, útil oferecer mais de uma opção de execução ao usuário (por exemplo, para atualização pode ser feita via Internet ou via arquivo local em Pen-Drive, baixado de outro dispositivo).
Sempre que possível, deve-se oferecer estimativas sobre o que já foi realizado e o que falta realizar. Essa informação é fundamental para o usuário se sentir no controle e decidir sobre esperar ou não, fazer outra coisa enquanto ou cancelar, etc. O uso de uma animação simples (sem informação de andamento e/ou estimativa de completude) é mais aceitável em tarefas solicitadas pelo usuário e cuja duração seja curta (refresh de tela, por exemplo).
É muito útil avaliar o uso da sua aplicação com seus usuários, tanto em protótipos durante a fase de desenvolvimento como com a aplicação real durante a fase de uso. Deve-se ficar atento a qualquer comentário ruim em relação a uma interação desse tipo, pois ele pode apontar um problema maior quando experienciado por mais usuários.
Comment: Muito boa resposta.
Answer: Depende de onde/como você despoleta a requisição: se for um botão o ProgressBar pode aparecer no próprio botão, se for na ActionBar a mesma coisa, ao preencher uma lista pode aparecer na lista, etc.
Qualquer que seja a forma escolhida ela deve garantir que não bloqueia a tela e, se possível, permita ao utilizador sair da aplicação e voltar mais tarde para aceder ao resultado da requisição.

Exemplo em que o ProgressBar aparece no botão.
Crie um layout com um Buttom e um ProgressBar
progress_buttom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/progressBarLayout">

    <Button
        android:id="@+id/progressButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/progressButton"
        android:layout_alignRight="@id/progressButton"
        android:visibility="invisible"/>

</RelativeLayout>

Substitua o seu botão, no xml da Activity, por este layout, da seguinte forma:
<include layout="@layout/progress_button"/>

O seu código ficaria assim:
public class MainActivity extends Activity {

    private final ProgressBar progressBar;
    private TextView dados;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button botao = (Button) findViewById(R.id.progressButton);
        progressBar = (ProgressBar)findViewById(R.id.progressBar);
        dados = (TextView)findViewById(R.id.dados);

        botao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Task().execute();
            }
        });
    }

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

        @Override
        protected void onPreExecute() {
            progressBar.setVisibility(View.VISIBLE);
        }

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

            String urlServico = "http://echo.jsontest.com/key/value/one/two";

            try {
                URL url = new URL(urlServico);
                HttpURLConnection http = (HttpURLConnection) url.openConnection();
                InputStream stream = http.getInputStream();

                Reader reader = new InputStreamReader(stream, "UTF-8");
                char[] buffer = new char[1024];
                reader.read(buffer);
                return new String(buffer);

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return "";
        }

        @Override
        protected void onPostExecute(String retorno) {
            dados.setText("Dados: " + retorno);
            progressBar.setVisibility(View.INVISIBLE);
        }
    }
}

Exemplos das outra formas que citei podem ser encontradas aqui e aqui.
Comment: Olá, Ramaral. A solução funcionou perfeitamente. Uma última questão: a prática adequada ou recomendada quando o usuário realiza uma requisição é então não "bloquear" a tela e permitir que o usuário utilize o app normalmente, é isso? Você pode incluir isso em sua resposta?
Comment: Editei a resposta.


How to get Database names from given Sql Server in LINQ

Question: I have DropDownList displays all server present in my network
I want to populate the databse names when i changed it into another dropdown
I want a LINQ query to get this.
Comment: Why do you want a LINQ query for this? Not everything is a nail you know?
Answer: See the question here on how to get the list of databases available to the logged-in user:
SELECT name
FROM sys.sysdatabases
WHERE HAS_DBACCESS(name) = 1

Implementing this into LINQ requires you to publish the sysdatabases view into your own view. I would recommend creating a view for the job in one of the databases:
CREATE VIEW [dbo].[vewDatabases]
AS
SELECT  name
FROM    sys.sysdatabases
WHERE   HAS_DBACCESS(name) = 1

GO

Add this to your LINQ data model, and you will be able to select from it like so [c#]:
var databaseNames = serverDataContext.vewDatabases.Select(a => a.name);

You can then populate the DropDownList with the contents of databaseNames.
Answer: I don't think this is a job for Linq2SQL (though I'm not overly familiar with it).
Basically, I think you can get the results you want by looking at one of the SYS_ tables, or a SP_ stored procedure. Can't remember which - been a while since I did anything with SQL Server.
Answer: Try code below:
    protected void ddList_SelectedIndexChanged(object sender, EventArgs e)
    {
        PopulateDatabaseDropDown(ddList.SelectedItem.Text);
    }
    private void PopulateDatabaseDropDown(string server)
    {
        ddDatabase.DataSource = DatabaseName(server);
        ddDatabase.DataValueField = "DatabaseId";
        ddDatabase.DataTextField = "Name";
        ddDatabase.DataBind();
    }
    private DataBase[] DatabaseName(string serverName)
    {
        List<DataBase> data = new List<DataBase>();
        System.Data.Linq.DataContext db = new System.Data.Linq.DataContext("Data Source="+serverName+";Initial Catalog=master;Integrated Security=SSPI");
       var dbName = db.ExecuteQuery<DataBase>("select database_id, [name] from sys.databases").AsEnumerable();
       foreach (var item in dbName)
           data.Add(new DataBase() { DatabaseId = item.DatabaseId, Name = item.Name });
       return data.ToArray();
    }
}
public class DataBase
{
    public string Name { get; set; }
    public int DatabaseId { get; set; }
}


"Failed to initialize PAL." while upgrading an LSI 9211-8i to IT?

Question: When attempting to flash my LSI SAS 9211-8i card on my ASUS H87I-PLUS LGA 1150 Intel H87 Mini ITX Motherboard, I was able to get through all of the instructions until I was finally ready to flash, using SAS2FLSH.exe. The error reported was:
ERROR: Failed to initialize PAL. Exiting program.
What would cause this?
Answer: Hit my head against the wall (a lot) on this. For me, solved it by:

Formatting the USB as freedos (using Rufus) - https://www.all4os.com/windows/create-a-bootable-ms-dos-or-freedos-usb-drive.html
Downloading the Shell_full.efi, renaming to shellx64.efi, and putting it on the root of the drive - https://svn.code.sf.net/p/edk2/code/trunk/edk2/EdkShellBinPkg/FullShell/X64/Shell_Full.efi
Downloading the sas2flash.efi - http://www.lsi.com/products/host-bus-adapters/pages/lsi-sas-9211-8i.aspx#tab/tab4
Booting to the ASUS bios and loading EFI shell (it's the last step, in the last page on the advanced screen on the bottom of the page, same page as "Save and Reset"
Follow the rest of the instructions on this page (http://digitalcardboard.com/blog/2014/07/09/flashing-it-firmware-to-the-lsi-sas-9211-8i-hba-2014-efi-recipe/)
; to show the controller and verify the current version.
sas2flash.efi -listall

; to erase the BIOS, do not reboot after this command.
sas2flash.efi -o -e 6

; to write the new firmware and BIOS.
sas2flash.efi -o -f 2118it.bin -b mptsas2.rom

More instructions here to compare: http://brycv.com/blog/2012/flashing-it-firmware-to-lsi-sas9211-8i/
Comment: This is already mentioned in the blogs, but for anyone else... the USB drive doesn't need to be bootable with Freedos.  You should be able to open any FAT USB drive in the EFI shell.  Your guide saved me a lot of time - thank you so much!!
Comment: in case my edit doesn't get approved: updated links ([Shell_full.efi](https://github.com/tianocore/edk2/blob/8afe7c9ae565f3369b8fa46af70ccb7c2f05ce01/EdkShellBinPkg/FullShell/X64/Shell_Full.efi), [sas2flash.efi](https://www.broadcom.com/site-search?q=Installer%20for%20UEFI)) & where to place the Shell_Full.efi so it works on current supermicro boards (/efi/boot/bootx64.efi). also added [reason of error](https://www.broadcom.com/support/knowledgebase/1211161501344/flashing-firmware-and-bios-on-lsi-sas-hbas). also note that sas2flash.efi doesn't work with newer efi shells.
Comment: also note that you can [update the firmware from windows & linux](https://www.broadcom.com/support/knowledgebase/1211161501344/flashing-firmware-and-bios-on-lsi-sas-hbas) as well. just not cross-flash it from IR to IT (and vice-versa)
Answer: Update and to know the reason:
Reason:
i cite from http://brycv.com/blog/2012/flashing-it-firmware-to-lsi-sas9211-8i/ :
"I booted from the SD card and attempted to run sas2flsh but was met with an error: "ERROR: Failed to initialize PAL. Exiting program." Fortunately, article 16266 mentions the error at the end and directs you to article 15807. The gist of article 15807 is that Intel 3000 or 5000-based boards have optionROM limitations which cause the above error. The easiest solution is to use a different system. Alternately, you can use the UEFI installer."
Update:
The sas2flash.efi ist now available from Broadcom
The files on the LSI web page is no longer available. E.g. search for the file installer_p12_for_uefi.zip or using the Link.
Current Version: installer_p20_for_uefi.zip
Thanks to aronchick for the hint to sas2flash.efi !!
Answer: I ran into the exact same problem with updating the LSI SAS 9211-8i ("Failed to initialize PAL"), and found an unlikely solution: A firmware update was possible from within the MegaRAID Storage Manager running under Windows, there's a link "Update firmware" right on its dashboard.
Answer: Based off of aaronchik's answer and bernstein's comment, this appears to be down to version mismatches between binaries.
Though there's quite a lot of thorough guide's out there, it tends to be that the actually binaries and tools are distributed all over the place, and often assume your motherboard or bootloader give you access to a bundled EFI shell, etc.
Getting compatible binaries took me quite a few hours of work last night, so I've bundled up a project that combines a walkthrough as well as all of the resources needed to complete the whole process:
https://github.com/strazto/lsi-sas92xx-m1015-flash-firmware
Answer: After hours struggling with this error I was finally able to do it booting off a Windows 10 USB and went into Repair / Advanced / Commandline and was able to run the dos commands to update the card.


Creating content type using views

Question: I created a content type using views called Bars & Restaurants
I want that content type to show under my Bars & Restaurants menu link at the top of my page.
I have changed the path to http://localhost/drupal/barsandrestaurants
and the menu to: menu tab - navigation and it still only shows up on my home page.
Is there a way to display the content type only on my bars and restaurants page?
I want authenticated users to be able to go into the page and add bars and restaurants themselves.
I am very new to drupal so any help will be great!

I want the content that Im adding to be under the Bars & Restaurants page there
Comment: Actually, you cannot create a content type using the Views module. It's the Node module that allows you to create a content type.
Answer: Assuming what you want to do is :

Make a content type which authenticated user can add by themselves called barandrestaurant.
Make a view displaying all the barandrestaurant content-type.

First creat a new content type called barandrestaurant :

You should unchecked the "promote to front page" in the content type page :

Allow user to add your content type in admin/people/permission --> find your content type node name (barandrestaurant) and allow authenticated user to create new content.

Second make a view page filtering your content type barandrestaurant

Go to admin/structure/views/add a new view and fill the form to filter on your content type like that :
Specifiy that what you want is a view page and that you want to add a menu link in navigation menu :
Add in the header or in the footer (as you want) a "global text area" with a html link to create new barandrestaurant content type page :

Add a new bar or restaurant

This should look like this :

Now you should have a content type called barandrestaurant which can be created by your authenticated users visiting the link http://www.yoursite.com/bar-and-restaurant. The link should be in your navigation menu too.
Comment: Aporie has it mostly right. When creating the new content type called barandrestaurant you should untick all Available Menus.  The View would be in the menu, not the actual nodes.
Comment: Thank you for the answer.. However, I already have a basic page created called Bars & Restaurants. Is there a way to set the content of the view to be displayed only on that page? Or do I need to create a new page ? The Basic Page is one of my main pages beside Home so would like the content to be displayed only there.
Comment: I have edited my question and added a picture to explain it better
Comment: So that's actually very close to what I said. You have to have a view filtering on the content type bar&restaurant. Are you sure, that's only the content you are adding under bard&restaurant content type that you want to be displayed or every content user posted under bar&restaurant ?
Comment: Well I want users to be able to add restaurands and bars only on that page if you know what I mean? .. And where would I specify that I want the content to be saved on this page http://localhost/drupal/barsandrestaurants ?
Comment: OK I answer you tomorrow.
Comment: I modified my answer to fit your needs.
Comment: Pleasure, if you can validate that the answer is what you were expecting.

Creating content type using views


Como manipular tamanho de div sem utilizar hover

Question:
Edited -- Apesar de ter pedido exclusivamente em css, vi que de fato o resultado final em JS é muito mais profissional e enxuto. Sendo
  assim confirmei a resposta de @renan como a que auxiliou de fato.
  Contudo ressalto aqui que a resposta de @Fetz foi realmente a melhor
  saída para a utilização de CSS nesse caso. Entretanto o efeito final é
  feio, movendo a página inteira de lugar.

Minha dúvida é simples. Tenho usado muito o :hover no CSS e tem me servido até certo ponto.
Contudo tenho desejado uma coisa diferente. Queria poder clicar numa div para que ela aumentasse de tamanho, e que eu tivesse que clicar nela num canto específico para ela diminuir.
O hover faz parte do processo, mas quando tiro o mouse de cima da div ele volta ao tamanho anterior.
O que quero é que a div só mude quando eu clicar nela. E se possível ela só volte à forma original se eu clicar num X por exemplo ou fora da div em questão.
Já procurei muito, encontrei algumas coisas em JS, mas estou fazendo o possível para não utilizar JS nesse meu projeto. Então comecei a imaginar que com PHP isso seja possível. Ou alguma palavra chave de CSS pra colocar no stylesheet no lugar do hover.
Tem alguma palavra reservada para isso como por exemplo um possível onmouseclick da vida???
Grato antecipadamente.
#atredit{
    position:absolute;
    width: 150px;
    height: 75px;
    background-color: #F5F5F5;
    border: 1px solid #111111;
    border-radius: 5px;
    margin-top: 150px;
    margin-left: 200px;
    overflow: hidden;
    cursor:pointer;

}
#atredit:hover{
    width: 150px;
    height: 300px;
    transition: 0.5s ease-in-out;

}

Comment: O PHP não consegue mudar tamanhos de div pois ele não tem como modificar as configurações dela. Mas Jquery consegue perfeitamente solucionar o seu problema.
Comment: obrigado @gustavox
Comment: O Jquery é feito em javascript, só que mais polido. Melhor usar o jquery pois ele possui classes prontas para fazer o que você quer.
Comment: Hanzer, mesmo parecendo irrelevante neste caso, considere que incluir um trecho de código (apenas o trecho que quando vc tira o mouse de cima da div ele volta à forma original) vai aumentar muito uas chances de receber  respostas.
Comment: Editei meu comentário anterior pra constar o trecho que acho importante vc incluir.
Comment: Tem como, usando javascript.
Comment: Me tira uma dúvida @SamuelNeiva O Jquery tem relação com o JS? Seria mais interessante usar Jquery ou JS?
Answer: Você pode inserir uma classe responsável por aumentar o tamanho do div quando este for clicado, por exemplo, uma classe que expande o tamanho do div em 'x' pixels.
A forma como você vai fazer isso depende do suporte que você quer dar aos usuários (na verdade, ao navegador que eles utilizam). Existe a API classList mas o Internet Explorer ainda possui implementação parcial, como pode ver neste link. No entanto encontrei essa pergunta no StackOverflowen na qual existem formas de contornar esse "problema" no IE.
Um exemplo utilizando a API classList:

document.querySelector('div').addEventListener('click', function() {
  this.classList.toggle('ativa');
});
div {
  width: 200px;
  height: 100px;
  background: red
}
div.ativa {
  width: 400px
}

document.getElementById('foo').addEventListener('click', function() {
  this.classList.toggle('ativa');
});
#foo {
  width: 200px;
  height: 100px;
  background: red
}
#foo.ativa {
  width: 400px
}

Comment: @HanzerDjAlgonn colocou onde? No caso, o código teria que ser inserido depois do elemento HTML. Se você tentar chamar essa função antes (no head, por exemplo) não irá funcionar. Vale lembrar que não entra só a questão do Javascript mas do CSS também, editei minha resposta e criei um novo *snippet* pegando o div pelo id.
Comment: testei de várias formas. Funcionou agora. Eu salvei o código numa página fora do html .js. Coloquei a chamada do código acima da tag . Funcionou lindamente! Grato profundamente. Apesar de não ser somente css agradeço deveras o esforço! vlw
Comment: vlw @renan!

no caso isso é JS? De todo modo agradecido!
Comment: olá novamente @renan! Sendo JS como procedo para ao invés de usar div como no exemplo seu eu usar a id da div?
Comment: compreendo que provavelmente seja '#varid
Comment: `document.getElementById("id-div").addEventListener(...);` @HanzerDjAlgonn
Comment: Eu coloquei como a resposta escolhida por mim, mas ainda não consegui fazer funcionar. Por esse motivo retirei agora.

Eu n sei o que fazer. Entrou com JS eu fico perdido por que ainda não me aprofundei o suficiente e por isso eu insisti na pergunta pra obter uma opção fora JS. Eu coloquei o trecho do código document.getElem... na minha página html entre as tags script. Eu n sei se precisa de mais alguma coisa pra fazer funcionar, pois n tenho conhecimento suficiente em JS. Se puder dar mais uma força ficarei grato
Answer: Com css apenas podes fazer assim:
Se usares o pseudo selector target em vez do hover.
Para usares o target, precisas de ter um id (ex:
) no elemento que vai crescer e um link a apontar para o id do elemento que queres que cresca (ex: show) com o prefixo # (ex:)
html:
x

css:
#show img {
    height: 150px;
}

#show:target img {
    height: 300px;
}

exemplo a funcionar:
http://jsfiddle.net/zzsLb6g9/
Comment: [Concordo](http://pt.stackoverflow.com/a/40789/74).
Comment: uou!! Isso chegou muito perto!

Realmente aumentou e agradeço deveras! Contudo a página se moveu pra cima. Tem alguma âncora que eu possa colocar para resolver isso? Toda vez que a página for chamada essa âncora segurar em determinado ponto?
Comment: Essa reação de movimentar a página me desagrada deveras.
por isso, apesar de sua resposta ser a que mais se aproximou do que pedi aceitei a do brother acima por que o efeito final foi realmente melhor em JS. Contudo muito grato por me mostrar essa possibilidade.


git - Fetch file from remotes/origin/main to temp area (not a local branch)

Question: I want to be able to do my own compare on a binary file (*.DBF) under git with our own comparison tool using Powershell. That is because the file header can change without the content changing.
"git diff --binary --output=$tempfile $path" does not provide diffs which are useful for this task.
I found a few posts but they seem convoluted in using different branches. "git checkout xx" does not seem to have options to do this.
Is there a git syntax to achieve this?
If i can fetch to a temp area, then i can compare main to the local branch, and if no meaningful changes have occurred, then use "git checkout $path" to undo the changes. Thanks
Comment: Why not configure the program using `.gitattributes` to be the diff driver? See the docs: [1](https://git-scm.com/docs/gitattributes#_defining_an_external_diff_driver), [2](https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#_diffing_binary_files).
Answer: You can use the git show to extract the content of the file to stdout (and then send it where you want), so:
git show origin/main:path/to/file.dbf > temp.dbf

Comment: Thanks!, i will assume that binary files are "shown" unmodified no matter the file file format, ANSI etc.
Comment: I compared the checksum of a binary file on disk with the output from `git show` and it matches, so it seems safe.
Comment: My testing using an exe and a dbf file is i couldn't get a byte for byte copy. I tried using --encoding on the git show and various combinations of | out-File encoding's + -NoNewLine and -width to a large value (as well as the original '>' )
This works well enough to text files but not binary for me.
Notepad++ considers an exe to be DOS ANSI and a DBF as Macintosh ANSI.
Comment: Does `git cat-file -p` behave the same for you? Oddly enough, I'm seeing bit-for-bit copies for both `git show` and `git cat-file -p`, using images and compiled binaries as test cases, verified using `sha256sum` on the output.


Spring boot:Não foi possível localizar nem carregar a classe principal

Question: Faz pouco tempo que estou usando Spring.
Alterei o nome do pacote controller e a aplicação não quer mais rodar.

Na segunda imagem em vermelho sublinhado estava trajes.trajes o nome do pacote e alterei para trajes.controller.O que eu fiz de errado?
Answer: Achei o meu próprio erro,quando eu fui refatorar eu não renomeei corretamente.Eu dei rename directory e não rename package.O certo é rename package.
Answer: O problema está na classe TrajesApplication.
Você precisa movê-la para a pasta com\sistema\trajes\trajes
Veja que não existe mais esse pacote: com.sistema.trajes.trates, seu arquivo TrajesApplication estava lá, e você moveu para dentro do pacote Controller.
E é disso que o Intelij está reclamando


VB Scripting for counting the client connection

Question: I want to Count the number of client connection connected to a shared folder using vbscript.  I can use any service but not WMIservice.
Answer: Why would you not use WMI?
<code>sComputer = "."
sShare = "C$"

Set oWMI = GetObject("winmgmts:\\" & sComputer & "\root\cimv2")
Set colConnections = oWMI.ExecQuery("ASSOCIATORS OF {Win32_Share.Name=""" &
sShare & """} WHERE AssocClass=Win32_ConnectionShare")

WScript.Echo colConnections.Count & " open connections on \\" & sComputer &
"\" & sShar
</code>
(Source: http://www.webmasterkb.com/Uwe/Forum.aspx/vbscript/12834/VBScript-and-Shares )


How to set up a recurring payment

Question: I need to set up a recurring payment on Drupal 8. I discovered these two possiblity :

https://stripe.com/us/billing
https://www.drupal.org/project/commerce_recurring

What is the difference between these two possiblity ?
The commerce reccuring module looks extremely complex to set up.
Comment: It really comes down to whether or not you want to maintain recurring billing yourself within Drupal, or outsource it.  Outsourcing it to Recurly, say, allows for multiple payment methods such as Stripe, but you can also add other ones (or remove them) there without having to do much work on your Drupal site.
Answer: It's entirely dependent on your business needs. The advantage of Commerce Recurring is that as part of the Drupal Commerce ecosystem, it gives you a complete toolset for building a subscription management interface in Drupal 8. This will let you completely customize the checkout flow, order receipts, other user interfaces and more, but it does require experience with Drupal 8 to build and maintain. For more information, review the documentation at:
https://docs.drupalcommerce.org/commerce2/developer-guide/recurring
If you just want to embed a Stripe widget, I recommend MoonClerk.
Answer: There is a Recurly module to integrate the Recurly subscription service.
This module has a stable release for Drupal 8.
The project page also has a fair amount of information on PCI compliance.
Answer: There is the Stripe Registration module, which implements Stripe Plans.
It has the important limitation of "one subscription per user".

How to set up a recurring payment


Display Format String to User

Question: How do I go about displaying a format string as-is?
I have a property decorated with some data annotations:
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public blah blah { get; set; }

I now have a reference to the format string:
string format = metadata.DisplayFormatString; // == {0:MM/dd/yyyy}

I want to display this format string to the user without manually typing it in my view. Is there a nice way (not replace chars with empty string) to get MM/dd/yyyy from the string format?
Comment: Why not replace chars? Surely that's what any other method would do anyway? I suppose you could use a regular expression, but that will be very similar.
Comment: Because I have several different format strings. Some of them contain colons and such that should be displayed and I was hoping there was a generic way to do it to where I don't have to worry about escaped chars and such.
Answer: I thing using replace is a nice way too. If you're concerned about clutter in the view, you could put this into an extension method (or even an HTML Helper extension method).
public static string ToUserFriendlyDateFormat(this string unfriendlyFormat) {
    return unfriendlyFormat
        .Replace("{0:", string.Empty)
        .Replace("}", string.Empty);
}

Comment: Since there's no generic way to handle it, I went with a simple replace that has the cases for my different format strings.
Answer: I don't know what all your format strings look like, but if your format strings ever make it to String.Format() you already have to escape { and } characters (by doubling them).  How about using a regular expression.  Here's something simple to start with that will also undouble the { and } characters:
string DisplayFormat(string format) {
    Regex rx = new Regex(@"\{\d+:([^}]+)}|\{\{|}}");
    return rx.Replace(format, delegate(Match m) {
        if (m.Value == "{{") {
            return "{";
        } else if (m.Value == "}}") {
            return "}";
        } else {
            return m.Groups[1].Value;
        }
    });
}

Note that the above code will have to change if your format strings contain sequences like {0} and you want something special done with them as well.

Display Format String to User


Intellij automatically converting FQN to imports

Question: If I have code that has a bunch of fully qualified names in it (java.util.List, javax.swing.JLabel, etc.) is there a command in intellij that will automatically convert those to import the package and just use the class name?
Answer: This can be achieved by first turning on inspection for this.
Open up the Settings dialog and go down to Inspections and then search for qualified keyword and then turn on Unnecessary fully qualified name inspection:

That will make all occurrences of FQN in the code being color marked:

Now place the cursor on one of the highlighted areas and press Alt+Enter and a popup will give you the choice to Fix all 'Unnecessary fully qualified name' problems:

And then all FQN's will have been replaced with imports at the top instead:

If you want to run this inspection on the whole project (instead of just the current file) then you can choose the Run inspection on... alternative in the context menu:

Then choose Whole project:

And then finally in the Inspection Results window choose to Apply Fix on the selection:
Comment: Run inspection on... what a killer feature. Saved a botched Structured Search and Replace. Nice.
Comment: If you have some time it would be helpful to update the screenshots as IntelliJ has changed a little since your answer. Anyways, still helpful!
Answer: In case, for new code entries if you are seeing the FQNs, just make sure that Use fully qualified class names is un-checked.
Preferences -> Editor -> Code Style -> Java -> Use fully qualified class names

Comment: I guess this should be marked as answer as it aligns with new UI


How to convert multiple string of date formats to timestamp with timezone format

Question: I want to convert multiple string date format into a timestamp
For Example, I have the following string of dates like below
String date1 = "2020-01-01 12:23:30.345"
String date2 = "2020-01-01 12:23:30"
String date3 = "2020-01-01 12:23"
String date4 = "2020-01-01 12"

I want to convert all the above strings format into timestamp like,
For date1, Timestamp should be 2020-01-01 12:23:30.345 UTC
For date2, Timestamp should be 2020-01-01 12:23:30.000 UTC
For date3, Timestamp should be 2020-01-01 12:23:00.000 UTC
For date4, Timestamp should be 2020-01-01 12:00:00.000 UTC

Could you please help me with this? Any info will be really helpful. I can't define single string formatted for parser since the string format is unpredictable in my scenario.
Comment: Also Timestamp now is legacy, I recommend to about learn [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) library
Answer: You can use two formatter one to convert String to LocalDateTime and the other to convert from LocalDateTime to the expected String :
String[] dates = {date1, date2, date3, date4};
DateTimeFormatter formatterIn = DateTimeFormatter.ofPattern("yyyy-MM-dd HH[:mm][:ss][.SSS]");
DateTimeFormatter formatterOut = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

for (String date : dates) {
    LocalDateTime ldtIn = LocalDateTime.parse(date, formatterIn);
    String ldtOut = ldtIn.format(formatterOut);
    System.out.println(ldtOut);
}

Outputs
2020-01-01 12:23:30.345
2020-01-01 12:23:30.000
2020-01-01 12:23:00.000
2020-01-01 12:00:00.000

Comment: It's safer to use `uuuu` instead of `yyyy`. Please check [this discussion](https://stackoverflow.com/questions/41177442/uuuu-versus-yyyy-in-datetimeformatter-formatting-pattern-codes-in-java) as a reference.
Answer: You can use the optional pattern (inside square bracket) for the missing parts. You can also use DateTimeFormatterBuilder#parseDefaulting to default the missing parts of time to 0 or any other value.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtfForFormating = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);

        // Tests
        System.out.println(getLocalDateTime("2020-01-01 12:23:30.345"));
        System.out.println(getLocalDateTime("2020-01-01 12:23:30.345").format(dtfForFormating));

        System.out.println(getLocalDateTime("2020-01-01 12:23:30"));
        System.out.println(getLocalDateTime("2020-01-01 12:23:30").format(dtfForFormating));

        System.out.println(getLocalDateTime("2020-01-01 12:23"));
        System.out.println(getLocalDateTime("2020-01-01 12:23").format(dtfForFormating));

        System.out.println(getLocalDateTime("2020-01-01 12"));
        System.out.println(getLocalDateTime("2020-01-01 12").format(dtfForFormating));
    }

    static LocalDateTime getLocalDateTime(String text) {
        DateTimeFormatter multiFormatter = new DateTimeFormatterBuilder()
                                            .appendPattern("uuuu-MM-dd HH[:mm][:ss][.SSS]")
                                            .parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
                                            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                                            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                                            .toFormatter(Locale.ENGLISH);

        return LocalDateTime.parse(text, multiFormatter);
    }
}

Output:
2020-01-01T12:23:30.345
2020-01-01 12:23:30.345
2020-01-01T12:23:30
2020-01-01 12:23:30.000
2020-01-01T12:23
2020-01-01 12:23:00.000
2020-01-01T12:00
2020-01-01 12:00:00.000

Update
This is an update based on the OP's request to have timezone with the date-time.
LocalDateTime does not have timezone information. In order to have the timezone information, you need to convert it into ZonedDateTime.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtfForFormating = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS z", Locale.ENGLISH);

        // Tests
        System.out.println(getZonedDateTime("2020-01-01 12:23:30.345"));
        System.out.println(getZonedDateTime("2020-01-01 12:23:30.345").format(dtfForFormating));

        System.out.println(getZonedDateTime("2020-01-01 12:23:30"));
        System.out.println(getZonedDateTime("2020-01-01 12:23:30").format(dtfForFormating));

        System.out.println(getZonedDateTime("2020-01-01 12:23"));
        System.out.println(getZonedDateTime("2020-01-01 12:23").format(dtfForFormating));

        System.out.println(getZonedDateTime("2020-01-01 12"));
        System.out.println(getZonedDateTime("2020-01-01 12").format(dtfForFormating));
    }

    static ZonedDateTime getZonedDateTime(String text) {
        DateTimeFormatter multiFormatter = new DateTimeFormatterBuilder()
                                            .appendPattern("uuuu-MM-dd HH[:mm][:ss][.SSS]")
                                            .parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
                                            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                                            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                                            .toFormatter(Locale.ENGLISH);

        return LocalDateTime.parse(text, multiFormatter).atZone(ZoneId.of("Etc/UTC"));
    }
}

Output:
2020-01-01T12:23:30.345Z[Etc/UTC]
2020-01-01 12:23:30.345 UTC
2020-01-01T12:23:30Z[Etc/UTC]
2020-01-01 12:23:30.000 UTC
2020-01-01T12:23Z[Etc/UTC]
2020-01-01 12:23:00.000 UTC
2020-01-01T12:00Z[Etc/UTC]
2020-01-01 12:00:00.000 UTC

Comment: Hi Arvind, Thanks for the solution, It's worked fine.

One more question, Among with timestamp how can be add timezone as an optional pattern.

For example: If my input string is "2020-01-01 12:30" I should get my output string as "2020-01-01 12:30:00.000 UTC"
Comment: Hi Arvind, I guess my question is closed. Could you please paste an updated one in this chat? I tried to re-open it, But I'm getting some error.
Comment: @saravanakumar - You are most welcome. Wish you success! I've added it as an update.
Comment: Fine answer. (1) I'd nest the brackets since we only allow seconds when minutes are there and only millis when there are seconds. (2) Wihle the calls to `parseDefaulting()` may help understanidng, we can also fo without them if we want (as long as we want to default to 0). So just: `DateTimeFormatter multiFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH[:mm[:ss[.SSS]]]", Locale.ENGLISH);`.


how to change ckeditor4 classses for alignment?

Question: As you know ckeditor4 has alignment buttons.
when you press on each button, it adds a default class.
rteleft for left, rteright for right, rtecenter for center and rtejustify for justify alignment.
I want to know a way to change these default css classes?
for example for left align, I want to use uk-text-left or for center align, I want uk-text-center
Answer: I found the solution.
Just need to add this config to custom javascript confiurations in advanced section of ckeditor profile.
<code>config.justifyClasses = [ 'uk-text-left', 'uk-text-center', 'uk-text-right', 'uk-text-justify' ];
</code>


Format response array from http

Question: please help me to format my response from http.
Posting with AsynckTask
<code>protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
         HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost("http/test.php");

            try {
                // Add user name and password
             String latitude = "44.754535";
             String longitude = "11.178589";
             String range = "222";

               List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair(2);
                nameValuePairs.add(new BasicNameValuePair("latitude", latitude));
                nameValuePairs.add(new BasicNameValuePair("longitude",longitude));
                nameValuePairs.add(new BasicNameValuePair("range", range));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                Log.w("SENCIDE", "Execute HTTP Post Request");
                HttpResponse response = httpclient.execute(httppost);

                String str = inputStreamToString(response.getEntity().getContent()).toString();
                Log.w("SENCIDE", str);

                if(str.toString().contains("da"))
                {

                content=str.toString();

                }else
                {

                 System.out.print(str);
                }

            } catch (ClientProtocolException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            }
            return content;
        }
</code>
The log is this one :
<code>`{"success":0,"error_message":" 16.07 km da Motta"}
</code>
`
So the goal is to have only 16.07 km da Motta without changing php part.
See there are 3 items in aray, have some ideas to get 3rd object from array.
Tnx in advance.
Comment: out of curiosity, what is inputStreamToString (and what does it do that EntityUtils.toString() doesnt ?)
Comment: that's some weird error message, if you ask me
Answer: you are getting JSONObject in response from server . you can get values from it as :
<code>// convert Response String to JSONObject
JSONObject json=new JSONObject(str); //str=response string from server

// set error_message from json
String str_error_message=json.getString("error_message");

// set success from json
String str_success=json.getString("success");
</code>

Format response array from http


How to calculate mean and standard deviation of a count variable when the raw data is based on frequency categories?

Question: I asked 312 people how many times they visited their preferred local supermarket in a month
The results are as follows:

5% did not visit at all
7% visited once a month
33% visited twice a month
22% visited three times a month
15% visited four times a month
18% visited five and more times a month

In the absence of the actual number of visits (I only have percentage of patrons as above), how do you calculate the mean and standard deviation for reporting purposes.
Comment: Do you have any domain specific knowledge about how the "five and more times" category would be distributed across counts of 5, 6, 7, etc.?
Comment: @JeromyAnglim Not really (sorry!). It is all lumped together in this big category. Is there a way out of this predicament?
Answer: You need to be creative, because these data are consistent with any mean exceeding $0\times .05 + 1\times .07 + \cdots + 5\times .18$ = $2.89$ and any standard deviation exceeding $1.38$ (which are attained by assuming nobody visited any more than five times per month).
For reporting purposes, simply tabulate or graph the raw data:

If you must have a summary of location and spread, use alternative measures that can uniquely be found from these data.  The median is between 2 and 3, because 45% visited 2 times or fewer and 67% visited 3 times or fewer.  You might simply interpolate linearly and report a median of 2.3 visits per month.  For the spread, use (say) an interquartile range, also computed with linear interpolation.  I find Q1 is 1.4 and Q3 is 3.3, for an IQR of 1.9.
To go beyond that, you need to fit the data with a distribution, which requires assumptions and therefore is not just reporting.  But it can be useful.  However, these data are elusive: they will not fit standard models like Binomial or Poisson.  (I recommend against trying to fit discretized versions of continuous distributions, such as Lognormal, because it's hard to find any reason why they should fit: they don't form informative bases for comparison.  Moreover, since there are only six values here, it would be almost worthless to use more than one parameter in the modeling: two or more parameters give too much flexibility.)
As an example of the insight that might be afforded by a simple distributional fit, suppose the visits are made randomly over time by individuals and each individual has the same probability (per unit time) of visiting.  This is potentially a useful and interesting framework against which these data can be compared.  It leads to a Poisson distribution.  The best fit (in a chi-squared sense) is achieved with an intensity of 3.185 per month; this also is the variance (whence the standard deviation is $\sqrt{3.185}$ = $1.8$).

This is not a good fit (as a chi-squared test will show, but the eye plainly sees): there are too many people reporting 2 visits and too few reporting 1 visit. That perhaps is the most interesting thing about this analysis.  You could announce these results like this:

The median number of monthly visits among the respondents is 2.3 (with an IQR of 1.9).  The data depart significantly from a (best fit) Poisson distribution with a mean of 3.18 visits per month in that 19 fewer people than expected report one visit and 37 more people than expected report two visits.

Incidentally, a Poisson fit suggestively fills in the upper tail of "5 or more visits," providing quantitative hypotheses that could be tested in follow-on surveys:

Other distributions would give different extrapolations into this upper range.
Comment: About the curve fitting: would you use all the availble categories? And do you use a numerical value of 5 for the last one?
Comment: @Simone For the fitting, the category $\ge 5$ was replaced by *all* values $5, 6, 7, \ldots$.  In this fashion we avoid making an arbitrary assignment of a single value to this category.  The price we pay is to push the arbitrariness back to our original assumption of a Poisson distribution: there's no avoiding making some assumption, if meaningful statistics like a mean or SD are to be computed.  But at least this assumption is clearly stated and it serves as a useful, interesting point of reference for evaluating the entire distribution.
Comment: Interesting. And how do you do it in practice? I think that a fitting procedure take in input the values and their empirical frequency. Do you need to assign a particular frequency to $5,6,7,\dots$?
Comment: @Simone Yes: the frequency assigned to $\{5,6,7,\ldots\}$ is given in the question as 0.18.
Answer: You definitely have to associate a numerical value to the class "visited five and more times a month".
By the way, I would calculate the mean and the standard deviation in the usual way. In fact, $x_i$ are your values and $p_i$ are their empirical frequency estimated on the sample. In your case
$$x_0=0 \ x_1=1 \ x_2=2 \ x_3=3 \ x_4=4 \ x_5=6$$
(you should decide $x_5$)
$$p_0=0.05 \ p_1=0.07 \ p_2=0.33 \ p_3=0.22 \ p_4=0.15 \ p_5=0.18 $$
Thus
$$\bar{x} = \sum_{i=0}^{5}x_i p_i$$
and
$$\sigma=\sqrt{\sum_{i=0}^{5}(x_i - \bar{x})^2 p_i}$$
It could be interesting to delete $x_0$ and $p_0$ and rescale all $p_i$ in order their sum is 1. So you can calculate the average number of visits to the supermarket for a person that visits the supermarket.
Comment: Thanks! Please tell me how do I associate a numerical value to the class "five and more times"?
Comment: Both the mean and the SD computed with the nominal data values will be biased low if you use $x_5=5$; if you use any other value for $x_5$, you're being arbitrary.
Comment: Can you ask to some of the 56 people who answered that how many times they meant? Otherwise, in an empirical way, it is likely it is a normal distribution with mean 2-3 (because of the shape of the histogram) with some variance. And any value around 6 could be a good value for that category.
Comment: Now I'm really guessing. In a more technical and complicated way, that might be not necessary in this case, I would fit $x_i$ and $p_i$ for $i=0,\dots,4$ with a log-normal distribution with a statistical sofware (eg Matlab) and then I would calculate the centroid of this function in the interval $[4.5, +\infty)$. But I might be not a log-normal distribution because the pdf is not continuous in 0. Maybe a simple curve-fitting, without referring to a particular pdf, with a statistical software is better.


Find sequence $(a_n)$ of positive reals such that $\sum a_n$ diverges but $\sum a_n/(\ln(\ln(n)))$ converges.

Question: I want to find an example of a sequence $a_n >0$ such that its series $\sum a_n$ diverges, but when we consider  $$\sum_{i=2}^n \frac{a_n}{\ln(\ln(n))}$$ then this series is in fact convergent.
Any idea what to start with, what motivation would you use to find such a sequence?
Comment: Sorry. My bad. I've addes some essential info.
Comment: @FilipWichrowski:  if we use  the variable $n$, use $\log$ instead of $\ln$. of course, both are correct, but $\log n$ looks fine than $\ln n$
Comment: but $\ln$ is the proper name for this $\log$
Comment: what would we like to see added to make this question better?
Answer: Take $$a_n=\frac{1}{(n\, \ln n) \ln( \ln n)}$$ Then $$\sum_{n=3}^\infty a_n= \sum_{n=3}^\infty \frac{1}{(n \,\ln n) \ln( \ln n)} $$ diverges , but $$\sum_{n=3}^\infty \frac{a_n}{\ln(\ln n)}= \sum_{n=3}^\infty\frac{1}{(n\,\ln n) \ln( \ln n)}. \frac{1}{\ln(\ln n)}=\sum_{n=3}^\infty \frac{1}{n \,\ln n [\ln (\ln n)]^2}< \infty$$

The convergence and divergence are follows from:
Theorem 1: Suppose $a_1 \geq a_2 \geq \cdots \geq 0. $ Then $\sum a_n < \infty \iff \sum 2^k a_{2^k} < \infty$
Theorem 2: If $p>1$, then $$\sum \frac{1}{n\, (\ln n)^p} $$ converges, and diverges  otherwise
Comment: @gimusi: I already mention that in my answer.
Comment: @ChinnapparajR That's fine sorry I didn't see that. Bye
Comment: What led you to this form of $a_n$? And how to prove that $\sum a_n = +inf$?
Comment: I suggest to use [Cauchy condensation test](https://en.wikipedia.org/wiki/Cauchy_condensation_test)
Comment: If this answers the question, I would say it's nice to accept it as an answer.
Comment: see my answer again!
Comment: Ok! no problem!
Comment: One more thing, if I may: I try to prove that $a_n$ diverges by comparing it to $\frac{1}{nln(n)ln(n)}$, but it coverages. Is there any different approach?
Comment: I think I got it - $\frac{ln(ln(n))}{ln(n)} < 1$ so the power of $ln(n)ln(ln(n)) < 1$, am I correct?


Cálculos dobras cutâneas

Question: Bom, eu não sei se posso pedir ajuda em relação a calculo, mais de toda forma, minha dúvida é a seguinte:
Eu preciso fazer o calculo de dobras cutâneas, neste caso o calculo de Pollok 3 dobras, pesquisei na internet, mais não é algo tão fácil de compreender, gostaria de saber, se a maneira com a qual eu estou fazendo esta correta. Eu ia postar apenas o calculo, mais fiz também um exemplo executável (exemplo bem simples) para poder ilustrar a situação melhor.
Eu usei estas informações como base:
Para 3 dobras:
DC= 1,10938 – 0,0008267 (X2) + 0,0000016 (X2)
2 – 0, 0002574 (X3)
Legenda:
DC= Densidade Corporal em g/ml
X2 = soma das 3 dobras (tórax, abdominal e coxa)
X3 = idade em anos

Obs: página 36 : https://sandrodesouza.files.wordpress.com/2010/05/perimetria-dobras-cutaneas-e-protocolos.pdf
Código:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class DobrasCuteneas extends JFrame {

    JTextField campoPeitoral = new JTextField();
    JTextField campoAbdominal = new JTextField();
    JTextField campoCoxa = new JTextField();
    JTextField campoGorduraIdeal = new JTextField();
    JButton botao = new JButton("Calcular");

    public DobrasCuteneas() {
        setTitle("Exemplo");
        add(tela());
        pack();
        acaoBotao();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

    private void acaoBotao() {
        botao.addActionListener((ActionEvent ae)
                -> {
            calculo();
        });
    }

    private JPanel tela() {
        JPanel painel = new JPanel();
        JLabel label01 = new JLabel("Peitoral:");
        painel.add(label01);
        painel.add(campoPeitoral);
        campoPeitoral.setPreferredSize(new Dimension(100, 20));
        JLabel label02 = new JLabel("Abdominal:");
        painel.add(label02);
        painel.add(campoAbdominal);
        campoAbdominal.setPreferredSize(new Dimension(100, 20));
        JLabel label03 = new JLabel("Coxa:");
        painel.add(label03);
        painel.add(campoCoxa);
        campoCoxa.setPreferredSize(new Dimension(100, 20));
        painel.add(botao);
        botao.setPreferredSize(new Dimension(90, 20));
        JLabel label04 = new JLabel("Gordura ideal:");
        painel.add(label04);
        painel.add(campoGorduraIdeal);
        campoGorduraIdeal.setPreferredSize(new Dimension(100, 20));
        add(painel);

        return painel;
    }

    private void calculo() {
        float peitoral = Float.valueOf(campoPeitoral.getText().replaceAll(",", "."));
        float abdominal = Float.valueOf(campoAbdominal.getText().replaceAll(",", "."));
        float coxa = Float.valueOf(campoCoxa.getText().replaceAll(",", "."));
        float idade = 25;
        Float x2 = (peitoral + abdominal + coxa);

        Float densidadeCorporal = (float) (1.10938 - x2) + (x2 * 2) - idade;
        System.out.println("Densidade corporal: " + densidadeCorporal);
        Float percentualGordura = ((float) ((4.95 / densidadeCorporal) - 4.50) * 100);
        System.out.println("Percentual de gordura: " + percentualGordura);
        campoGorduraIdeal.setText("" + percentualGordura);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(()
                -> {
            DobrasCuteneas dobras = new DobrasCuteneas();
            dobras.setVisible(true);
        });
    }
}

E para o calculo final (gordura ideal) :
%G = [(4,95/Densidade Corporal) - 4,50] x 100

Answer: Na formula para a densidade corporal ficaram a faltar os coeficientes assim como o quadrado de X2. Relembrando que a mesma é (pelo pdf indicado):

DC= 1,10938 – 0,0008267 (X2) + 0,0000016 (X2)^2 – 0,0002574 (X3)

E que foi aplicada como:
Float densidadeCorporal = (float) (1.10938 - x2) + (x2 * 2) - idade;

Os coeficientes de 0,0008267, 0,0000016 e 0,0002574 não foram utilizados.
Para corrigir basta trocar a formula para:
Float densidadeCorporal = 1.10938 - (0.0008267 * x2) + (0.0000016 * x2 * x2) - (0.0002574 * idade);

Comment: Nesse caso, ele acaba me retornando valores como -421.000 por exemplo, eu acredito que isso não esteja correto.
Comment: @GustavoSantos De facto também faltava o coeficiente para a `idade`. Confirme agora se obtêm os valores esperados

Cálculos dobras cutâneas


Rescue as much data as possible from damaged tape

Question: We have some data on very old DDS (1,2 and 3) DAT tapes.
I tried reading them with:
dd if=/dev/st0 of=file bs=32k

but get many partial blocks and sometimes IO errors.
Have also tried with:
dd if=/dev/st0 of=file bs=32k conv=noerror

which does not stop at partial blocks but does sometimes give IO errors.
Some of these tapes contain tar archives but most of them contain a bunch of FITS files.
What would be the best way to rescue as much data as possible from these tapes?
Answer: Send 'em to Kroll Ontrack (or another professional data recovery company). Your restore efforts are much more likely to further damage the tapes than doing anything productive.
Comment: To some degree I feel bad not voting for the answer that provided technical information, but the risk of additional loss due to half (or 3/4 or 7/8) measures, and not knowing how valuable the data is that is being recovered make me want to err on the side of caution.
Comment: I don't think the data is important enough to justify sending it to such a company. I would prefer to just read the maximum amount and spend a couple of hours regenerating the few files missing.
Answer: Have a look at ddrescue, which is written for exact this purpose. Depending on the importance of the data, a professional rescue service might be able to do much better, at a (likely very high) price.
Comment: ddrescue only works with block devices that allow non sequential access (am I right?). I thought it would not work with /dev/st0 which is a character device? If not I might give it a try.


run xterm by crontab

Question: $ */1 * * * * xterm    -display :0 -hold -e 'which xterm'
There will be two xterm windows pop-out at the same time, why?
$*/1 * * * * xterm    -display :0 -hold -e '/home/name/bin/scriptaaa '
works well
$*/1 * * * * xterm    -display :0 -hold -e 'scriptaaa'
command not found   ,why?
$ which xterm
/usr/bin/xterm
Comment: Are you sure you have 'which xterm' in single quotes instead of in backticks? Also `/1` is redundant.
Comment: yes, single quotes. and /1 is not necessary
Answer:
Because you explicitly asked for, the first time as crontab-executed command, and another - in the command executed by xterm
Ok
Check $PATH. Usually crontab doesn't inherit environment of a user, so $HOME/bin isn't in $PATH
Comment: you mean 'which xterm' is special? `which xterm` could be normally run in xterm itself.  xterm's path is in `$PATH`. I do not know why the scripts in `/home/name/bin` can not be recognised.
Comment: many people have noticed that. http://lists.apple.com/archives/darwinos-users/2005/Feb/msg00029.html
Comment: @questionhang xterm might inherit the path, but this isn't run from a shell that has PATH defined, it's run from a crontab which hasn't inherited it. You can specify, PATH=/home/name/bin/ in the crontab and it will probably work.
Comment: There is no change. It is still `command not found`.                                                        $crontab -e                                                   $`* * * * * export PATH="/home/name/bin:$PATH"`
Comment: No, 'which xterm' is not special, and actually it does exactly what it should do (prints /usr/bin/xterm). But when I first saw this question the command seemed to be `which xterm`, which obviously runs xterm by its full path. If you're sure that you haven't `s` in the command line and you still get two xterms at once then it's strange indeed. You may add `-title "$date"` to xterm options to see, if these xterm are run at once
Comment: Well, it's better to configure PATH and other environment variables on a dedicated line, as documented in `man 5 crontab`

run xterm by crontab