Control ELB by Traffic load

Question: We recently used Amazon AWS.
Now our application is on the cloud. And we configured ELB with Auto Scalling and it works fine.
We need to modify the ELB and control how it works. I checked all the configuration and couldn't do it.

How could we customize the traffic distributation over the instances?
If it's not possible to do with ELB, is there any other way to do so?
Answer: ELB distributes requests evenly amongst the healthy availability zones, then evenly amongst the instances in that zone. You can't configure this further. You'll want to make sure you don't do something like 3 instances in us-west-2a and one in us-west-2b, as the one in 2b would receive 3x the traffic as each of the 2a instances.
If you want load balancing based on something like instance load, you'll need to build your own solution in AWS with something like HAProxy.

Control ELB by Traffic load


Limit of functions involving trigonometry as n approaches infinity

Question:
By graphing these functions, I know that P(n) approaches pi as n tends towards infinity. However, is there a mathematical way for proving this?
I am doing a maths exploration on Archimedes' approximation of pi and those are the formulas that I derived for polygons that fit perfectly outside (the first function) and inside (the second function) of a circle with a diameter of 1 (and they work!).
I have also taken the derivative of the functions to show that they are monotone increasing (for the second function) and decreasing (for the first function).
Comment: For the first one note that $n\tan(\frac{\pi}{n})= \pi\frac{\tan(\frac{\pi}{n})}{\frac{\pi}{n}}$. You can solve the second one by using this trig identity: $2\sin^2(\frac{x}{2}) = 1 - \cos(x)$
Comment: Hm Interesting Question...
Answer: I think that Taylor series could be a simple solution.
Considering that, for small $x$, $$\tan(x)=x+\frac{x^3}{3}+O\left(x^4\right)$$ $$n \tan\big(\frac{\pi}n\big)=n \Big(\frac{\pi }{n}+\frac{\pi ^3}{3 n^3}+\cdots)=\pi+\frac{\pi ^3}{3 n^2}+\cdots$$ For the second (without using the good hint user222031 provided in comments) $$\cos(x)=1-\frac{x^2}{2}+\frac{x^4}{24}+O\left(x^6\right)$$ $$\cos\big(\frac{2\pi}n\big)=1-\frac{2 \pi ^2}{n^2}+\frac{2 \pi ^4}{3
   n^4}+\cdots$$ $$\frac 12 -\frac 12 \cos\big(\frac{2\pi}n\big)=\frac{\pi ^2}{n^2}-\frac{\pi ^4}{3 n^4}+\cdots=\frac{\pi ^2}{n^2}\big(1-\frac{\pi ^2}{3n^2}+\cdots\big)$$ $$\sqrt{\frac 12 -\frac 12 \cos\big(\frac{2\pi}n\big)}=\frac{\pi }{n}\sqrt{1-\frac{\pi ^2}{3n^2}+\cdots}=\frac{\pi }{n}\big(1-\frac{\pi ^2}{6n^2}+\cdots\big)$$ $$n\sqrt{\frac 12 -\frac 12 \cos\big(\frac{2\pi}n\big)}=\pi\big(1-\frac{\pi ^2}{6n^2}+\cdots\big)$$
For sure, this be can be done faster using  user222031's hint since  $$\sqrt{\frac 12 -\frac 12 \cos\big(\frac{2\pi}n\big)}=\sin\big(\frac{\pi}n\big)$$ and since $$\sin(x)=x-\frac{x^3}{6}+O\left(x^4\right)$$ then $$n\sin\big(\frac{\pi}n\big)=n\Big(\frac{\pi }{n}-\frac{\pi ^3}{6 n^3}+\cdots\Big)=\pi\big(1-\frac{\pi ^2}{6n^2}+\cdots\big)$$


Tomcat home directory environment variable

Question: I'm currently editing the server.xml context paths and want to have a context path back to the original webapps directory. Is there an built in tomcat environment variable that points back to the tomcat installation directory like TOMCAT_HOME or something?
Comment: The environment variables [`CATALINA_HOME` and `CATALINA_BASE`](https://tomcat.apache.org/tomcat-10.0-doc/introduction.html#CATALINA_HOME_and_CATALINA_BASE) can be accessed through `${catalina.home}` and `${catalina.base}` in `server.xml`. However most paths are already relative to `CATALINA_BASE`. Can you explain better what you want to achieve? It seems like an [XY problem](https://meta.stackexchange.com/q/66377/930241), maybe there is a better solution.
Comment: Well I changed my  the log file stderror says it can't find C:\FB20\web\webapps. So basically I want to change that to TOMCAT_HOME/webapps.
Answer: As pointed out in the comments, the Tomcat installation directory is available as ${catalina.home} property, while the Tomcat instance root directory through ${catalina.base} (cf. Tomcat documentation). E.g. you can use ${catalina.home}/webapps/manager for the location of the Tomcat Manager application.
However I wouldn't define the contexts for Tomcat Manager and other applications in server.xml: they have their own context definitions in the META-INF/context.xml file of their folder, so they probably should not be redefined in server.xml: this way you can loose some important configuration attributes (like privileged="true" for Tomcat Manager).
A better solution would be to copy those definitions into conf/Catalina/localhost/<appname>.xml and add the docBase="${catalina.home}/webapps/<appname> attribute. E.g. for Tomcat Manager you should create a file named conf/Catalina/localhost/manager.xml with content:
<Context docBase="${catalina.home}/webapps/manager" antiResourceLocking="false" privileged="true" >
  <CookieProcessor className="org.apache.tomcat.util.http.Rfc6265CookieProcessor"
                   sameSiteCookies="strict" />
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>


Is it possible for a systemd service to update itself?

Question: Hey faultless server folks,
I'd like to write a systemd service that can update itself.
Specifically, every 5 minutes it should look at Amazon S3 for new versions of its binary and .service files.
If they've been updated, it should download and replace them, and then restart itself.
Unfortunately, I understand systemd doesn't allow modification of in-use files.
Is there some standard way to achieve this?
Thanks!
EDIT: To clarify, I'm asking if it's possible to do this with a single service. I realize I could have a pair of services which update each other, but that seems inelegant.
Comment: why don't you want to use systemd.times or cron for this task?
Answer: Updating files related to systemd .service files or program executables is the same as updating any other file.
You should really do this with configuration management such as Ansible, but to get it done as-is your general workflow could be using a bash/python script that does the following:

Gets the file(s) from the web server/s3/etc.

You can do a quick md5sum check to compare differences. Or compare dates, other metadata to determine if the file is new or changed

Replace the files as needed

You may need to stop the service (service <servicename> stop) beforehand if the files are in-use.

Run systemctl daemon-reload to tell systemd to "re-scan" the service files for any changes.
Restarts/starts the service in question

You can then load that script up in cron or as a systemd timer to run on a schedule.
Comment: Thanks, and I take it to mean the answer is "no". No, a service can't update itself - you need to use a second service to update the first one.
Comment: Well, I think it leans more towards "yes - it's technically possible". It depends on what process is running as the service. If you ran the above script process as a systemd service you could do it. Like a self-updater mechanism written into the process itself. It could even restart itself. Depends on the use-case but most things are always possible depending on how creative you get.
Comment: If your service executes a binary at a path, and your 'updater' service finds the new binary, pulls it down (replaces the old with a symlink to the new), and restarts the service, you woudln't even need a deamon-reload if you're not actually updating the *.service file


Which soccer players have been selected best player of the Copa América more than once?

Question: I know that Lionel Messi and Enzo Francescoli have been chosen the best player of the Copa América twice. It happened in 2021, 2015, 1995 and 1983 respectively. Are there other soccer players who have been chosen the best player of the Copa América more than once?
Answer: Technically, the tournament was renamed Copa America in 1975. It isn't really hard to list all the best players:

Year
Best Player

1975
 Teófilo Cubillas

1979
 Carlos Caszely

1983
 Enzo Francescoli

1987
 Carlos Valderrama

1989
 Rubén Sosa

1991
 Leonardo Rodríguez

1993
 Sergio Goycochea

1995
 Enzo Francescoli

1997
 Ronaldo

1999
 Rivaldo

2001
 Amado Guevara

2004
 Adriano

2007
 Robinho

2011
 Luis Suárez

2015
 Lionel Messi

2016
 Alexis Sánchez

2019
 Dani Alves

2021
 Lionel Messi

If you want to count the best players of the South American Championship (before 1975), then the full list of them is available on the RSSSF website. According to this list two other players won the award twice:
José Nasazzi (Uruguay, 1923, 1935) and Manuel Seoane (Argentina, 1925, 1927).
Comment: Not sure, supposedly Pelé was the best player of the 1959 Copa América.
Comment: @Pablo Hmm, interesting. It seems I'll need to dig deeper. At least, this list is a start. :)
Comment: that's why I upvoted
Comment: @Pablo I've updated my answer with the link to a full list of best players, including South American Championship.


How to access twig object values?

Question: I have an object called 'attributes' available to me in a twig template. Given that the following:
{{ dump(attributes) }}
{{ dump(attributes.storage) }}
{{ dump(attributes.storage['data-quickedit-field-id']) }}

dumps this:

how do I access the value property:?
'paragraph/3/field_section_title/en/default'

I've tried the obvious:
{{ dump(attributes.storage['data-quickedit-field-id'].value) }}

The following methods are available to me:
Answer: You can pipe it to render:
{{ attributes.storage['data-quickedit-field-id']|render }}

Answer: You can use offsetGet and render :
{{ attributes.offsetGet('data-quickedit-field-id')|render  }}

Source : https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Template%21Attribute.php/function/Attribute%3A%3AoffsetGet/8.2.x

How to access twig object values?


Kolmogorov's Maximal inequality and convergence a.s.

Question: I have a question about Durrett exercise 2.5.12 (i).

where the (*) is given in 2.5.9

When I try to use Maximal Inequality, it is in the form of $|\frac{S_N}{a(n)}-\frac{S_m}{a(m)}|$. So that, I am not able to apply Maximal Inequality directly. Could anyone help me with this?
Answer: It suffices to show that
$$
M_n:=\frac1{a(2^n)}\max_{2^n+1\leqslant k\leqslant 2^{n+1}}\lvert S_k-S_{2^n}\rvert\to 0 \mbox{ a.s.}
$$
Indeed,
$$
\max_{2^n+1\leqslant k\leqslant 2^{n+1}}\frac{\lvert S_k\rvert}{a(k)}
\leqslant\max_{2^n+1\leqslant k\leqslant 2^{n+1}}\frac{\lvert S_k\rvert}{a(2^n)}\leqslant
\frac{\lvert S_{2^n}\rvert}{a(2^n)}+M_n
$$
Noticing that $S_k-S_{2^n}=S_{2^n,k}$ we have by 2,5,9:
$$
\mathbb P\left(M_n>2\varepsilon\right)\leqslant \frac{\mathbb P\left(\lvert S_{2^{n+1}}-S_{2^n}\rvert>\varepsilon a(2^n)\right)}{\min_{2^n+1\leqslant k\leqslant 2^{n+1}}\mathbb P\left(\lvert  S_k-S_{2^n}\rvert \leqslant \varepsilon a(2^n)\right)}.
$$
Using boundedness of $a(2^n)/a(2^{n-1})$, we know that $\lvert S_{2^{n+1}}-S_{2^n}\rvert/ a\left(2^n\right)\to 0$ in probability.
Comment: @user124697 Actually, it turns out that it was not the right place to use the assumption. I have edited.
Comment: Why boundedness of $a(2^{n})/a(2^{n-1})$ implies that $M_{n} \to 0$a.s. implies $S_{n}/a_{n} \to 0$ a.s.?

Kolmogorov‘s Maximal inequality and convergence a.s.


How do I make a div animation slide up and disappear?

Question: I know this may sound like a basic question but the truth is I'm not that of an expert with animations and it's hard to calculate the math from x and y. So, I would like to know how to make the "gl_banner" div simply slide up after a 0.5-1 second(s) and disappear and the content below it will be pushed up to its original position. What css properties do I use? css-animation? transition? How do I do it?
P.S. I did some research on animations and I saw a lot of animations, advanced animations but couldn't find a simple slide up animation. A little help is appreciated! Thanks!
HTML CODE:

Good Luck! :)

                <form id="quiz" action="grade.php" method="post" style="visibility:hidden;">

1. How many percent of modern camera phones use CMOS?

                        <input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" />
                        A) 20%

                        <input type="radio" name="question-1-answers" id="question-1-answers-B" value="B" />
                        B) 80%

                        <input type="radio" name="question-1-answers" id="question-1-answers-C" value="C" />
                        C) 50%

                        <input type="radio" name="question-1-answers" id="question-1-answers-D" value="D" />
                        D) 90%

2. Which type of camera setting(s) is best for greater control and flexibility in terms of focusing on a subject?

                        <input type="radio" name="question-2-answers" id="question-2-answers-A" value="A" />
                        A) Manual Focus

                        <input type="radio" name="question-2-answers" id="question-2-answers-B" value="B" />
                        B) Auto Focus

                        <input type="radio" name="question-2-answers" id="question-2-answers-C" value="C" />
                        C) Both A and B

                        <input type="radio" name="question-2-answers" id="question-2-answers-D" value="D" />
                        D) Neither

3. What are the three properties included in an exposure triangle?

                        <input type="radio" name="question-3-answers" id="question-3-answers-A" value="A" />
                        A) White Balance, ISO, Low Light

                        <input type="radio" name="question-3-answers" id="question-3-answers-B" value="B" />
                        B) Shutter Speed, Exposure, ISO

                        <input type="radio" name="question-3-answers" id="question-3-answers-C" value="C" />
                        C) Aperture, ISO, Exposure

                        <input type="radio" name="question-3-answers" id="question-3-answers-D" value="D" />
                        D) ISO, Aperture, Shutter Speed

4. The higher the ISO, the more noise it produces in an image.

                        <input type="radio" name="question-4-answers" id="question-4-answers-A" value="A" />
                        A) True

                        <input type="radio" name="question-4-answers" id="question-4-answers-B" value="B" />
                        B) False

5. What is the name of the smartphone you've seen all over this site?

                        <input type="radio" name="question-5-answers" id="question-5-answers-A" value="A" />
                        A) Nokia Pureview 808

                        <input type="radio" name="question-5-answers" id="question-5-answers-B" value="B" />
                        B) Nokia Lumia 1020

                        <input type="radio" name="question-5-answers" id="question-5-answers-C" value="C" />
                        C) Nokia Lumia 925

                        <input type="radio" name="question-5-answers" id="question-5-answers-D" value="D" />
                        D) Nokia Lumia 920

                    <input style="cursor:pointer;" type="submit" value="Submit Quiz" />
                </form>

JavaScript Code:
function takeQuiz()
{
// hide the intro
document.getElementById('intro').style.display = 'none';

// display the quiz
document.getElementById('quiz').style.visibility = 'visible';
document.getElementById('gl_banner').style.display = 'block';
document.getElementById('gl_banner').style.visibility = 'visible';
}

Answer: Use jQuery library .
Ex:

$( "intro" ).hide(); //hide div "intro" immd
$( "intro" ).click(function( event ) {//hide div "intro" on click
  event.preventDefault();
  $( this ).hide();
});

$( "intro" ).show(); //to show after hide

$( "intro" ).fadeOut();
$( "intro" ).fadeIn();

Comment: i dont know anything about jquery. I just want a simple javascript code without the use of libraries.
Comment: Just add this script include line within the  section , and follow the exact syntax. Very simple !
Comment: Just by reading it, it does the exact same thing as my javascript code. What I want changed now is the "gl_banner" div to slide up animated and disappear, that's it.
Comment: use $("gl_banner").fadeout();
Comment: Um, I'm having trouble running the jquery code now. I added mine after your comment to include mine. Is that correct?
Comment: jquery script in head at the top .
Comment: At the bottom put the code I put into
Comment: i believe i have done that shown above? mind editing the code, so I know what you mean.
Comment: I am sorry I cannot edit already posted answers too much . They anyway get declined.
Comment: okay, I'll try to figure it out. Thanks for giving me a head start.
Answer: Check an example made by me with click function from JQuery:
Knee's Fiddle

Have fun (:


Showing equality of sets using logical equivalance

Question: I'm just getting started with sentential logic and set theory in Discrete Math.
I'd learned that to show two sets equal, say $A$ and $B$, you show $A$ is a subset of $B$ and that $B$ is a subset of $A$.  But is it also possible to show that the sets are equal by showing that they are logically equivalent?  Or is that comparing apples and oranges?
Basically, is showing $A \equiv B$ the same as $A = B$ ?
If my question isn't clear I can add an example of what I'm talking about.
Thanks!
Comment: What do you even mean by saying that two groups are "logically equivalent"?
Comment: And are you sure you really mean "groups" here, rather than sets? (A group is a set together with an associative binary operation that has an identity element and inverses for all elements).
Comment: @Henning Makholm:  I'm refering to sets, not groups. Thanks for pointing out the difference.  I'm really really new to this :-)
Comment: Also, I'm posting from Linux.  How do I add math symbols?
Comment: @Robert: This has nothing to do with your operating system (a linux user myself), this is called $\LaTeX$, compiled here using the MathJax script.
Comment: What is "sentinel logic"? Is that supposed to be "sentential logic" (aka propositional calculus)?
Comment: @ArturoMagidin Yes, I mean sentential - just a typo...
Comment: This question is not yest answered in terms which I can understand.
Answer: We start in a given model in which we consider the sets $A,B$.
Suppose $A=\{x\mid\varphi(x)\}$, and $B=\{x\mid\psi(x)\}$. That is $A$ and $B$ are sets defined as all the elements with property $\varphi$ or $\psi$.
Note the following things:

$A\cup B=\{x\mid x\in A\lor x\in B\} = \{x\mid\varphi(x)\lor\psi(x)\} = \{x\mid\big(\varphi\lor\psi\big)(x)\}$
$A\cap B=\{x\mid x\in A\land x\in B\} = \{x\mid\big(\varphi\land\psi\big)(x)\}$
$A^c = \{x\mid x\notin A\} = \{x\mid\lnot\varphi(x)\}$
$A\setminus B=\{x\mid x\in A\land x\notin B\} = \{x\mid\big(\varphi\land\lnot\psi\big)(x)\}$
$A\subseteq B$ means $x\in A\rightarrow x\in B$, that is $\varphi(x)\rightarrow\psi(x)$, similarly to before $\big(\varphi\rightarrow\psi\big)(x)$.

We can formulate logical equivalence as: $$\varphi\leftrightarrow\psi\iff(\varphi\rightarrow\psi)\land(\psi\rightarrow\varphi)$$
From this and the list above we reach the following conclusion:
$$\{x\mid\varphi(x)\} = \{x\mid\psi(x)\}\iff\varphi\leftrightarrow\psi$$
Of course all the above is true in the context of a given model. The formulas might not be equivalent in a different interpretation.
For example, let $\mathcal L=\{<,a\}$  be a language with a binary relation $<$ and a constant $a$. (We of course include $=$ as well)
Now consider $\varphi(x) = a<x$, and $\psi(x) = \lnot(x=a)$.

Take the model of $\mathbb N$, interpret $a=0$ and $<$ as the usual ordering. We have that $\{x\in\mathbb N\mid\varphi(x)\} = \{x\in\mathbb N\mid\psi(x)\}$, since in $\mathbb N$ being greater than $0$ is the same as being nonzero.
Take the model of $\mathbb Z$, interpret $a$ and $<$ as before. Now $\{x\in\mathbb Z\mid\varphi(x)\}\subsetneqq\{x\in\mathbb Z\mid\psi(x)\}$, since $-1$ is nonzero, but not positive either.

A final word, of utter importance (I think) is that in general there can be much more sets than formulae, therefore some sets cannot be described by a formula. To add on that the whole process of showing logical equivalence above is pretty much the same amount of work as to show the two sided inclusions this brings one important moral: Two sided inclusion is a safe way to show equality of sets in a general setting.
Comment: The line for A intersection B isn't displaying correctly.
Comment: @Robert: Thanks! I have correct that now.
Comment: 2 Questions:  Showing logical equivalence means showing the condition for inclusion in each set results in the same set of members, and this depends on the model in use? So 2 sided inclusion can work in any general case, but logical equivalence may or may not work depending on the model in use?
Comment: @Robert: Logical equivalence is to show that under certain assumptions two sentences are equivalent. Different models may have different properties which imply the assumptions are different. The inclusion is a relatively "safer" way to work with.
Comment: תודה רבה אסף, תשובה מעולה
Answer: The truth is that $(A\subseteq B \land B\subseteq A) \leftrightarrow (\forall x(x\in A \leftrightarrow x\in B))$. On the right side you see the logical equivalence $\leftrightarrow$, not equivalence of sets, but equivalence of logical formulas that say that $x$ belongs to a set. Yes, in a sense you can prove equality of sets by proving logical equivalence.
Comment: "in a sense" is somewhat vague and this answer hasn't been up-voted so I don't know how much to trust it.


Question regarding a remark in Hatcher's Algebraic Topology

Question: I am having difficulty understanding the following remark made by Hatcher on page 50 of Algebraic Topology:

My understanding of this paragraph is as follows: For a basepoint $s_0\in S^1$ the attaching map $\varphi_{\alpha}$ determines a loop based at $\varphi_{\alpha}(s_0)$ in $Y$, namely the boundary of the image of $e^2 _{\alpha}$. For some path $\gamma_{\alpha}$ from $x_0$ to $\varphi_{\alpha}(s_0)$ one can use the change of base isomorphism, one sees that the loops $\varphi_{\alpha}(s_0)$ can be associated with loops all based at the same point $x_0 \in X$. This is as far as I can follow. I don't understand why although the loop $\gamma_{\alpha}\varphi_{\alpha}(s_0)\overline{\gamma_{\alpha}}$ will be nullhomotopic after attaching $e^2_{\alpha}$, even though it may not be before.

Why is this? Also, are there examples which can elucidate why this is true?
Answer: Let $X$ be an annulus with boundary and let $\phi_\alpha$ be the map that maps $S^1$ homeomorphically to the inner boundary of the annulus. Pick any point $x_0$ in the interior of the annulus and paths from $x_0$ to $\phi_\alpha(s_0)$. Then $\gamma_\alpha\phi_\alpha \bar{\gamma}_\alpha$ is certainly not nullhomotpic as it is in the equivalence class of the generator of the fundamental group of the annulus ($\mathbb{Z}$).
After the attaching is performed, the space $Y$ is a disk, as the map $\phi_\alpha$ attaches the two-cell and fills in the center of the annulus. Therefore, after attaching the disk, the loop becomes nullhomotopic.
Answer: The simplest example would be taking a generator of $\pi_1(S^1,x_0)$, pick any $x_0$, and attach a single 2-cell to $S^1$ in the normal way. Then the (previously non-zero) loop becomes null-homotopic, since this new space is just $S^2$(EDIT: $D^2$, as pointed out in the comments).
In general, the loop $\varphi_\alpha$ will become null-homotopic, since we can just 'shrink' it to a constant map in the 2-cell we just attached(via, e.g. straight line map in the disk), $e^2_\alpha$. So imagine in your head you have your loop $\gamma_\alpha \varphi_\alpha \overline{\gamma}_\alpha$, now mentally 'shrink' $\varphi_\alpha$ so we're now homotopic to $\gamma_\alpha \overline{\gamma}_\alpha$, but that is obviously nullhomotopic.
Comment: Attaching a $2$-cell to $S^1$ in the normal way seems to give a space homeomorphic to $D^2$, not $S^2$, though this would be homeomorphic to a hemisphere.


Configuring IIS ARR for backend client certificate authentication

Question: I have an IIS server configured with ARR to reverse proxy requests to a backend server. The backend server requires client certificate authentication, however, it only needs to authenticate the reverse proxy (not the end user).
The end user authentication is passed inside the content of the request and is not the problematic part.
End User -->-- IIS with ARR -->(mutual SSL)>-- Backend web server
How does one configure the client certificate in IIS or ARR?
When searching around, I often find questions and threads related to forwarding the client certificate from the end user to the backend server and this is not possible. Further, these usually indicate to turn off client certificate authentication on the backend server but this must remain on.
Here are some questions I found, but they all relate to the end-user client certificate:

https://stackoverflow.com/questions/22805705/client-certificate-authentication-with-reverse-proxy
http://forums.iis.net/t/1157253.aspx
http://forums.iis.net/t/1175264.aspx
Answer: Chances are Microsoft ARR is using CAPI to store its certificates, but there are no guarantee that ARR will use it even if you make the certificate available to it. Client side authentication requires extra code, and your requirements are not that common. It could have been overlooked and left behind...
To make your client certificate available to a service, you have to edit its "MY" CAPI store. Run mmc.exe from an elevated prompt and add the certificate snap-in. You will have to select which CAPI store to use. Select the computer's store.  Import your certificate in the "Personal certificates", making sure you imported the private key with it (it will say so when you go back and view the certificate you imported).
If adding your certificate to the computer store does not work, try the service store. This will be required if ARR runs with its own identity.
I also had an issue with AD-LDS where the service did not have read access to the private key. This article was helpful, but it might be too far off for ARR. Look for ADAM special case in that page, the command you are looking for is
Certutil –V –Verifystore MY 0


How to put view results in an entity reference field?

Question: So the scenario is like this:
I have to create a "node" which has an entity reference field which can hold multiple values. I am looking for a way to be able to select view results to be stored in the entity reference field and I do not know how to do that in Drupal 8.
For Drupal 7 there was this module which does what I need https://www.drupal.org/project/entityreference_view_widget
I have tried doing it the custom way by creating views and placing them on the same page as the node create and then getting the resulting values with ajax to store in the field but I do not believe that is the best way to go about it as it does not seem reliable.
Any advice is appreciated.
Comment: The closest match to the link you shared is to use the [Entity Browser module](https://www.drupal.org/project/entity_browser).
Comment: What are the view results that you are trying to store?  With just the core modules, you can use a custom view to set an entity reference field, including the case of multiple values.
Comment: For example I have a view with lots of filters which returns users, and from the view I need to use checkboxes to select which users I want to select to save in my reference field.
Comment: Thank you @sonfd. That was exactly what I was looking for!
You should post it as an answer so I can mark it.
Answer: The closest match to the link you shared is the Entity Browser module.

Goal of this module is to provide a generic entity browser/picker/selector. It can be used in any context where one needs to select few entities and do something with them.

The module allows you to build your own widgets (similar to the Media Library) to use with entity reference fields or in WYSIWYGs, via integration with the Entity Embed module. You can create widgets with multiple options, an option to create new content (with the entity_form submodule), and select existing content via view displays.


Need to alter "No Paragraph added yet. Select a Paragraph type and press the button below to add one." message - Paragraph Module

Question: I am using paragraph bundle and I want to alter this message with my custom text "Please click on below button to add data".
Answer: You need to patch the contrib module.
Patch here works for me.


I can't find ConvexHull in scipy.spatial

Question:
Edit: As far as I can tell it's an issue with the build, I haven't figured out exactly what yet, but I've narrowed it down to that. For anyone reading this, try the suggestion in the marked answer first.

I'm trying to use the ConvexHull function from the scipy library to compute the convex hull for some points, but scipy.spatial.ConvexHull doesn't seem to exist.
The documentation has this as an example:
from scipy.spatial import ConvexHull
points = np.random.rand(30, 2)   # 30 random points in 2-D
hull = ConvexHull(points)

I tried to use this example in my project but couldn't get it to work..
I typed in the appropriate import line but ConvexHull was not found, PyCharm underlined the ConvexHull reference in red, and a mouse-hover shows a 'not found' message.
I've found various mentions on SO about different methods that might be required for importing and using parts of scipy, which I've tried and none of them seem to work, including the import line in the docs example.
I'm running Python 3.6 inside a clean PyCharm venv that I've just created. The pip install of scipy worked fine and scipy is appearing when I try to import it, as is spatial... but ConvexHull doesn't seem to exist.
I'm using scipy 1.1.0, and I've tried using the import that a deleted answer provided...
from scipy.spatial.qhull import ConvexHull... but this didn't work.
Alternately, if this won't work then I am willing to use a different library if possible.
Comment: *"... but couldn't get it to work."* Please include the exact, complete error message in the question.
Comment: What's the OS?  linux?
Comment: OS is Windows 10
Answer: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html
Did you try
from scipy import spatial
spatial.ConvexHull

In 1.0.1 both of these work
In [2]: spatial.qhull.ConvexHull?
In [3]: spatial.ConvexHull?

Glancing at the github issues, there may be some build issues, involving cython versions, that may prevent building the qhull file.
https://github.com/scipy/scipy/issues/8562 - CI: Appveyor builds fail because it can't import ConvexHull from spatial.qhull

I upgraded to 1.1.0, and had no problem accessing ConvexHull.
Comment: Thanks for your answer hpaulj, as far as I can tell it's an issue with the build.


Como retornar registros relecionados entre tabelas em laravel

Question: Tenho 2 tabelas cidade e estado possuo o estado paraná e gostaria de saber como faço para retornar todas as cidades relacionadas ao  estado Parana de forma simples sem ter que fazer um laço de repetição
Tipo
$estados = App/Estado::all();
$cidades = App/Cidade::all();
foreach($estado as $estados)
{
    if($estado->id === $cidade->id)
    {
    }
}

não testei o código mas a maneira que sei seria essa tem alguma maneira mais simplificada
Comment: Primeiramente, bem vindo à comunidade. Existe forma mais simples sim, use os models :D vou preparar algo pra você em uma resposta, você poderia postar a estrutura das suas tabelas?
Comment: Cidade id nome fk_estado_id
Comment: Estado id nome sigla
Comment: Você conseguiu resolver?
Answer: Vamos ao trivial:
rode os seguintes comandos:
php artisan make:model Estado -crm
php artisan make:model Cidade -crm
Desta forma você fará o model, migration e o controller em apenas um comando
Você terá as seguintes migrations:

Estado

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEstadosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('estados', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('nome',500);
            $table->string('sigla',2);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('estados');
    }
}

Cidade

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCidadesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cidades', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('estado_id')->unsigned();
            $table->string('nome',500);

            $table->foreign('estado_id')->references('id')->on('estados')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('cidades');
    }
}

Dessa forma você já referenciou a chave estrangeira e definiu suas tabelas. Rode sua migration usando o comando php artisan migrate.
Abra o model Cidade e adicione o seguinte código:
public function Estado()
{
    return $this->belongsTo('App\Estado','estado_id');
}

Abra o model Estado e adicione as seguintes linhas:
public function cidades()
{
    return $this->hasMany('App\Cidade','estado_id');
}

Agora basta que você utilize as próprias ferramentas do laravel para que faça os filtros da forma que você precisa:
Exemplo de uso aplicado em blade:
@foreach($estados as $estado)

    {{$estado->nome}}

    @foreach($estado->cidades as $cidade)

            {{$cidade->nome}}

    @endforeach
@endforeach


Ainda é recomendado tratar o IE (Internet Explorer) nos testes de CrossBrowser?

Question: Hoje sabemos que 80% ou mais dos acessos aos sites são mobile, e que as tecnologias estão avançando cada vez mais nesse sentido como os PWA e o AMP.

Fonte: http://zydigital.com.br/radar/dados-da-comscore-sobre-acessos-a-internet-destacam-o-mobile-apps-e-entretenimento/
Além disso, pensando em Graceful Degradation versus Progressive Enhancement, até que ponto visando a UX, eu devo "prejudicar" a maioria dos usuários evitando novas tecnologias em prol de 5% ou menos dos usuários que ainda usam IE?

Fonte: https://caniuse.com/usage-table
No Windows atual o IE não é o browser padrão, e no próximo Windows se quer ele vai existir... Existe alguma razão para ainda testar no **IE?**
Pensando em UX, é aconselhável fazer o usuário migrar para uma plataforma mais moderna deixando de dar suporte para as antigas? (pratica aplicada pela própria MicroSoft)
Answer: Dê suporte ao usuário, e não ao navegador.
É fato que a maioria dos acessos hoje se dá via mobile (fonte). Mas você deve analisar primariamente o público do seu site. A audiência é o que importa. É esperado que um site como Stack Overflow, direcionado para programadores, tenha mais acessos desktop com browsers de última geração. Mas também é esperado que um site de uma comunidade de tricô tenha browsers nem tão atualizados. E não só o exemplo clichê do tricô, mas também existem empresas em que o uso de Internet Explorer é mandatório (exemplo).
Para medir qual é o navegador, sistema operacional, e outras métricas do seu usuário, você pode usar uma ferramenta como o Google Analytics em seu site.
Em uma perspectiva de experiência do usuário, existem algumas opções quando falamos em navegadores antigos, tendo em base as heurísticas da usabilidade:

Em hipótese alguma culpe o usuário. A culpa do navegador não ser suportado pelo seu site é sua e não do seu usuário. Ele pode estar usando Netscape 8, a culpa ainda é sua.
Apresente uma versão utilizável do seu site sem JavaScript ou CSS. Tenha certeza que é melhor que deixar seu usuário com uma página em branco (como é o caso de single-page applications que não conseguem carregar seu JS).
Mostre uma mensagem na página dizendo ao usuário que seu site parece ruim por conta do navegador não suportado. Uma mensagem, e não um modal, pois não queremos quebrar o fluxo.
Se uma parcela considerável dos seus acessos vem de navegadores não suportados, adicione o mínimo de CSS e JavaScript que seja suportado por esses navegadores para melhorar a experiência.
Answer: Eu partiria para a comunicação oficial que o suporte iria acabar para este tipo de browser pois está sendo prejudicial para o restantes dos usuários e tornando mais caro sua manutenção. Obviamente esses 5% são financeiramente estratégicos para o negócio ? se não, manda ver na comunicação.
Em resumo, a partir do momento que o browser IE foi descontinuado, já não é mais recomendado. Faça grande uso de estratégias que propicie os usuários a migrarem de browser, mostre os benefícios.
Lembre-se que é comum essa prática, muitos desistiam de suportar versões antigas do Internet Explorer, cortando uma fatia significativa de possíveis consumidores. Isso acontece com os celulares Android, IOS e por ai vai.
Abraços!


Does the set of all $C^\infty$ functions having compact support an ideal in $C(\Bbb{R})$?

Question:
Question. Let $C(\Bbb{R})$ denote the ring of real-valued continuous functions on $\Bbb{R}$, with pointwise addition and multiplication. Which of the following form an ideal in this ring?

The set of all $C^\infty$ functions having compact support.
$C_c(\Bbb{R})$
The set of all continuous functions which vanish at infinity.

My Solution.

True.(Follows from: $Support(f+g) \subset support(f) \cup support(g)$ also $Support(fg) \subset support(f)$ and $support(f):=cl\{x | f(x) \neq 0\}$)
False. (Take, $f(x)=\frac{1}{1+x^2} \in C_0(\Bbb{R})$ and $r(x)=1+x^2\in C(\Bbb{R})$, then $rf$ doesn't belong to $C_0(\Bbb{R})$).

But I cannot find a counter example in (1) as I did in  (3) ...
Suppose I choose $f(x)=1$ in $[-1,1]$ and take $r(x)=|x|$. Then $rf(x)=|x|$ and $rf$ doesn't belong to $C_0(\Bbb{R})$. But the problem is if I define $f=0$ outside $[-1,1]$ it wouldn't be smooth...
So I think I have to find another counter example. Can any one please help me to find an counter example here?
Answer: There exists a $C^{\infty}$ function $f$ such that $f(x)=1$ for all $x \in (-1,1)$ and $f(x)=0$ for $|x| >2$. [Construction of such functions using $e^{-1/x}$ is standard].  If you multiply this by $|x|$  you will go out of $C^{\infty}$.


c# pass cmd args to existing instance instead of new instance

Question: I have a C# Windows Forms application that is manually started and then mostly runs in the background.  In my registry, this program is set up to handle a "dstel" url protocol.  That is, href="dstel:1234567890" will successfully open my program.
The issue is that my program needs have only one instance running at any given time.  My research suggests that in order to ensure that multiple instances are not operating simultaneously, I should use a mutex (courtesy of How to check if another instance of the application is running).
Assuming that works, I am now left with what to do when someone clicks on my special dstel link in a webpage.  What I need is how can I redirect the command line input to method xyz() of my already-running application?
To be clear, I'm envisioning the following events, in order:

I manually start instance A of my program
I click on the dstel link
Instance B of my program starts
Thanks to the mutex, instance B of my program realizes that instance A is already running
Instance B passes its command line args to method xyz() of instance A. <<<< My issue
Instance B exits

I have a few things in mind that might work, most notably either using a helper application or setting up a named pipe via WCF.  I am open to any suggestions you may have.
Thanks!
Comment: Look at http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.applicationservices.windowsformsapplicationbase(v=vs.110).aspx.  Specifically its IsSingleInstance property and OnStartupNextInstance method
Comment: @jamesthollowell that did it, thanks!  if you put that in an answer I'll mark it as correct.
Answer: Look at http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.applicationservices.windowsformsapplicationbase(v=vs.110).aspx
If you override this class for your base app and set its protected IsSingleInstance property as true, you can override the method OnStartupNextInstance(), which gets called anytime a subsequent instance of your program is started.
This should do it like you want!


Change the disabled status of a form element via Ajax

Question: I have a form built with the Form API. I have a field which is, at first, disabled. I want to change the status of that field to enabled when the user selects another contiguous field.
I have a working example of changing the callback URL of Ajax complete of that field, so the form is making a kind of OnChange and working well, but for some reason I am not able to change the disabled status.
Code. Here the 2 elements, first brand and next the model, which is disabled at the beginning.
 $form['brand'] = array(
'#type' => 'select',
'#title' => t('Brand'),
'#options' => $brands,
'#default_value' => $brand,
'#ajax' => array(
    'callback' => 'hook_models_update',
    'wrapper' => 'models_wrapper',
    'progress' => array(
        'message' => '',
        'type' => 'throbber',
    ),
),
);

 $form['model'] = array(
    '#type' => 'textfield',
    '#title' => t('Model'),
  //    '#description' => 'Please note available models change based on the brand selected.',
'#required' => FALSE,
'#autocomplete_path' => 'providers/autocomplete/' . $brand,
'#attributes' => array("placeholder" => t('Model')),
'#prefix' => '
',
'#suffix' => '
',
'#disabled' => TRUE,
);

Now the code for the "onChange" behaviour, which is a "throbber" called hook_models_update:
function hook_models_update($form, &$form_state) {
    unset($form_state['input']['model'], $form_state['values']['model']);
    $brand = $form_state['values']['brand'];
    $form['model']['#autocomplete_path'] = 'providers/autocomplete/' . $brand;
     $form['model']['#enabled'] = TRUE;
    // $form['model']["#disabled'] = FALSE
    return form_builder($form['#id'], $form['model'], $form_state);
} // function

I have tried with #enabled = TRUE and with #disabled = FALSE, with no successs.
Comment: I haven't seen `form_builder` used in an AJAX callback before, is that something you've seen in core/contrib? Not saying it's wrong, just never seen it. Usually you just return the element (`return $form['model'];`) It's definitely `'#disabled' => FALSE` BTW, there isn't an `#enabled` property
Comment: I don't recall where I saw it, it took me quite a lot to find it, and it is working perfectly in spite of all. I have solved the problem, I didn't find the right way of making the question, finally I found the solution, of course in this site.
Comment: can you post the answer?
Comment: Yeah I'm sure it'll work (if you return the element directly I'd wager the form system runs it through `form_builder` anyway). What was the problem out of interest?
Comment: It was done to refresh the autocomplete path of the form, so when the user select a brand, the autocomplete model URL changes dinamically (Javascript) so it only suggests those models of that selected brand. I didn't find more than this solution after quite a lot of time searching !
Comment: Adrian, I have updated the post to reflect the answer. It was already in this site but I hadn't find it.
Answer: I found the solution here:
Enable DropDown using Ajax Call
The code finally gets this:
     function hook_models_update($form, &$form_state) {
         unset($form_state['input']['model'], $form_state['values']['model']);
         $brand = $form_state['values']['brand'];
         $form['model']['#autocomplete_path'] = 'providers/autocomplete/' . $brand;
         unset($form['model']["#attributes"]['disabled']);
         $form['model']['#disabled'] = FALSE;
         return form_builder($form['#id'], $form['model'], $form_state);
} // function

The trick lies in these two lines:
     unset($form['model']["#attributes"]['disabled']);
     $form['model']['#disabled'] = FALSE;

Apparently, there has to be an unset and not of #disabled, but #attributes - disabled. Why this is so convoluted is beyong my comprehension.
Comment: Good find! I'm pretty sure you've found a small bug in form API - `#attributes` should really be re-processed if there's a chance that property changes could have affected them
Comment: Well, I don't think I have found anything, cause the problem and solution was already in that post, I simply had a need. But I agree that if may be a small bug in the form API.


Como popular um objeto carregado com populate no Mongoose?

Question: Tenho uma duvida, se eu ja tenho uma query sendo populada no Mongoose, e ela for populada com um model que também tem relação, existe um meio de popular ele também?
Por exemplo:
Tenho meu model de Os:
const mongoose = require('../config/database');
const Schema = mongoose.Schema;

const OsSchema = new Schema({

    nome: {type: String, required: true},
    cnpjcpf: {type: String, required: true},
    dataservico: { type:Date, required:true},
    datagarantia: { type:Date, required:true},
    duracao: { type:Number},
    dificuldade: {type: Number},
    vendedor: {type: String, required: true},
    score: {type: Number, required: true},
    done: {type: Boolean, required:true},
    created: { type:Date, default:Date.now()},
    operador:[{type: Schema.Types.ObjectId, ref: 'Operador'}],
    pragas:[{type: Schema.Types.ObjectId, ref: 'Praga'}],
    produtos:[{type: Schema.Types.ObjectId, ref: 'Produto'}],
    reforco:[{type: Schema.Types.ObjectId, ref: 'Reforco'}],

},{toJSON:{virtuals:true}});

module.exports = mongoose.model('Os', OsSchema);

Mas meu model de reforco também tem relações:
const mongoose = require('../config/database');
const Schema = mongoose.Schema;

const ReforcoShema = new Schema({

    dataservico: { type:Date, required:true},
    duracao: { type:Date},
    done: {type: Boolean, required:true},
    programado: {type: Boolean, required:true},
    operador:[{type: Schema.Types.ObjectId, ref: 'Operador'}],
    pragas:[{type: Schema.Types.ObjectId, ref: 'Praga'}],
    produtos:[{type: Schema.Types.ObjectId, ref: 'Produto'}],
    created: { type:Date, default:Date.now()}

},{toJSON:{virtuals:true}});

module.exports = mongoose.model('Reforco', ReforcoShema);

Quando faço uma query nas Os e populo o reforco, ele tras o reforço normalmente, mas só trás o ID das relações do reforço, existe um meio de popular eles também?
Answer: Você teria que usar o populate para multiplos níveis. No seu caso você pode tentar passar um array contento regras de campos para popular.
Um exemplo para o seu caso, vamos popular o campo reforco e deste campo queremos tambem popular o campo operador:
Os.find({ nome: req.body.nome })     // filtro qualquer
  .populate({
    path: 'reforco',                 // populamos o "reforco"
    populate: [{ path: 'operador' }] // passamos um array com objetos
                                     // com os campos a serem populados
                                     // neste caso o campo "operador"
  })

Se quise popular mais campos, passe mais objetos para o array:
Os.find({ nome: req.body.nome })
  .populate({
    path: 'reforco',
    populate: [{ path: 'operador' }, { path: 'pragas' }, { path: 'produtos' }]
  })

Isso se chama Populating across multiple levels e podemos encontrar na documentacao do mongoose.
Comment: sim, mas fique atento para a questao de performance pois popular varios campos, podem afetar o desempenho da consulta.
Comment: Isso funciona em quantos níveis for necessário certo?


What is a Fake Book?

Question: The question was asked here as to why there are no Fake Books for Blues. But what is a Fake Book in the first place? What genres is it used in?
Comment: @ Matt L. Yes, but stack exchange is supposed to be a place to collect knowledge, even knowledge available elsewhere on the internet. I think the definition of a fakebook is worthwhile basic information to have available on this site. Want to write your link into an answer?
Comment: I've cleaned up some of the comments here.  The downvote tooltip says "This question does not show any research effort", which is true, so do so if you wish and move on.  You are also free to ignore it and/or upvote, it's your choice.  This is not the place to argue about it.
Comment: Have you read [this](http://en.wikipedia.org/wiki/Fake_book)?
Answer: The first "fake books" were in fact sold and distributed illegally, but that is not why they were called Fake Books. Each piece of sheet music in a Fake Book is merely a "lead sheet" of just the melody and the chord progression. It is not a full arrangement with parts written out for each musician. Consequently, musicians look at a Fake Book lead sheet and they have to "fake" their parts, or make them up as they go along. This is essential to jazz, but it was not that way originally.
At the Woodwind and Brasswind music company, they have a page on their website, "What is a Fake Book?" which includes this: "Usually, there is no arrangement, no intros or endings, no specific instructions on "how" to play the song. Hence, the word "fake" – musicians are supposed to take the basic information and simply "fake" it."
The Wikipedia article on the Fake Book says this: "...the minimal information needed by a musician to make an impromptu arrangement of a song, or "fake it."
Musicians today often forget that the classic jazz songs in Fake Books and used by bands for improvisation did not start out that way. Most jazz standards were originally songs from Broadway musicals from prior decades. The original versions of these songs were arranged for a full orchestra that accompanied the singers, and there was no improvisation. There would be a part completely notated for each instrument in the orchestra, and there would be a conductor's score.
But the purpose of the Fake Book and the lead sheet are to re-purpose (and usually re-harmonize) a fully-composed orchestral piece for use by a small jazz band that improvises. Thus the original, elaborate Broadway form of the song is transformed into another kind of musical art as a template for jazz improvisation.
Furthermore, most pieces in the best-known Fake Books only provide a lead sheet for the chorus of a song from a Broadway musical. The original song might also have an extensive intro, with lyrics, and several verses, and a bridge, and a coda. When jazz musicians improvise on a Fake Book chart, they are usually only concerned with playing the chorus and repeating it many times so that different members of the band can take solos.
Here is an example: the original fully-orchestrated version of "My Funny Valentine" which is from the musical Babes in Arms by Rodgers and Hart from 1937. Notice that it has whole sections, and lots of lyrics, that are omitted from any version of this song you've ever heard from a jazz band.

Now here is the classic jazz recording of "My Funny Valentine" by Chet Baker from 1952. You will realize that it omits the entire first section (called the verse in Broadway parlance) of the original song. This recording sounds to me like something improvised from a fake book lead sheet.

Now here is Miles Davis and his band doing a 15-minute version of "My Funny Valentine" which is essentially just the chorus of the original song, played over and over again for improvising. It's beautiful and it's excellent jazz, and it is undoubtedly something the band improvised or developed from a simple lead-sheet fake book chart, rather than from the original full arrangement by the composer Richard Rodgers.
Comment: Fake books are not restricted to Broadway tunes and the like.  Some of them give the melody and chords of jazz tunes, which have never had anything BUT a "head" arangement.
Comment: I did not say that Fake Books are restricted to Broadway tunes. I said that "Most jazz standards were originally songs from Broadway musicals". Of course contemporary Fake Books contain charts for many new tunes that are not historical jazz standards. I'm just trying to point out that there is a history to music that came before the wonderful original melodies of later composers such as Herbie Hancock, John McLaughlin, or whomever.
Comment: For the complete history of fake books, see *The Story of Fake Books: Bootlegging Songs to Musicians* by Barry Kernfeld.
Answer: A Fake book  is book that contains music sheets for songs. Usually they contain chords and melody, but sometimes lyrics as well. These kind of books are really famous for jazz repertoire, but there have also been fake books for blues/latin/rock etc.
They were called Fake Books, because the people that wrote and publish them didn't have the royalties for the songs.
The Fake books were replaced by Real Books, which means that royalties were paid to the composers. Τhere have also been many editions, like the Real Book in C,Eb,Bb and Bass Clef.
Comment: As a performer, I find these kind of books really helpful. The Jazz Real Book (at least) has the most common jazz standards , so that you won't have to search the net to find myriads of false music sheets
Comment: @WheatWilliams Interesting! There's much more to them than I thought, thanks for the info. Seems that they were also an "underground" thing, illegal, and the first ones had many chord changes wrong. I wonder how many of those mistakes ended up being absorbed and accepted as features of the original song.
Comment: @WheatWilliams That doesn't sound right. The lead sheets contain the harmony, the melody, and sometimes the lyrics, and at least in a blues and jazz context (which the fake and real books come from) that is all to be expected since everything else is improvised. It's not that they have to "fake" their parts, it's not that the lead sheet is incomplete. Unless I'm missing something here?
Comment: I should turn my comments into a separate answer later.
Comment: The first "Real Book" was an underground compilation of jazz tunes and chords.  The name is now applied loosely to a number of publications, including both jazz and commercial tunes.  There are some that cover blues tunes. Google "blues real book".

What is a Fake Book?


Aplicar recursividade num batch script

Question: Há algum tempo atrás me surgiu a necessidade de utilizar o Microsoft Office Document Imaging para converter um modelo de documento criado no Microsoft Word como medida de prevenção anti-cópia do modelo em si (posicionamento, medidas, definições e etc.).
Porém o aplicativo em questão, para quem não conhece, é bem espartano, lento e com umas restrições esquisitas demais para uma GUI. Felizmente, a funcionalidade que eu precisava dele, podia ser executada em linha de comando.
Nunca fui muito fã de batch scripts, mas mesmo assim optei por criar um arquivo .BAT para automatizar a OCR dos arquivos MDI previamente gerados pela impressora virtual disponibilizada pelo aplicativo.
Como a sintaxe dos batch scripts já era coisa antiga quando ganhei meu primeiro computador, nunca me dei ao trabalho de aprender mais do que o necessário para instalar o Windows 98 (na época) e acabei com o seguinte arquivo:
<code>@echo off

set filesCount=0

echo Performing OCR over files
echo.

for /r %%i in (*.mdi) do (

set /a filesCount+=1

echo Curent file: %%i

"C:\Program Files\Common Files\Microsoft Shared\MODI\11.0\MSPVIEW.EXE" -f %%i

echo OCR performed succesfully
echo.

)

echo.
echo OCR performed over %filesCount% files found
echo.

pause
</code>
Funciona bem, mas eu tenho de duplicar (ou mover) o arquivo .BAT pra cada diretório antes de executá-lo. E como a execução é aplicada em milhares de arquivos estruturados hierarquicamente em diversos subníveis, isso se torna uma tarefa tediosa quase não fazendo valer a pena utilizar o dito script.
É possível modificar esse script para que este opere recursivamente? Dessa forma, eu o armazenaria no diretório-pai de todos os subníveis e executaria uma só vez.
Comment: Testei aqui e a sua bat já esta executando o comando recursivamente, basta executar ela no diretório raiz...
Comment: @Bruno quer executar esse comando recursivamente sobre todo o seu diretório raíz?
Comment: @Jader: Sério? Confesso que nunca experimentei pra ver o que aconteceria. Talvez porque o PC onde usaria é quse movido a carvão. Kyllopardium: Não no diretório raiz, mas a partir de um raiz. Algo como o ./ do *nix. De onde se encontra o .BAT pra frente (ou "pra dentro")
Comment: veja o teste que fiz: [print](http://pt-br.tinypic.com/view.php?pic=1zdw16v&s=8#.U-VNYKx0y70) obviamente eu retirei a linha com o executável, mas pode ver que ele pega todos os arquivos em todos os diretórios...
Comment: Vou experimentar só segunda-feira, no serviço. Nesse interim, se quiser responder com esse teste, ficaria feliz em avaliar e marcar como resolvido. Mas só segunda-feira :p
Answer: De acordo com um teste que realizei aqui, sua bat já funciona de forma recursiva:
teste.bat
<code>@echo off

set filesCount=0

echo Performing OCR over files
echo.

for /r %%i in (*.mdi) do (

set /a filesCount+=1

echo Curent file: %%i

echo OCR performed succesfully
echo.

)

echo.
echo OCR performed over %filesCount% files found
echo.

pause
</code>
resultado:

Obs.: a linha <code>"C:\Program Files\Common Files\Microsoft Shared\MODI\11.0\MSPVIEW.EXE" -f %%i</code> foi removida para evitar erros durante a execução, pois não possuo esse executável.
Comment: Caramba... Se eu soubesse que levariam tantos dias até eu poder testar o script não teria dito "segunda feira". Mas funcionou perfeitamente, já era recursivo e eu nem sabia. E o responsável por isso é a flag **/r**

Aplicar recursividade num batch script


Bash. Replace with sed. End of line problem

Question: I am trying to search and replace in file using sed. But sed seems to hate end of line special char.
text=$(shuf text.txt)
echo "This is text:
$text"
sed -i "s~%text%~$text~g" t.txt

Here is what I get:
This is text:
 line 2
 line 1
 line 3
 line 4
sed: -e expression #1, char 15: unterminated `s' command

I've tried to replace \n with \r but result is not satisfying at all.
There is an option to do tr '\n' , '$' and then do it backwards afterwards but it doesn't seems right.
Help?
Comment: In `sed` commands end with a newline. A newline is command delimeter inside `sed`. So `s~blabla\n` is interpreted by sed as a single command. `but it doesn't seems right.` - that is actually a really good idea, I would say go with it. To be extra safe use unreadable character, like `tr '\n' $'\01'`
Comment: Thank you. So there is no way to avoid tr?
Comment: A better way is to read the file content when you encounter `%text%`. Also note that `sed` will parse `\r` `\n` and etc. inside `$text` and substitute them, so you may have problems with "\". And sometimes that's also solved with another escaping sed... `sed 's@%text%@$(<<<"$text" sed 's#\\#\\\\#g')/`.... But, as always, [awk](https://unix.stackexchange.com/questions/141387/sed-replace-string-with-file-contents) solution looks neat.
Answer: Using sed and bash
Since you are using bash, try:
sed -i "s~%text%~${text//$'\n'/\\n}~g" t.txt

${text//$'\n'/\\n} is an example of bash's pattern substitution.
In this case, it replaces all newline characters with with backslash followed by n which sed will interpret as a newline.
Example
Consider this text variable:
$ echo "$text"
line 2
 line 1
 line 3
 line 4

And this input file:
$ cat t.txt
start
%text%
end

Now, run our command:
$ sed "s~%text%~${text//$'\n'/\\n}~g" t.txt
start
line 2
 line 1
 line 3
 line 4
end

To change the file in-place, of course, add the -i option back.
Using awk
With the same text variable and t.txt file as above:
$ awk -v new="$text" '{gsub(/%text%/, new)} 1' t.txt
start
line 2
 line 1
 line 3
 line 4
end

Comment: Thank you! Very elegant. :)


How to override php session expire on Android webview

Question: I'm new in Android development. Currently i'm working on webview app.
The webview (website) has a session timeout for example 10 minutes. When the session expired, it will redirect to login page. Is that possible, if the android handling/override the session? I don't want the session expire when run on app.
Currently I've tried used CookieManager but it seem doesn't work.
Answer: What I'm currently doing is this:
Get your android app to send the unique device id via post
<code>String deviceId = Settings.Secure.getString(MainActivity.this.getContentResolver(),
                Settings.Secure.ANDROID_ID);

        try {
            postData = "deviceId=" + URLEncoder.encode(deviceId, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        mainWebView.postUrl(postUrl,postData.getBytes());
</code>
Then what im doing is at the home page (launched in android app) I check to see if the android id is in the database and belongs to a specific user.
<code>//This is just pseudo code actual implementation depends your database and user login setup
if(!isset($_POST["deviceId"]){
    //no deviceId sent
    //so redirect to login page
}
//check database for deviceId and see if it has a user id associated with  it
if(deviceId has a userID){
    //load user info / log the user in
}
</code>
And then your user never has to log in on his phone again unless you put some additional logic in to remember the first time they logged in on the app and have it expire a week later.


quaternions - understanding a formula

Question: Quaternions are new for me. I am trying to understand the following formula:

What are:

$\large{q^x}$ ? I don't think it is a power.
$\large{q^t}$ ? just a transposition of the quaternion $q$?

Do the subscripts next to the $q's$, represent entire rows or columns of the quaterion in question?
This should normally give me a $3 \times 3$ matrix $R$, if I understood it correctly.
source: http://www.dept.aoe.vt.edu/~cdhall/courses/aoe4140/attde.pdf
page 4-14
Answer: Addressing your questions in order:

$\mathbf q^\times$ is the $3\times3$ matrix that represents the operation of taking the cross product with $\mathbf q$, i.e. $(\mathbf q^\times)\mathbf x=\mathbf q\times\mathbf x$.
No, $\mathbf q$ is not a quaternion. The quaternion is being denoted by $\bar{\mathbf q}$, and $\mathbf q$ is the vector of its components $1$ to $3$. The symbol $^\top$ represents transposition.
The subscripts refer to the four components of the quaternion, which are here being indexed with $1$ to $4$.

quaternions - understanding a formula


How to whitelist a directory in Apache configuration

Question: In Wordpress, one of the few effective ways at reducing server load is to whitelist individual clients to /wp-login.php and /wp-admin/:
<Directory /wp-admin>
    order deny,allow
    deny from all
    allow from 10.1.1.50
    allow from ...other ips...
</Directory>

But I don't want to have to edit and reload Apache to change this list. In my Virtual Host, I want:
<Directory /wp-admin>
     RewriteEngine On
     RewriteMap hosts-allow txt:/var/www/html/wp/wp-admin/hosts.allow
     RewriteCond ${hosts-allow:%{REMOTE_ADDR}|NOT-FOUND} =NOT-FOUND [AND]
     RewriteCond ${hosts-allow:%{REMOTE_HOST}|NOT-FOUND} =NOT-FOUND
     RewriteRule ^ - [F]
</Directory>

But:
[root@blah httpd]# service httpd reload
Reloading httpd: not reloading due to configuration syntax error
                                                       [FAILED]
[root@blah httpd]# apachectl -S
Syntax error on line 34 of /etc/httpd/sites-enabled/example.org.conf:
RewriteMap not allowed here

So is there a way to accomplish what this says that doesn't require RewriteMap or do I need to write a new module?
Answer: Create .htaccess file and put allowed IP addresses there. RewriteMap is not allowed within Directory.
Comment: Ok. This does require adding an `allowoverride` to the virtualhost config. But it would allow dynamic changes to the access list without reloading apache.
Comment: Yes, this is only way for standard configuration. You can also use modsecurity and specify file in it's configuration, but it will be much complicated.
Answer: Try this:
    RewriteMap ipslist txt:/full/path/to/iplist.txt
    RewriteCond %{REMOTE_ADDR} ^(.*)$
    RewriteCond ${ipslist:%1|black} ^black$ [NC]
    RewriteRule (.*) - [F]

And your file should look something like this:
192.168.0.12 ok
127.0.0.1 ok
[...]


Different ways to calculate conditional probability of independent events

Question: Say we have TWO tests for cancer. Each test has the same probabilities of being right/wrong for cancer/no cancer. What is the probability of getting two positive test results?
In what follows, I'll use C for "has cancer", "+" for a positive test result, "++" for two positives (I don't distinguish between the tests because they have the same probabilities).
A. Use the formula for total probability:
P(++) = P(++|C) $\times$ P(C) $+$ P(++|$\neg$C) $\times$ P($\neg$C)
Since each test is independent of the other, apply the formula for joint probability:
= P(+|C)$^2$ $\times$ P(C) $+$ P(+|$\neg$C)$^2$ $\times$ P($\neg$C)
B. Since each test is independent of the other one, the joint probability is the product of the probability of each (which is the same):

P(++) = P(+)$^2$
Then, apply the formula for total probability to each:
= [P(+|C) $\times$ P(C) $+$ P(+|$\neg$C) $\times$ P($\neg$C)]$^2$
Obviously, the two are not equal. Why not? And which one is correct?
Answer: The two tests are not absolutely independent.  They are conditionally independent on C.
Thinking about it intuitively, if you test positive for the first test, we can predict that it's more likely you'll test positive for the second test, hence the two are not absolutely independent.
However, given that you know that you have cancer, the two tests are independent i.e. knowing the outcome of the first will not affect our prediction of the outcome of the second.  Hence, "conditional independence".
Answer: Jason's answer is certainly true, but I don't think it fully explains the reason your formulas don't match up, but only why you wouldn't want to apply this logic in the specific case of cancer tests.
Instead of + and ++, let's generalize this to events $A,B,C$. Your second calculation assumes $P(AB)=P(A)P(B)$, i.e. that $A$ and $B$ are marginally independent, which is in agreement with your assumption (although that assumption would not hold for cancer tests).
Your first calculation, however, assumes $P(AB|C) = P(A|C) P(B|C)$, i.e. that $A$ and $B$ are conditionally independent given $C$. These are NOT the same and in general one does not imply the other. This is easy to see in the Gaussian case: Gaussian r.v.s are independent if and only if their correlation is 0, but they are conditionally independent given another if and only if their partial correlation is 0. Setting up a correlation matrix with some zeros and inverting it to find the partial correlation matrix is a good way to see how these two quantities relate and that they are NOT interchangeable.


RAID controller question: NVDIMM or not?

Question: I am in the market for a new RAID controller for a Dell server, and I have a choice between "PERC H700 512mb Cache" and "PERC H700 512mb NVDIMM Cache". There is a $200 difference between the 2 cards, can anyone recommend either one? Is the second option worth the extra $200?
Answer: NVDIMM is a new technology that avoids the need for a battery-backed cache by preserving the data in memory even in the event of power loss.  This article seems like a reasonable primer to the technology.
As to whether it's worth it, I'm not sure.  I've never had a reliability problem with the BBU in a RAID controller, nor have I had a server down for long enough that the battery fully discharged, but if that was something that made you nervous, it might be worth the extra $200 for peace of mind.  I doubt the performance will be substantively different.


Including PHP code in WordPress CSS files

Question: I want to know how to run the PHP function in a WordPress CSS file. Because I want to add images by running the PHP function.
<code>**Below are my CSS codes:**

    .hero {
      width: 100%;
      height: 100vh;
      background: URL(<?php echo get_theme_mod( '......' ); ?>) top center no-repeat;
      background-size: cover;
    }
</code>
Comment: I would suggest editing your css using Javascript (which will be usable within your .php file).
Answer: css files are not parsed by php interpreter. only files with .php ending will processed by php. you have to type the full path to the backgroundn image on your own.


Why do the residuals from a factor analysis have mean zero?

Question: The model is given below:
\begin{align}
y_1 - \mu_1 &= \lambda_{11}f_1 + \lambda_{12}f_2 + \dots + \lambda_{1m}f_m + \epsilon_1  \\
y_2 - \mu_2 &= \lambda_{21}f_1 + \lambda_{22}f_2 + \dots + \lambda_{2m}f_m + \epsilon_2  \\
 &\vdots  \\
y_p - \mu_p &= \lambda_{p1}f_1 + \lambda_{p2}f_2 + \dots + \lambda_{pm}f_m + \epsilon_p  \\
\ \\
\text{For }j &= 1,2,\ \dots,\ m  \\
E(f_j) &= 0,\ {\rm Var}(f_j) = 1,\ {\rm Cov}(f_j, f_k) = 0,\ j \neq k  \\
\ \\
\text{For }i &= 1,\ 2,\ \dots,\ p  \\
E(\epsilon_i) &= 0,\ {\rm Var}(\epsilon_i) = \psi_i, {\rm Cov}(\epsilon_i,\epsilon_k) = 0, i \neq k
\end{align}
I understand why each $\epsilon_i$ have different variances, but why do they have $0$ mean?
Comment: So, we want to have $E(y_i - \mu_i) = 0$, and $E(f_j)=0$, then $E(\epsilon_i)$ should be $0$. Is that right?
Comment: How would you identify the $\mu_i$ otherwise?
Comment: I mean why not $\phi_i$?
Comment: You lost me there--there are no references to any "$\phi_i$" in your post.
Comment: I meant why not 1,2 or some other number.
Comment: I think $\epsilon_i$ is just like an error, so they can follow any distribution, don't they?
Answer: It is an assumption of the model. Think of it this way, in your model you have one of your equations written as:
\begin{align}
y_1 - \mu_1 &= \lambda_{11}f_1 + \lambda_{12}f_2 + \dots + \lambda_{1m}f_m + \epsilon_1
\end{align}
The intention of writing something like this is that you think $y_1-\mu_1$ can be modeled as a linear combinations of $m$ factors. If this is true, then in the best case (probably impossible) you will get that the error of your model is 0. However, since you know it is almost impossible to find statistical models that work 100% of the time (otherwise you have determinism), then you should get an error close to zero, and since the error is a random variable, you can assume that it has a first moment (i.e mean) equal to zero.


How to prove that $ \frac{1}{x^{k}} $ is analytic in $ \mathbb{R} \setminus [0] $

Question: I want to prove that $ \frac{1}{x^{k}} $ is analytic in $ \mathbb{R} \setminus [0] $
for |x|<1  its obvious. i want to prove for the rest of $ \mathbb{R} $
so i tried that:
I proved by induction that $ \left(\frac{1}{x^{k}}\right)^{(n)}=\frac{\left(k+n-1\right)!}{\left(k-1\right)!}\frac{\left(-1\right)^{n}}{x^{\left(k+n\right)}} $
then, I wrote lagrange reminder of the function
$ |R_{n}\left(x\right)|=|\frac{\frac{\left(n+k\right)!}{\left(k-1\right)!}\frac{\left(-1\right)^{n+1}}{c^{\left(k+n+1\right)}}}{\left(n+1\right)!}\left(x-x_{0}\right)^{n+1} $ = $ |\frac{\left(n+k\right)!}{\left(n+1\right)!\left(k-1\right)!c^{\left(k+n+1\right)}}\left(x-x_{0}\right)^{n+1}| $
so all i have to do in order to prove it, is to find $ \delta $ such for any $ x\in\left(x_{0}-\delta,x_{0}+\delta\right) $   the reminder goes to $ 0 $.
i dont know how to calculate this limit and find delta, any help will be great. Thanks
Answer: It's enough to prove that $f(x)=\frac{1}{x}$ is analytic; the general case follows by an easy induction, because products of analytic functions are analytic. Now, if $a\neq 0,$ we have $\frac{1}{x}=\frac{1}{a+(x-a)}=\frac{1}{a}\frac{1}{1+(x-a)/a)}=\frac{1}{a}\sum^\infty_{n=0}\left(\frac{x-a}{a}\right)^n$ and by uniqueness of power series, this is the Taylor series of $f$ about $x=a$ and it has radius of convergence $|a|.$We just need to check that the remainder $R_n(x)\to 0$ as $n\to \infty.$ We have $R_n(x)=\frac{f^{n+1}(\xi)}{(n+1)!}(x-a)^{n+1}$ for $a<\xi<x$ and $|f^{n+1}(\xi)|=\left|\frac{(-1)^{(n+1)}(n+1)!}{\xi^{k+1}}\right|\le \frac{(n+1)!}{a^{n+1}}$ so $|R_n(x)|\le \left(\frac{|x-a|}{|a|}\right)^{n+1}\to 0$ as $n\to \infty$ within its radius of convergence.
Comment: why do we need to verify that the remider goes to $ 0 $ ? Isnt the fact that $ \frac{1}{1+\left(\frac{x^{k}-x_{0}}{x_{0}}\right)} $ geometric series enough to verify it?
Comment: @Waizman Yes, if you know that the form of the remainder in this case is a geometric series. But I guess it's no problem to just do it.
Answer: You only need to check one derivative:  holomorphic implies analytic.  And $(1/x^k)'=-k/x^{k+1}$ is defined on $\Bbb R\setminus\{0\}$.
Comment: But it appears the OP wanted a direct proof, using series. Anyway,  "holomorphic implies analytic" requires the Cauchy Thm, and a manipulation of series so it really comes to the same thing, right?
Comment: @Matematleta I didn't read very carefully: I was thinking complex analytic.


django queryset returns wrong values from postgresql view

Question: I have a crazy bug somewhere in this setup.
The database is Postgres 9.1 and is pre-existing (not managed by Django).  In it there exists 1 table and then a number of fairly simple views, one of which is called valid_logins_dow_popularity as defined:
 =>\d+ valid_logins_dow_popularity
             View "public.valid_logins_dow_popularity"
   Column   |       Type       | Modifiers | Storage | Description
------------+------------------+-----------+---------+-------------
 logins_avg | double precision |           | plain   |
 dow        | double precision |           | plain   |
View definition:
 WITH by_dow AS (
         SELECT valid_logins_over_time.count, date_part('dow'::text, valid_logins_over_time.date) AS dow
           FROM valid_logins_over_time
        )
 SELECT avg(by_dow.count)::double precision AS logins_avg, by_dow.dow
   FROM by_dow
  GROUP BY by_dow.dow
  ORDER BY by_dow.dow;

In Django 1.4 I've defined a simple model that uses that view as it's datasource:
class ValidLoginsDowPopularity(models.Model):
    class Meta:
        db_table = 'valid_logins_dow_popularity'
        managed = False

    logins_avg = models.FloatField(
                            db_column='logins_avg')
    # Day of Week (dow)
    dow = models.IntegerField(db_column='dow',
                              primary_key=True)

    def __unicode__(self):
        return u"%d : " % (self.dow, self.logins_avg )

When I grab the data directly from the DB I get one set of numbers:
SELECT "valid_logins_dow_popularity"."logins_avg", "valid_logins_dow_popularity"."dow"
  FROM "valid_logins_dow_popularity";

    logins_avg    | dow
------------------+-----
 28.8571428571429 |   0
 95.1428571428571 |   1
 91.4285714285714 |   2
           89.625 |   3
 82.6666666666667 |   4
 61.4285714285714 |   5
 28.4285714285714 |   6
(7 rows)

When I get the data through the Django model I get a somewhat vaguely related, but different set of numbers:
In [1]: from core.models import *

In [2]: v = ValidLoginsDowPopularity.objects.all()

In [3]: for i in v:
    print "logins_avg : %f | dow : %d" % (i.logins_avg, i.dow)
   ...:
logins_avg : 25.857143 | dow : 0
logins_avg : 85.571429 | dow : 1
logins_avg : 89.571429 | dow : 2
logins_avg : 86.375000 | dow : 3
logins_avg : 83.000000 | dow : 4
logins_avg : 67.000000 | dow : 5
logins_avg : 28.000000 | dow : 6

To date, I've verified the sql that Django generates, when run directly from psql returns the expected output.  I've likewise tried with the Django model using a IntegerField, FloatField and DecimalField for the logins_avg attribute -- all have the same, but incorrect values. I've also written a simple test program to bypass the Django code and make sure it isn't a psycopg2 issue:
import psycopg2

def main():
    conn_string = "dbname='********' user='*********'"

    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()

    sql = "select * from valid_logins_dow_popularity"
    cursor.execute(sql)

    for rec in cursor.fetchall():
        print rec

if __name__ == '__main__':
    main()

Which, when run give the correct fault, so psycopg2 seems to be doing the right thing:
$ python test_psycopg2.py
(28.8571428571429, 0.0)
(95.1428571428571, 1.0)
(91.4285714285714, 2.0)
(89.625, 3.0)
(82.6666666666667, 4.0)
(61.4285714285714, 5.0)
(28.4285714285714, 6.0)

How is this possible?  Any clues would be appreciated.  Where could I dig into the Django code and see where things go wrong?  Should I report this issue with the Django Project?
Comment: What is the database type of the logins_avg field in your view/table?  I suspect the conversion from that to the FloatField type is not working correctly.
Comment: Good idea.  I've edited the question to have those details, but I've also tried to cast the login_avg column to be an int, updated the model to IntegerField, and still there were odd value differences.
Comment: FloatField should map correctly to "double precision"...what python db engine are you using?  postgresql_psycopg2?   you could also maybe try a DecimalField instead of FloatField and see if that changes anything
Comment: psycopg2==2.4.5  I just converted the model over DecimalField and get the exact same (incorrect) values.
Comment: django code is at https://github.com/django/django/tree/1.4.1
Answer: Redefine the view and cast the value to a numeric instead of a double. In the Django model you need a DecimalField that matches the Postgres numeric (like numeric(15,10) -> DecimalField(max_digits=15, decimal_places=10)).
I've never had any luck at all with floating point values between Django and the db and have had similar float weirdness problems with other software talking to databases before as well. Doing numeric <-> DecimalField is the only way I've found to guarantee floating point values don't get weird -- by changing them into fixed-point values.


Unable to change date format on node created field

Question: On my article content type, I enabled "Display author and date information" but am unable to change the date format.
I'm using Druapl 8.0.0-beta14 with a sub-theme based on Classy. The field's value is already computed by the time the twig template and hook_preprocess_field get to it but was able to chase down the setting of the date format to the defaultSettings method in TimestampFormatter.php using a debugger.
<code>    public static function defaultSettings() {
      return array(
        'date_format' => 'medium',
        'custom_date_format' => '',
        'timezone' => '',
      ) + parent::defaultSettings();
    }
</code>
So far, I haven't found a place in the admin UI or yaml files (or a hook, which I know I probably shouldn't be doing too much of in D8) where the date format can be changed. Interestingly enough, this "field" on the node seems to be some sort of pseudo-field, because the value is actually the timestamp on the revision_timestamp field in the node_revision table.
That said, how can I change the date format for this "field"?
Comment: I would suggest you open a core issue and add ->setDisplayConfigurable('view', TRUE); to the created field definition in Node::baseFieldDefinitions(). With that, it will show up in the manage display screen and becomes easy to configure. Not sure why this isn't done at the moment.
Answer: One way to do this is using a preprocess hook in your .theme file. There you can do pretty much anything with that variable.
Here an example:
<code>function [theme_name]_preprocess_node(&$variables) {
  if ($variables['display_submitted']) {

    // Getting the node creation timestamp from the node object.
    $date = $variables['node']->getCreatedTime();

    // Here you can use drupal's format_date() function, or some custom php date formatting.
    $variables['date'] = format_date($date, 'medium');
  }
}
</code>
In an earlier beta, before being able to alter the 'date' variable, I had to  first pass the string through the create() method of the SafeString class like this:
<code>$variables['date'] = \Drupal\Core\Render\SafeString::create('your dangerous new date string')
</code>
This might not be necessary anymore, concidering all the recent fuss around the safe string functions.
Edit: I still need to do that in beta15.


JLabel not added to JPanel

Question: I have this class, which should add a JLabel to a JPanel, but for some reason it isn't doing that. Why is it not adding the JLabel to the JPanel? This takes place in my SwigWorker class in the done() method
package sscce;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class sscce extends javax.swing.JFrame{
    protected XML xml = new XML();

    public sscce(){
        initComponents();
        GetNotes getNotes = new GetNotes();
        getNotes.execute();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        notesPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout notesPanelLayout = new javax.swing.GroupLayout(notesPanel);
        notesPanel.setLayout(notesPanelLayout);
        notesPanelLayout.setHorizontalGroup(
            notesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 494, Short.MAX_VALUE)
        );
        notesPanelLayout.setVerticalGroup(
            notesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 433, Short.MAX_VALUE)
        );

        jScrollPane1.setViewportView(notesPanel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    public static void main(String args[]){
        try{
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }catch(  ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex){
            java.util.logging.Logger.getLogger(sscce.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable(){
            public void run(){
                new sscce().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel notesPanel;
    // End of variables declaration

    public class GetNotes extends SwingWorker{

        protected ArrayList<XML> notes;

        @Override
        public void done(){
            System.out.println(notes.size());
            for(XML note : notes){
                String n = note.getNode("notes", "note");
                System.out.println(n);
                JLabel lbl = new JLabel(n);
                lbl.setVisible(true);
                notesPanel.add(lbl);
            }
        }

        @Override
        public String doInBackground(){
            String xmlStr = "<?xml version=\"1.0\"?>"
                    + "<root>"
                    + "    <success>true</success>"
                    + "    <notes>"
                    + "        <note>Note 1</note>"
                    + "    </notes>"
                    + "    <notes>"
                    + "        <note>Note 2</note>"
                    + "    </notes>"
                    + "    <notes>"
                    + "        <note>Note 3</note>"
                    + "    </notes>"
                    + "</root>";
            xml.parse(xmlStr);
            notes = xml.getNodes("root", "notes");
            return null;
        }
    }
}

class XML{

    private Document doc;

    public XML(){
    }

    public void parse(String xml){
        try{
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));

            doc = db.parse(is);
        }catch(ParserConfigurationException | SAXException | IOException ex){
            //Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Document getDoc(){
        return this.doc;
    }

    public ArrayList<XML> getNodes(String root, String name){
        ArrayList<XML> elList = new ArrayList<>();
        NodeList nodes = doc.getElementsByTagName(root);
        for(int i = 0; i < nodes.getLength(); i++){
            Element element = (Element)nodes.item(i);
            NodeList nl = element.getElementsByTagName(name);
            for(int c = 0; c < nl.getLength(); c++){
                Element e = (Element)nl.item(c);
                String xmlStr = this.nodeToString(e);
                XML xml = new XML();
                xml.parse(xmlStr);
                elList.add(xml);
            }
        }
        return elList;
    }

    private String nodeToString(Node node){
        StringWriter sw = new StringWriter();
        try{
            Transformer t = TransformerFactory.newInstance().newTransformer();
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            t.transform(new DOMSource(node), new StreamResult(sw));
        }catch(TransformerException te){
            System.out.println("nodeToString Transformer Exception");
        }
        return sw.toString();
    }

    public String getNode(String root, String name){
        NodeList nodes = doc.getElementsByTagName(root);
        for(int i = 0; i < nodes.getLength(); i++){
            Element element = (Element)nodes.item(i);

            NodeList n = element.getElementsByTagName(name);
            Element e = (Element)n.item(0);
            return getCharacterDataFromElement(e);
        }
        return "";
    }

    public static String getCharacterDataFromElement(Element e){
        Node child = e.getFirstChild();
        if(child instanceof CharacterData){
            CharacterData cd = (CharacterData)child;
            return cd.getData();
        }
        return "";
    }
}

Comment: Start by changing the layout manager for the `notesPanel` to something other then `GroupLayout` - this layout manager really isn't meant to be handled by hand.
Comment: I have tried: Gridbag, flow, box, and none of them have worked.
Comment: See my answer, also +1 for a running example, thank you
Answer: 1- Change the layout manager for the notesPanel.  GroupLayout really isn't meant for hand coding like this.  In my test, I used FlowLayout.
//        javax.swing.GroupLayout notesPanelLayout = new javax.swing.GroupLayout(notesPanel);
//        notesPanel.setLayout(notesPanelLayout);
//        notesPanelLayout.setHorizontalGroup(
//                    notesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
//                .addGap(0, 494, Short.MAX_VALUE));
//        notesPanelLayout.setVerticalGroup(
//                    notesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
//                .addGap(0, 433, Short.MAX_VALUE));
        notesPanel.setLayout(new FlowLayout());

2- Add a call to JComponent#validate after you've finished adding the labels.
System.out.println(notes.size());
for (XML note : notes) {
    String n = note.getNode("notes", "note");
    System.out.println(n);
    JLabel lbl = new JLabel(n);
    lbl.setVisible(true);
    notesPanel.add(lbl);
}
notesPanel.validate();

This should encourage the frame to re-layout it's child components.

JLabel not added to JPanel